SQL PDF
SQL PDF
Basics
Dr. Sanjeev
Verma
IMS, University of
Lucknow, Lucknow -
226021
What is
SQL stands forStructured Query
• SQL?
Language. It is used for storing and
managing data inRelational Database
Management System (RDBMS).
•
Itis a standard language for Relational
Database
• System. It enables a user tocreate,
read, update
and deleterelational databases
• andtables.
Allthe RDBMS likeMySQL, Informix,
Oracle, MS Access and SQL
Serveruse SQL as their standard
database language.
What are the SQL?
SQL follows the following
rules:
• Structure query language is not case sensitive.
Generally, keywords of SQL are written
inuppercase.
•
Statementsof SQL are dependent on text lines.
• We can
use a single SQL statement on one or multiple
textline.
most of the
actions in adatabase.
What is SQL
When an SQL command is executing for
Process?
•
any RDBMS, then the system figure out the
best way to carry out the request and the
SQL engine determines that how to
interpret the task.
•In the process, various components are
These components can be optimization
Engine, Query
included.
engine, Query dispatcher, classic, etc.
•
All the non-SQL queries are handled by the
classic
query engine, but SQL query engine won't
handle
What is SQL
Process?
What isAdvantages
•
ofSQL?
High speed No
coding needed
• Well defined
standards
• Portability
Interactive
• language Multiple
data view
•
•
What
SQLDatatypeis used to define the values
isSQLDatatype?
•
that a column cancontain.
Everycolumn is required to have a name
and data
• type in the database table.
SQL
SQL commands are instructions. It is used to
Commands
•
communicate with the database. It is also
used to perform specific tasks, functions,
and queries of data.
• SQL can perform various tasks like create a
table, add
data to tables, drop the table, modify the
table, set
permission for users.
Types of SQL
• There are five types of SQL commands: DDL,
Commands
DML, DCL, TCL, and DQL.
Data Definition Language
• DDLchanges the structure of the table
(DDL)
likecreating a table, deleting a table,
altering a table,etc.
•
Allthe command of DDL are auto-
• committed that
means it permanently save all the changes
in the
database.
Hereare some commands that come under
DDL:
CREATE
ALTER
Data Definition Language (DDL)-
CREATE
CREATEIt is used to create a new table in the
database.
REATE TABLE TABLE_NAME (COLUMN_NAME
Syntax:
DATATYPES[,....]);
Examp
CREATE TABLE EMPLOYEE(Name VARCHAR2(20),
Email VARCHA
le:
R2(100), DOB DATE);
Data Definition Language
(DDL)-Drop
Drop: Itis used to delete both the structure
andrecord storedin the table.
Syntax:
DROP
TABLE ;
Examp
le: DROP TABLE
EMPLOYEE;
Data Definition Language (DDL)-
ALTER
ALTER:It is used to alter the structure of the database.
This change could be either tomodifythe
characteristics of an existing attribute or probably
toadd a newattribute.
Synt
ALTER TABLE table_name ADD column_name
ax:COLUMN-definition; ALTER TABLE MODIFY(COLUMN
DEFINITION....);
Examp
le: ALTER TABLE STU_DETAILS ADD(ADDRESS
VARCHAR2(20)); ALTER TABLE STU_DETAILS
MODIFY (NAME VARCHAR2(20));
Data Definition Language TRUNC
(DDL)- ATEthe
TRUNCATE:It is used todelete all the rowsfrom
committedthat
means it can't permanently save all the
changes
Hereare someincommands
the that come
DML:
under
database.
INSERT They can be rollback.
UPDATE
DELETE
Data ManipulationLanguage-
INSERT
INSERT:The INSERT statement is a SQL query. It is
used to insert data into the row of a table.
INSERTINTO TABLE_NAME
Syntax:
(col1,col2,col3,....colN)
VALUES (value1, value2, value3, ....
valueN); O
INSERT INTO VALUES (value1, value2, value3, ....
TABLE_NAME R
valueN);
Examp
le: INSERT INTO XYZ (Author, Subject) VALUES
("Sonoo", "DBMS");
Data ManipulationLanguage-
UPDATE
Update: Thiscommand is used toupdate or
modifythe value of a column in the table.
UPDATE table_name SET [column_name1=
Syntax:
value1,...column_n ameN = valueN] [WHERE
CONDITION]
Examp
UPDATE
students
le: SET User_Name =
'Sonoo'
WHERE Student_Id =
'3'
Data Control Language
DCL commands are used
toGRANTandTAKE BACK authorityfrom any
database user.
e
Data ControlLanguage-Grant
GRANT:It is used to give user access privileges to
a database.
Examp
GRANT SELECT,
SOME_USER, UPDATE ON MY_TABLE TO
ANOT
le:
HER_USER;
from
Exampthe user.
USER1, USER2;
Transaction Control Language
TCL commands can onlyuse with DML
commands like INSERT, DELETE and UPDATE
only.
These operations are automatically
committed in the
database that's why they cannot be used
while creating
COMMIT
tables or dropping them.
are some commands that come under
Here
ROLLBACK
TCL:
SAVEPOINT
Transaction Control COMMI
Language- command is used to saveTall the
Commit:Commit
transactions to the database.
Syntex:
COMMI
T;
Examp
le: DELETE FROM
CUSTOMERS
WHERE AGE = 25;
COMMIT;
Transaction Control Rollba
Language-
Rollback:Rollback ckused to
SAVEPOINT:It is
command is used to roll the transaction back
undo transactions that to a certain point without
have not already been rolling back the entire
saved to the database. transaction.
Syntex:
ROLLBA Syntex:
SAVEPOINT
CK; SAVEPOINT_NA ME;
Examp
DELETE FROM
CUSTOMERS
le:
WHERE AGE = 25;
ROLLBACK;
Data QueryLanguage
DQL is used to fetch the data from the
database. It uses only one command: SELECT
a.SELECT:This is the same as the projection
operation of
relational algebra. It is used to select the
attribute based on
theconditiondescribed by WHERE clause.
Synt
SELECTexpressions
conditions; FROMTABLES WHERE
ax:
Examp
SELECT emp_name FROM employee WHERE
age > 20;
le:
SQL
Operator
SQL Comparison
Operat Description
Operators:
or It adds the value of both
+ operands.
It is used to subtract the right-hand operand from
the left-hand
- operand.
right-hand
/ operand.
right-hand
operand and returns reminder.
SQL Arithmetic
Operators
Operat Descript
or It
ionchecks if two operands values are equal or not, if the
= values are quealthen condition becomes true.
operand value, if
> yes then condition becomes true.
SQL Arithmetic
Operators
Operat Descript
or ion
It checks if the left operand value is less than or equal to
< the right operand value, if yes then condition becomes
true.
= It checks if the left operand value is not less than the
! right operand
value, if yes then condition becomes true.
< It checks if the left operand value is not greater than the
! right operand
value, if yes then condition becomes true.
>
SQLLogical
Operators
Operat Descript
or All It
ioncompares a value to all values in another value set.
• from one
or more tables present in the database.
on certain
condition or all the rows of a table.
Creating view
Aview can be created using theCREATE
VIEWstatement. We can create a view from a single
table or multiple tables.
Syntax
CREATE VIEW
view_name AS SELECT
column1, column2.....
FROM table_name
WHEREcondition;
Creating View from a
single table
CREATE VIEW
DetailsView AS
SELECTNAME,ADDRESS
FROM
WHEREStudent_Details
STU_ID < 4;
Creating View from multiple
tables
View from multiple tables can be created by simply
include multiple tables in the SELECT statement.
In the given example, a view is created
namedMarksViewfrom
two tablesStudent_DetailandStudent_Marks.
CREATE VIEW MarksView AS SELECT Student_Detail.NAME,
Student_Detail.ADDRESS, Student_Marks.MARKS FROM
Student_Detail, Student_Mark WHERE Student_Detail.NAME =
Student_Marks.NAME;
SELECT * FROM
MarksView;
DROP VIEW
view_name;
SQL
Indexes are special lookup tables. It is used to
Index
•
retrieve data from the database very fast.
An Index is used to speed up select queries and
where clauses.
• But it shows down the data input with insert and
update
• statements. Indexes can be created or dropped
without
affecting the data.
Create
An index in a database is just like an index in the
Indexstatement
CREATE INDEX index_name ON
back
book.of a
table_name (column1,
column2, ...);
Unique Index
statement
CREATE UNIQUE INDEX index_name ON table_name
Syntax(column1, colum
n2,...);
CREATE UNIQUE INDEX websites_idx ON websites
Example
(site_name);
Drop Index
Synt
Statement
ax DROP INDEX
Exam index_name;
ple DROP INDEX
websites_idx;
SQL Sub Query
ASubqueryis a query within another SQL query and
embedded within the WHERE clause.
Important Rule:
• Asubquerycan be placed in a number of SQL clauses like
WHERE clause, FROM clause, HAVINGclause.
Youcan useSubquerywith SELECT, UPDATE, INSERT, DELETE
statements
• along with the operators like =, <, >, >=, <=, IN,
BETWEEN,etc.
• is known as
the main query, and the inner query is known as asubquery.
•
Subquerieswith the Select
Statement
SQLsubqueriesare most frequently used with theSelect
SELECT column_name FROM table_name
statement. Syntax: expression operator
WHERE column_name
( SELECT column_name from table_name
WHERE ... );
Examp
le: SELEC
TF
* ROM EMPLOYEE
WHEREIDIN(SELECT
ID FROM EMPLOYEE
WHERESALARY>
4500);
Subquerieswith the INSERT
• SQLsubquerycan also be used with the Insert statement. In
Statement
the insert statement, data returned from thesubqueryis used
to insert into another table.
• In thesubquery, the selected data can be modified with any
of the
character, date functions.
Synt
INSERT INTO table_name (column1, column2,
ax:column3....)
SELECT * FROM table_name WHERE VALUE
OPERATOR
Examp
INSERT INTO
EMPLOYEE_BKP
le: SELECT * FROM
WHEREIDIN(SELECT
ID
EMPLOYEE
FROM
EMPLOYEE);
Subquerieswith theUPDATE
Statement
Thesubqueryof SQL can be used in conjunction with
the Update statement. Whenasubqueryis used with
the Update statement, then either single or multiple
UPDATEtable SETcolumn_name=new_value
columns in a table can be updated.
WHEREVALUEOPERATOR
(SELECTCOLUMN_NAME FROMTABLE_NAME
Syntax:
Example:
WHEREcondition);
Let's assume we have an EMPLOYEE_BKP table
available which is backup of
EMPLOYEE table. The given example updates the SALARY
by .25 times in the
EMPLOYEE table for all employee whose AGE is greater than or
UPDATEEMPL
equal toSET
OYEE 29. SALARY =
SALARY
WHERE
* 0.25AGE IN (SELECT AGE FROM
CUSTOMERS_BKP
WHERE AGE
>= 29);
Subquerieswith theDELETE
Statement
Thesubqueryof SQL can be used in conjunction with
the Delete statement just like any other statements
DELETE FROM TABLE_NAME WHERE
mentioned above.
VALUE(SELECT
OPERATOR
COLUMN_NAME FROM TABLE_NAME
Syntax:
Example:WHERE
Let's assume
condition);
we have an EMPLOYEE_BKP table
available which is backup of
EMPLOYEE table. The given example deletes the records from
the EMPLOYEE
table for all EMPLOYEE whose AGE is greater than or equal to
29.
DELETE FROM
WHERE AGE IN (SELECT AGE FROM
EMPLOYEE_BKP
EMPLOYEE
WHERE AGE
>= 29 );
SQL
Clauses
GROUP
SQL GROUP BY statement is used to arrange
BYidentical data into groups.
•
COMPANY
HAVING COUNT(*)>2;
SUMFUNCTI
ON
• Sum function is used to calculate the sum of
all selected columns. It works on numeric
fields only.
Synt
ax SUM() or SUM( [ALL|
Exam
DISTINCT]expression )
SELECT SUM(COST) FROM
SUM() with
ple
WHERE
PRODUCT_MAST;
SELECTSUM(COST) FROMPRODUCT_MAST
SUM() with
GROUP BY
WHEREQTY>3;
SELECTSUM(COST) FROM PRODUCT_MAST
WHEREQTY>3
SUM() withBY COMPANY;
GROUP
SELECTCOMPANY,SUM(COST)FROMPRODUCT_MASTGROUPB
YCOM
HAVING
PANY HAVING SUM(COST)>=170;
AVG
FUNCTION
• The AVG function is used to calculate the average
value of the numeric type. AVG function returns the
average of all non-Null values.
Synt
AVG() or AVG([ALL|
ax
Exam
DISTINCT]expression )
SELECTAVG(COST) FROM
ple
PRODUCT_MAST;
MAX
FUNCTION
• MAX function is used to find the maximum value of a certain
column. This function determines the largest value of all
selected values of a column.
Synt
ax MAX() or MAX([ALL|
Exam DISTINCT]expression )
ple SELECTMAX(RATE)
MIN FROMPRODUCT_MAST;
FUNCTION
• MIN function is used to find the minimum value of a certain
column. This
function determines the smallest value of all selected
Synt
values of a column
MIN() or MIN([ALL|
ax DISTINCT]expression )
Exam
SELECTMIN(RATE) FROM
PRODUCT_MAST;
ple
SQL JOIN
SQL, JOIN means "to combine two or more tables". InSQL, JOIN
clause is used to combine the records from two or more tables in
adatabase.
Typesof
SQLJOIN
INNER
JOIN
LEFT
JOIN
RIGHT
JOIN
FULL
JOIN
INNER JOIN
InSQL, INNER JOIN selects records that have matching values in
both tables as long as the condition is satisfied. It returns the
combination of all rows from both the tables where the condition
satisfies.
Syntax
SELECT table1.column1, table1.column2,
table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column =
Examtable2.matching_column;
SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT
ple
FROM
INNER EMPLOYEE
JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
LEFT JOIN
The SQL left join returns all the values from left table and the
matching values from the right table. If there is no matching
join value, it will return NULL.
Syntax
SELECT table1.column1, table1.column2,
table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column =
Examtable2.matching_column;
SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT
ple
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the
rows of right table and the matched values from the left table. If
there is no matching in both tables, it will return NULL.
Syntax
SELECT table1.column1, table1.column2,
table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column =
Examtable2.matching_column;
SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT
ple
FROM
RIGHT EMPLOYEE
JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and
right outer join. Join tables have all the records from both tables.
It puts NULL on the place of matches not found.
Syntax
SELECT table1.column1, table1.column2,
table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column =
Examtable2.matching_column;
SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT
ple
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
SQL Set
Operation
TheSQL Set operation is used to combine
the two or more SQL SELECTstatements
Typesof Set
Union
Operation
UnionA
ll
Interse
ct
Minus
Union
• TheSQL Union operation is used to combine the result of two
Operation
• or more SQL SELECT queries.
In the union operation, all the number ofdatatypeand
•
columns must be
same in both the tables on which UNION operation is being
applied.