You are on page 1of 17

SELE SELECT column1, SELECT 

sta SELECT city FROM placeofinterest;


column2, ... FROM
CT table_name; tement is
used to
fetch data
from a
database.
WHE SELECT column1, WHERE cla SELECT * FROM placeofinterest WHERE
column2, ...FROM city == 'Rome' ;
RE table_name WHERE use is used
condition; to extract
only those
records
that fulfill a
specified
condition.
COU SELECT COUNT * FROM COUNT is a SELECT COUNT(country) FROM
table_name ; placeofinterest WHERE country='Canada';
NT function
that takes
the name
of a
column as
argument
and counts
the
number of
rows when
the column
is not
NULL.
DISTI SELECT DISTINCT DISTINCT f SELECT DISTINCT country FROM
columnname FROM placeofinterest WHERE type='historical';
NCT table_name; unction is
used to
specify that
the
statement
is a query
which
returns
unique
values in
specified
columns.
LIMIT SELECT * FROM LIMIT is a SELECT * FROM placeofinterest WHERE
table_name LIMIT number; airport="pearson" LIMIT 5;
clause to
specify the
maximum
number of
rows the
result set
must have.
INSE INSERT INTO table_name INSERT is INSERT INTO placeofinterest
(column1,column2,column3.. (name,type,city,country,airport)
RT .) used to VALUES('Niagara
VALUES(value1,value2,valu insert new Waterfalls','Nature','Toronto','Canada','Pearson'
e3...); rows in the );
table.
UPDA UPDATE table_name UPDATE us UPDATE placeofinterest SET name = 'Niagara
SET[[column1]=[VALUES]] Falls' WHERE name = "Niagara Waterfalls";
TE WHERE [condition]; ed to
update the
rows in the
table.
DELE DELETE FROM table_name DELETE sta DELETE FROM placeofinterest WHERE city
WHERE [condition]; IN ('Rome','Vienna');
TE tement is
used to
remove
rows from
the table
which are
specified in
the WHERE
condition.
CREATE CREATE TABLE table_name CREATE CREATE TABLE employee
(col1 datatype optional TABLE statement ( employee_id char(2)
TABLE keyword, col2 PRIMARY KEY,
datatype optional is to create the first_name varchar(30) NOT
keyword,col3 table. Each NULL, mobile int);
datatype optional keyword,..., column in the
coln datatype optional
keyword)
table is specified
with its name,
data type and an
optional keyword
which could
be PRIMARY
KEY, NOT NULL,
etc.,
ALTER ALTER TABLE table_name ALTER ALTER TABLE employee
ADD COLUMN TABLE statement ADD COLUMN income
TABLE - column_name_1 bigint;
ADD datatype....ADD COLUMN is used to add the
COLUMN column_name_n datatype; columns to a
table.
ALTER ALTER TABLE table_name ALTER TABLE ALTER TABLE employee
ALTER COLUMN ALTER ALTER COLUMN mobile
TABLE - column_name_1 SET DATA COLUMN statemen SET DATA TYPE
ALTER TYPE datatype; CHAR(20);
t is used to
COLUMN
modify the data
type of columns.
ALTER ALTER TABLE table_name ALTER TABLE ALTER TABLE employee
DROP COLUMN DROP DROP COLUMN mobile ;
TABLE - column_name_1 ; COLUMN statemen
DROP
t is used to
COLUMN
remove columns
from a table.
ALTER ALTER TABLE table_name ALTER TABLE ALTER TABLE employee
RENAME COLUMN RENAME RENAME COLUMN
TABLE - current_column_name TO COLUMN statemen first_name TO name ;
RENAME new_column_name;
t is used to
COLUMN
rename the
columns in a
table.
TRUNCATE TRUNCATE TABLE TRUNCATE TRUNCATE TABLE
table_name IMMEDIATE; TABLE statement employee IMMEDIATE ;
TABLE
is used to delete
all of the rows in a
table. The
IMMEDIATE
specifies to
process the
statement
immediately and
that it cannot be
undone.
DROP TABLE DROP TABLE table_name ; Use the DROP DROP TABLE employee ;
TABLEstatement
to delete a table
from a database.
If you delete a
table that
contains data, by
default the data
will be deleted
alongside the
table.
LIKE SELECT column1, LIKE operator is used in SELECT f_name ,
column2, ... FROM l_name FROM
table_name WHERE a WHERE clause to employees WHERE
columnN LIKE pattern; search for a specified address LIKE '%Elgin,IL
pattern in a column. %';
There are two wildcards
often used in
conjunction with the LIKE
operator which are
percent sign(%) and
underscore sign (_).
BETWEEN SELECT column_name(s) The BETWEEN operator SELECT * FROM
FROM table_name employees WHERE
WHERE column_name selects values within a salary BETWEEN 40000
BETWEEN value1 AND given range. The values AND 80000;
value2; can be numbers, text, or
dates.
The BETWEENoperator is
inclusive: begin and end
values are included.
ORDER BY SELECT column1, ORDER BY keyword is SELECT f_name,
column2, ... FROM l_name, dep_id FROM
table_name ORDER BY used to sort the result- employees ORDER BY
column1, column2, ... ASC| set in ascending or dep_id DESC, l_name;
DESC; descending order. The
default is ascending.
GROUP BY SELECT column_name(s) GROUP BY clause is used SELECT dep_id,
FROM table_name COUNT(*) FROM
WHERE condition GROUP in collaboration with the employees GROUP BY
BY column_name(s) SELECT statement to dep_id;
ORDER BY arrange identical data
column_name(s);
into groups.

COUNT SELECT COUNT function SELECT COUNT(dep_id)


COUNT(column_name) FROM employees;
FROM table_name WHERE returns the
condition; number of rows
that matches a
specified
criterion.
AVG SELECT AVG function SELECT AVG(salary) FROM
AVG(column_name) FROM employees;
table_name WHERE returns the
condition; average value of
a numeric
column.
SUM SELECT SUM function SELECT SUM(salary) FROM
SUM(column_name) FROM employees;
table_name WHERE returns the total
condition; sum of a numeric
column.
MIN SELECT MIN(column_name) MIN function SELECT MIN(salary) FROM
FROM table_name WHERE employees;
condition; returns the
smallest value of
the SELECTed
column.
MAX SELECT MAX function SELECT MAX(salary) FROM
MAX(column_name) FROM employees;
table_name WHERE returns the
condition; largest value of
the SELECTed
column.
ROUND SELECT ROUND(2number, ROUND function SELECT ROUND(salary)
decimals, operation) AS FROM employees;
RoundValue; rounds a number
to a specified
number of
decimal places.
LENGTH SELECT LENGTH function SELECT LENGTH(f_name)
LENGTH(column_name) FROM employees;
FROM table; returns the length
of a string (in
bytes).
UCASE SELECT UCASE function SELECT UCASE(f_name)
UCASE(column_name) FROM employees;
FROM table; that displays the
column name in
each table in
uppercase.
DISTINCT SELECT DISTINCT function SELECT
DISTINCT(column_name) DISTINCT(UCASE(f_name))
FROM table; is used to display FROM employees;
data without
duplicates.
DAY SELECT DAY function SELECT DAY(b_date) FROM
DAY(column_name) FROM employees where emp_id =
table returns the day of 'E1002';
the month for a
given date
CURREN SELECT (CURRENT DATE CURRENT DATE is SELECT YEAR(CURRENT
- COLUMN) FROM table; DATE - b_date) As AGE,
T DATE used to display CURRENT_DATE, b_date
the current FROM employees;
date.This can be
subtracted from
the previous date
to get the
difference.
Subquery SELECT column_name [, Subquery is a query SELECT emp_id, fmame, lname,
column_name ] FROM table1 within another salary FROM employees where
[, table2 ] WHERE salary < (SELECT AVG(salary)
column_name OPERATOR SQL query and FROM employees);
(SELECT column_name [, embedded within SELECT * FROM ( SELECT
column_name ] FROM table1 the WHERE emp_id, f_name, l_name, dep_id
[, table2 ] [WHERE]) FROM employees) AS emp4all;
clause.
A subquery is
used to return SELECT * FROM employees
data that will be WHERE job_id IN (SELECT
used in the main job_ident FROM jobs);
query as a
condition to
further restrict
the data to be
retrieved.
Implicit SELECT column_name(s) Implicit Inner SELECT * FROM employees,
FROM table1, table2 WHERE Joincombines the jobs where employees.job_id =
Inner table1.column_name = jobs.job_ident;
Join table2.column_name; two or more
records but
displays only
matching values
in both tables.
Inner join applies
only the specified
columns.
Implicit SELECT column_name(s) Implicit Cross SELECT * FROM employees,
FROM table1, table2; Join defines as a jobs;
Cross
Join Cartesian product
where the
number of rows
in the first table
multiplied by the
number of rows
in the second
table..

 CREATE VIEW  CREATE VIEW


view_name AS EMPSALARY AS
A  CREATE VIEW  is
SELECT column1, SELECT EMP_ID,
Create an alternative way
column2, ... of representing F_NAME, L_NAME,
View 
FROM table_name data that exists in B_DATE, SEX,
WHERE one or more tables. SALARY FROM
condition;    EMPLOYEES; 
 CREATE OR REPLACE
VIEW EMPSALARY AS
 CREATE OR SELECT EMP_ID,
REPLACE VIEW F_NAME, L_NAME,
view_name AS The  CREATE OR B_DATE, SEX,
Update SELECT column1, REPLACE  VIEW JOB_TITLE,
a View column2, ... command updates MIN_SALARY,
FROM table_name a view. MAX_SALARY FROM
WHERE EMPLOYEES, JOBS
condition;    WHERE
EMPLOYEES.JOB_ID =
JOBS.JOB_IDENT; 

Use the  DROP


Drop a  DROP VIEW VIEW  statement to  DROP VIEW
View view_name;    remove a view from EMPSALARY; 
the database. 

Stored Procedures in IBM Db2 using SQL


Stored  --#SET A  stored  --#SET
Procedures TERMINATOR @ procedure  is a TERMINATOR @
CREATE prepared SQL code CREATE
PROCEDURE that you can save, so PROCEDURE
the code can be
PROCEDURE_NAME reused over and RETRIEVE_ALL 
LANGUAGE over again.  LANGUAGE SQL
READS SQL
BEGIN  The default
DATA 
terminator for a
stored procedure is DYNAMIC RESULT
END
semicolon(;). To set SETS 1
@
a different
  BEGIN 
terminator we
use  SET DECLARE C1

TERMINATOR  clause CURSOR

followed by the WITH RETURN


terminator such as FOR 
‘@’. SELECT * FROM
PETSALE; 

OPEN C1; 
END
@

Stored Procedures in MySQL using


phpMyAdmin
A  stored
procedure  is a  DELIMITER //
DELIMITER //
prepared SQL code CREATE
that you can save, so
CREATE PROCEDURE
the code can be
PROCEDURE reused over and over RETRIEVE_ALL()
PROCEDURE_NAME again. 
BEGIN
Stored
BEGIN  The default terminator
Procedures
for a stored procedure SELECT * FROM
END // is semicolon (;). To set
PETSALE;
a different terminator
we
DELIMITER ;  END //
use  DELIMITER  clause
  followed by the
DELIMITER ;
terminator such as $$
or //.

Transactions with Db2


Com COMM A  COM  CREATE TABLE employee(ID INT, Name
mit IT; MIT VARCHAR(20), City VARCHAR(20), Salary
com
mand  comma INT, Age INT); 
 
nd  is INSERT INTO employee( ID, Name, City,
used Salary, Age) VALUES( 1, ‘Priyanka pal’,
to ‘Nasik’, 36000, 21), (2, ‘Riya chowdary’,
persist
the ‘Bangalor’, 82000, 29);
chang
es in SELECT *FROM employee;
the COMMIT;
databa
se. 

The
default
termin
ator
for a
COM
MIT
comm
and is
semico
lon (;).

As auto-commit is enabled by default, all


transactions will be committed. We need
to disable this option to see how
A  ROL
rollback works.
LBACK
For db2, we have to disable auto-commit
comma
manually. Click the gear icon located on
nd  is
the right side of the SQL Assistant
used
window. Next, select the “On Success”
to
rollbac drop-down and choose “commit after the
k the last statement in the script” Remember to
transa
save your changes!
ctions
which
are
ROLL
Rollb not
BACK saved
ack
com ; in the
mand  databa
  se. 

The
default
termin
ator
for a
ROLLB
ACK
comm
and is INSERT INTO employee VALUES (3, ‘Swetha
semico Tiwari’, ‘Kanpur’, 38000, 38);
lon (;).
SELECT *FROM employee;
ROLLBACK;
SELECT *FROM employee;

Transactions with MySQL


 CREATE TABLE
employee(ID INT,
Name VARCHAR(20),
City VARCHAR(20),
Salary INT, Age
INT);
START
A  COMMIT TRANSACTION;
command  is used
to persist the INSERT INTO
changes in the employee( ID,
COMMIT; database. 
Commit Name, City,
command  The default Salary, Age)
 
terminator for a VALUES( 1,
COMMIT ‘Priyanka pal’,
command is
semicolon (;). ‘Nasik’, 36000,
21), (2, ‘Riya
chowdary’,
‘Bangalor’,
82000, 29);

SELECT *FROM
employee;
COMMIT;

Rollback ROLLBACK; A  ROLLBACK As auto-commit


command  command  is used is enabled by
 
to rollback the default, all
transactions which transactions
are not saved in
the database.  will be
committed. We
The default need to disable
terminator for a
this option to
ROLLBACK
command is see how rollback
semicolon (;). works. For MySQL
use the command
“SET autocommit
= 0;”
INSERT INTO
employee VALUES
(3, ‘Swetha
Tiwari’,
‘Kanpur’, 38000,
38);

SELECT *FROM
employee;
ROLLBACK;
SELECT *FROM
employee;

Db2 Transactions using Stored Procedure


Commit –#SET TERMINATOR A  COMMIT  --#SET
command  @ command  is TERMINATOR @
used to persist CREATE PROCEDURE
CREATE PROCEDURE the changes in TRANSACTION_ROSE
PROCEDURE_NAME the database. 
LANGUAGE SQL
The default MODIFIES SQL
BEGIN 
terminator for a DATA 
COMMIT
COMMIT; BEGIN
command is
semicolon (;).
END DECLARE SQLCODE
@ INTEGER DEFAULT 0;
  DECLARE retcode
INTEGER DEFAULT 0;
DECLARE CONTINUE
HANDLER FOR
SQLEXCEPTION
SET retcode =
SQLCODE; 
UPDATE
BankAccounts
SET Balance =
Balance-200
WHERE AccountName
= ‘Rose’;
UPDATE
BankAccounts
SET Balance =
Balance-300
WHERE AccountName
= ‘Rose’;
IF retcode < 0
THEN
ROLLBACK WORK;
ELSE
COMMIT WORK;
END IF;

END
@

Rollback  --#SET A  ROLLBACK  --#SET


command  TERMINATOR @ command  is TERMINATOR @
CREATE PROCEDURE used to rollback CREATE PROCEDURE
PROCEDURE_NAME the transactions TRANSACTION_ROSE
which are not
saved in the LANGUAGE SQL
BEGIN 
database.  MODIFIES SQL
DATA 
ROLLBACK; The default
BEGIN
terminator for a
COMMIT; ROLLBACK
command is DECLARE SQLCODE
END semicolon (;). INTEGER DEFAULT 0;
@ DECLARE retcode
  INTEGER DEFAULT 0;
DECLARE CONTINUE
HANDLER FOR
SQLEXCEPTION
SET retcode =
SQLCODE; 
UPDATE
BankAccounts
SET Balance =
Balance-200
WHERE AccountName
= ‘Rose’;
UPDATE
BankAccounts
SET Balance =
Balance-300
WHERE AccountName
= ‘Rose’;
IF retcode < 0
THEN
ROLLBACK WORK;
ELSE
COMMIT WORK;
END IF;

END
@

MySQL Transactions using Stored Procedure


Commit DELIMITER // A  COMMIT  DELIMITER //
command  command  is CREATE PROCEDURE
CREATE PROCEDURE used to persist TRANSACTION_ROSE()
PROCEDURE_NAME the changes in
the database.  BEGIN
BEGIN 
The default
DECLARE EXIT
COMMIT; terminator for
a COMMIT HANDLER FOR
command is SQLEXCEPTION
END //
semicolon (;). BEGIN
DELIMITER ;  ROLLBACK;
RESIGNAL;
 
END; 
START TRANSACTION;
UPDATE BankAccounts
SET Balance =
Balance-200
WHERE AccountName =
‘Rose’;
UPDATE BankAccounts
SET Balance =
Balance-300
WHERE AccountName =
‘Rose’;
COMMIT; 

END //

DELIMITER ;

 DELIMITER //
CREATE PROCEDURE
TRANSACTION_ROSE()

BEGIN

DECLARE EXIT
HANDLER FOR
DELIMITER // SQLEXCEPTION
A  ROLLBACK
BEGIN
CREATE PROCEDURE command  is
ROLLBACK;
PROCEDURE_NAME used to
rollback the RESIGNAL;
BEGIN  transactions END; 
which are not START TRANSACTION;
Rollback ROLLBACK; saved in the
UPDATE BankAccounts
command  database. 
SET Balance =
COMMIT;
The default Balance-200
terminator for
END // WHERE AccountName =
a ROLLBACK
command is ‘Rose’;
DELIMITER ;  semicolon (;). UPDATE BankAccounts
SET Balance =
 
Balance-300
WHERE AccountName =
‘Rose’;
COMMIT; 

END //

DELIMITER ;

Cros SELECT The CROSS SELECT DEPT_ID_DEP, LOCT_ID FROM


column_name(s) FROM DEPARTMENTS CROSS JOIN LOCATIONS;
s table1 CROSS JOIN JOIN is
Join table2; used to
generate a
paired
combinatio
n of each
row of the
first table
with each
row of the
second
table.
Inner SELECT You can select E.F_NAME,E.L_NAME,
column_name(s) FROM JH.START_DATE from EMPLOYEES as E
Join table1 INNER JOIN use an inner INNER JOIN JOB_HISTORY as JH on
table2 ON join in a E.EMP_ID=JH.EMPL_ID where E.DEP_ID ='5';
table1.column_name = SELECT
table2.column_name;
WHERE condition;
statement
to retrieve
only the
rows that
satisfy the
join
conditions
on every
specified
table.
Left SELECT The LEFT select
column_name(s) FROM OUTER E.EMP_ID,E.L_NAME,E.DEP_ID,D.DEP_NAM
Oute table1 LEFT OUTER E from EMPLOYEES AS E LEFT OUTER JOIN
r JOIN table2 ON JOIN will DEPARTMENTS AS D ON
Join table1.column_name = return all E.DEP_ID=D.DEPT_ID_DEP;
table2.column_name records
WHERE condition;
from the
left side
table and
the
matching
records
from the
right table.
Right SELECT The RIGHT select
column_name(s) FROM OUTER E.EMP_ID,E.L_NAME,E.DEP_ID,D.DEP_NAM
Oute table1 RIGHT OUTER E from EMPLOYEES AS E RIGHT OUTER JOIN
r JOIN table2 ON JOIN return DEPARTMENTS AS D ON
Join table1.column_name = s all E.DEP_ID=D.DEPT_ID_DEP;
table2.column_name records
WHERE condition;
from the
right table,
and the
matching
records
from the
left table.
Full SELECT The FULL select E.F_NAME,E.L_NAME,D.DEP_NAME
column_name(s) FROM OUTER from EMPLOYEES AS E FULL OUTER JOIN
Oute table1 FULL OUTER DEPARTMENTS AS D ON
r JOIN table2 ON JOIN clause E.DEP_ID=D.DEPT_ID_DEP;
Join table1.column_name = results in
table2.column_name the
WHERE condition;
inclusion of
rows from
two tables.
If a value is
missing
when rows
are joined,
that value
is null in
the result
table.
Self SELECT A self join is SELECT B.* FROM EMPLOYEES A JOIN
column_name(s) FROM EMPLOYEES B ON A.MANAGER_ID =
Join table1 T1, table1 T2 regular join B.MANAGER_ID WHERE A.EMP_ID = 'E1001';
WHERE condition; but it can
be used to
joined with
itself.
Joins in MySQL using phpMyAdmin

Full SELECT column_name(s) The UNION select


FROM table1 LEFT OUTER E.F_NAME,E.L_NAME,D.DEP_NAME
Outer JOIN table2 ON operator is used from EMPLOYEES AS E LEFT OUTER
Join table1.column_name = to combine the JOIN DEPARTMENTS AS D ON
table2.column_name result-set of E.DEP_ID=D.DEPT_ID_DEP
WHERE condition
two or more UNION
UNION SELECT
statements. select
SELECT column_name(s) E.F_NAME,E.L_NAME,D.DEP_NAME
FROM table1 RIGHT from EMPLOYEES AS E RIGHT
OUTER JOIN table2 ON OUTER JOIN DEPARTMENTS AS D
table1.column_name = ON E.DEP_ID=D.DEPT_ID_DEP
table2.column_name
WHERE condition

You might also like