SQL Complete
SQL Complete
L
Introductio
n
SQL (Structured Query Language)
– Statements data definitions, queries,
forupdates (both DDL
andand
DML)
– a•‘standard’ that specifies
how a relational schema is created
• data is inserted / updated in the relations
• data is queried
• transactions are started and stopped
• programs access data in the relations and
a host of other things are done
• DBMS software : SQL Server, SYBASE, Paradox, Informix, Oracle
History of
SQL
▪ SEQUEL
– developed by IBM in early 70’s
– relational query language as part of System-R project
at
IBM San Jose Research Lab.
– the earliest version of SQL
▪ SQL evolution
– ANSI (American National Standard Institute) and
the ISO (International Standard Organization)
Made standard
version of SQL in 1989 called SQL 89.
SQL Server Release
History
SQL Server Release History
Version Year Release Name
1.0 1989 SQL Server 1.0
1.1 1991 SQL Server 1.1
4.21 1993 SQL Server 4.21
6.0 1995 SQL Server 6.0
6.5 1996 SQL Server 6.5
7.0 1998 SQL Server 7.0
8.0 2000 SQL Server 2000
8.0 2003 SQL Server 2000
9.0 2005 SQL Server 2005
10.0 2008 SQL Server 2008
10.25 2010 SQL Azure DB
10.50 2010 SQL Server 2008 R2
11.0 2012 SQL Server 2012
12.0 2014 SQL Server 2014
13.0 2016 SQL server 2016
Components of SQL
Standard
▪ Data Definition Language(DDL)
– Specifies constructs for schema definition, relation
definition, integrity constraints, views and schema
modification.
▪ Transaction Control
– Specifies how transactions can be started / stopped, how a
set of
concurrently executing transactions can be managed.
▪ Authorization
– Specifies how to restrict a user / set of users to access only
certain
parts of data, perform only certain types of queries etc.
SQL Data Definition and
Data
▪ Terminology:
– Table, row, and column used for relational model
▪ CREATE statement
– Main SQL command for data definition
Data Definition in
SQL
Attribute Data Types in
SQL
▪ Basic data types
– Numeric data types
• Integer numbers: INTEGER,INT, and SMALLINT
• Floating-point (real) numbers: FLOAT or REAL, and
DOUBLE PRECISION
– Character-string data types
• Fixed length: CHAR(n), CHARACTER(n)
• Varying length: VARCHAR(n), CHAR
VARYING(n), CHARACTER VARYING(n)
Attribute Data Types in
SQL
▪ Boolean data type
– Values of TRUE or FALSE or NULL
▪ DATE data type
– Ten positions
– Components are YEAR, MONTH, and DAY in
the
form YYYY-MM-DD
Attribute Data Types in
SQL
▪ NOT NULL
– NULL is not permitted for a particular attribute
▪ Default value
– DEFAULT <value>
▪ CHECK clause
– CHECK clauses at the end of a
CREATE TABLE statement Apply to
each tuple individually
CHECK (Dnumber>0 AND Dnumber<21)
Specifying Key and Referential Integrity
Constraints
PRIMARY KEY clause
– Specifies one or more attributes that make • only one in a table
up • It never allows null
– the primary key of a relation values
– Ex : Dnumber INT PRIMARY KEY;
UNIQUE clause
– Specifies alternate (secondary)
• Can be more than one unique key in one
keys table.
– Dname VARCHAR(15) UNIQUE; • Unique key can have null values
Specifying Key and Referential Integrity
Constraints
Referential Integrity Constraints
Violation
▪ can occur if a referenced tuple is deleted or modified action
canspecified for each case using qualifiers ON
be or ON
DELETE UPDATE
▪ Actions
– three possibilities can be specified
▪ Example
We have STUDENT table with schema :
STUDENT(USN, NAME, gender, degree, deptno, advisor)
Create new table called CSSTUDENTS(USN, Name) and insert CS
student details from STUDENT table.
SELECT *
FROM Product
WHERE category=„Gadgets‟
Category
SELECT DISTINCT Gadgets
category FROM Product Photography
Household
Compare to:
Category
Gadgets
SELECT Gadgets
category FROM Photography
Product Household
Example Queries Involving a Single
Table
▪ Get the rollNo, name of all female students in the dept no.
5.
Select STUDENT.name,
DEPARTMENT.name FROM STUDENT,
DEPARTMENT
Where STUDENT.deptNo=DEPARTMENT.deptId
and
STUDENT.deptNo=4
Aliasing, Renaming and Tuple
Variables
▪ Select student name and department name for
DeptNo=4
Select S.name, D.name
FROM STUDENT AS S, DEPARTMENT AS D
Where S.deptNo=D.deptId and Aliasing
S.deptNo=4
▪ Get the rollNo, name of students in the CSE dept (deptNo= 3)
along
with their advisor’s name and phone number.
▪ Get the names, employee ID’s, phone numbers of
professors in CSE dept who joined before 1995.
Unspecified WHERE
Clause
▪ A missing WHERE clause indicates no condition on tuple
selection;
– All tuples of the relation specified in the FROM clause qualify
and are selected for the query result.
SELECT empId
FROM PROFESSOR;
– If more than one relation is specified in the FROM clause, then the
CROSS PRODUCT all possible tuple combinations of these
relations is selected
SELECT empId,deptId
FROM PROFESSOR,DEPARTMENT;
– all combinations of an PROFESSORE empId and a
DEPARTMENT deptId, regardless of whether the employee
works for the department or not
Unspecified WHERE
Clause
R U S returns relation instance containing all tuples that occur in either relation
instance R or S, or both.
Example using
INTERSECTION
(SELECT rollNo
FROM enrollment WHERE
courseId= „CS563‟ and sem= 5 and year = 2015)
INTERSECT
(SELECT rollNo
FROM enrollment WHERE
courseId= „CS561‟ and sem= 5 and year = 2014 );
(SELECT rollNo
FROM enrollment
WHERE sem= 5 and year = 2017 )
EXCEPT
(SELECT rollNo
FROM enrollment
WHERE courseId= „CS563‟and
sem= 5 and year = 2017);
R – S: returns a relation instance containing all tuples that occur
in R but not in S.
Substring Pattern Matching and Arithmetic
Operators
(a) ‘_ _ 91’ matches with any string ending with “91”, with any
two
characters before that.
SELECT Name
FROM STUDENT
WHERE Year LIKE „_ _ _ _ _ _ _ _ _12‟
SELECT
* Products
FROM PName LIKE
WHER ‘%gizmo%’
E
Use of ‘between
and’
Dr. Mahesha
Aggregation: Count
Dr. Mahesha
More Examples
SELECT Sum(price *
quantity) FROM Purchase
What do
they mean ?
SELECT Sum(price *
quantity) FROM Purchase
WHERE product = „bagel‟
Dr. Mahesha
Simple Aggregations
Purchase
Product Date Price Quantity
Bagel 10/21 1 20
Banana 10/3 0.5 10
Banana 10/10 1 10
Bagel 10/25 1.50 20
SELECT Sum(price *
quantity) FROM Purchase 50 (= 20+30)
WHERE product = „bagel‟
Dr. Mahesha
Grouping &
Aggregation
Dr. Mahesha
Grouping and Aggregation
Dr. Mahesha
Grouping and Aggregation
Dr. Mahesha
3. SELECT
Dr. Mahesha
Database schema for Online Book
Database
JOIN
S
▪ A query that combines tuple from two or more relations is
called as
join query
Dr. Mahesha
Join
▪ Sometimes, it is
examples
required to extract information from more
than two relations.
▪ In such case, more than two relations are required to be
joined
through join query.
▪ This can be achieved by specifying names of all the required
relations in FROM clause and specify join condition in
WHERE clause
▪ Ex. List title, category and price of all the books written by
author
Charles Smith
Dr. Mahesha
More Join
Examples
Dr. Mahesha
More Join
Examples
Dr. Mahesha
Nested Queries or
Subqueries
▪ Complex queries
– In Some queries, part of the computation is specified as
a separate query & the result be used in comparison
condition such queries can be formulated using nested
queries
Dr. Mahesha
Subqueries/Nested queries
• In the Sub query you may use the different operators to filter out the
result
like [=, >, =, <=, !=, ].
• These Sub queries can be used conjunction with INSERT, UPDATE
and DELETE queries.
Dr. Mahesha
Subquerie
▪ Suppose youwant s findthe name
to of the department
in which employee_id = 100 is currently working on.
SELECT department_name FROM department WHERE
department_id = (SELECT department_id
FROM employee WHERE employee_id = 100);
Dr. Mahesha
Join vs
Subqueries
▪ Joins and subqueries are both used to combine data from
different
tables intoa single result. They share many similarities
differences.
and
▪ But whether to use a JOIN or a sub-query is a tricky subject
discussed in many forums. Unfortunately, there is no definite
answer; very much dependent on the circumstances, data
involved, and the data system involved.
▪ Subqueries can be used to return either a scalar (single) value
or a
row set; whereas, joins are used to return rows.
▪ A common use for a subquery may be to calculate a summary
value for use in a query. For instance, we can use a subquery
to help us obtain all products that have a greater than average
product price.
Dr. Mahesha
Subquer
y
▪ A subquery is a SELECT statement written within
parentheses and nested inside another statement.
▪ Example:
SELECT department_name FROM department WHERE
department_id = (SELECT department_id
FROM employee WHERE employee_id = 100);
Dr. Mahesha
Nested query
operators
▪ IN – This operator is used to compare a value to a list of
literal
values that have been specified.
▪ ANY – This operator is used to compare a
value to any applicable value in the list as per the
condition.
▪ ALL – This operator is used to compare a value to all
values in another value set.
▪ EXISTS – This operator is used to search for the
presence of a row in a specified table that meets a
certain criterion.
Dr. Mahesha
Nested
Queries
▪ Comparison operator IN
– Example : Get the rollNo, name of students who have a lady
professor as their advisor.
SELECT s.usn,
s.name FROM
student s
WHERE s.advisor IN(SELECT eid
FROM professor
WHERE gender="F")
Dr. Mahesha
EXISTS
Operator
• EXISTS is used to check whether the result of a
correlated query is empty (contains no tuples) or
not (contains one or more tuples)
– Returns a Boolean result (TRUE or FALSE)
– Can be used in the WHERE-clause as a
condition
– EXISTS (Q) evaluates to TRUE if the result of Q
has one or more tuple; evaluates to FALSE if the
result of Q has no tuples
Dr. Mahesha
Correlated Nested
Queries
▪ Whenever a condition in the WHERE clause of a nested
query references some attribute of a relation declared in
the outer query, the two queries are said to be correlated.
▪ Correlated Subquery is a sub-query that uses values from
the outer query. In this case the inner query has to be
executed for every row of outer query.
SELECT eid,
name FROM
professor
WHERE EXISTS (SELECT *
FROM student
WHERE advisor=eid)
Dr. Mahesha
NOT EXISTS
Operator
Dr. Mahesha
Nested query
examples
Dr. Mahesha
Nested query
examples
▪ The IN operator can be used to compare a single value to
the set of multiple values
Dr. Mahesha
Nested query
examples
Dr. Mahesha
Nested query
examples
▪ EXISTS operator evaluates to true if a subquery returns at
least one tuple as result otherwise, it returns false value
Dr. Mahesha
Nested query
examples
▪ On the other hand, NOT EXIST operator evaluates to
true if
subquery returns no tuple as a result.
Dr. Mahesha
Group by and Having
clause
Dr. Mahesha
Having
clause
▪ HAVING is like a WHERE clause, except that it applies to
the
results of a GROUP BY query
▪ HAVING places conditions on groups, whereas, WHERE
clause used to place conditions on the individual tuples
▪ Another difference is that, condition specified in WHERE
clause cannot include aggregate functions, whereas,
HAVING clause can.
Dr. Mahesha
Where clause versus Having
clause
▪ Where clause
– Performs tests on rows and eliminates rows not
satisfying the specified condition
– Performed before any grouping of rows is done
▪ Having clause
– Always performed after grouping
– Performs tests on groups and eliminates
groups not satisfying the specified condition
– Tests can only involve grouping attributes
and aggregate functions
Dr. Mahesha
Group by and Having
clause
▪ List the book categories for which number of books published is
less
than 5
Dr. Mahesha
Modifying a Defined
Schema
▪ ALTER TABLE command can be used to modify a
schema
– Adding a new attribute
ALTER table student ADD address varchar(30);
– Deleting an attribute
• need to specify what needs to be done about constraints that refer
to the
attribute being dropped
– two possibilities
• CASCADE - delete the constraints also
• RESTRICT –do not delete the attributes if there are
some views/constraints that refer to it.
ALTER TABLE student DROP degree RESTRICT
Similarly,
Dr. Mahesha an entire table definition can be deleted
Modifying a Defined
Schema
▪ To rename table
ALTER TABLE table_name
RENAME TO new_table_name;
▪ To add a column to an existing table,
ALTER TABLE table_name
ADD column name column-definition;
▪ To modify a column in an existing table,
ALTER TABLE table_name
MODIFY column_name column_type;
Dr. Mahesha
View
▪ A view is a virtual
s
relation, whose
contents are derived
from already existing relation and it does not exist in
physical form
▪ The contents of views are determined by executing a
query based on any relation and it doesn't form the part
of database schema
▪ Each time a view is referred to, its contents are derived
from the relation on which it is based
▪ A view can be used like any other relation, it can be
queried
and joined with other relations or views
▪ These are very useful in the situation where only parts of
relations are to be accessed frequently instead of
Dr. Mahesha
VIE
WS
▪ CREATE VIEW command can be used for creating views
▪ This command provides the name to the view and specifies
the
list of attributes and tuples to be included using a subquery
Dr. Mahesha
VIE
WS
Dr. Mahesha
VIE
WS
▪ Now queries can be performed on these views
as they are performed on the other relations
Dr. Mahesha
VIE
▪
WS
Views can also be based on more than one
relation
▪ The views that are based on more than one relation are said to be complex
views
▪ These types of views are time consuming to execute, especially if multiple
queries are involved in view definition
▪ Since their contents are not physically stored, they are executed each and
every time they are referred to.
Dr. Mahesha
VIE
WS
Dr. Mahesha
Restrictions on Updating
Views
▪ Updates on views defined on joining of more than one
table are not allowed
▪ For example, updates on the following view are not
allowed
Dr. Mahesha
Restrictions on Updating
Views
▪ Updates on views defined with ‘group by’ clause and
aggregate functions is not permitted, as a tuple in view
will not have a corresponding tuple in base relation.
▪ For example, updates on the following view are not
allowed
Dr. Mahesha
Restrictions on Updating
Views
▪ Updates on views which do not include Primary Key of
base table, are also not permitted
Dr. Mahesha
Stored
Procedures
▪ Stored procedures are procedures or functions that are
stored and executed by the DBMS at the database server
machine.
▪ Procedures can be
dropped
Dr. Mahesha
Trigger
s
▪ Trigger is a type of stored procedure that is executed
automatically when some database related events like insert,
update, delete etc., occur.
Dr. Mahesha
Trigger
s
▪ Although triggers like constraints are defined to maintain
the database integrity, yet they are different in the
following ways
Dr. Mahesha
Trigger
s
Dr. Mahesha
Trigger
s
▪ FOR EACH ROW clause makes sure that trigger is executed for
every single tuple processed
▪ FOR EACH STATEMENT clause specifies the trigger is executed
only once
for specified statement
▪ REFERENCING NEW ROW AS clause can be used to create a
variable for storing the new value of an updated tuple
▪ BEFORE INSERT trigger to set the NULL value no matter what value
was
inserted by a user:
▪ AFTER INSERT trigger, the rows firstly inserted to the table, and
then they are updated.
Dr. Mahesha
Dr. Mahesha
Trigger
s
▪ Triggers can be enabled and disabled by using ALTER
TRIGGER command
▪ The triggers which are not required can be removed by
using DROP Trigger command
Dr. Mahesha
Exampl
e
Dr. Mahesha
Exampl
e
Dr. Mahesha
Dr. Mahesha
Dr. Mahesha
Dr. Mahesha
SAILORS ( sid, sname, rating,
age) BOATS (bid, bname,
color) RESERVES (sid, bid,
day)
Dr. Mahesha
Basic SQL
Queries
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)
Dr. Mahesha
UNION, INTERSECT and
EXCEPT
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)
Dr. Mahesha
Nested queries
Dr. Mahesha
Aggregate
operation
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)
Dr. Mahesha
Basic SQL
Queries
SAILORS ( sid, sname, rating, age)
BOATS (bid, bname, color)
RESERVES (sid, bid, day)
Dr. Mahesha
Dr. Mahesha
Dr. Mahesha
UNION, INTERSECT and
EXCEPT
Dr. Mahesha
UNION, INTERSECT and
EXCEPT
1. Find the names of sailors who have reserved a
red or a green boat
Dr. Mahesha
UNION, INTERSECT and
EXCEPT
2. Find the names of sailors who have reserved both
a red
and a green boat
Dr. Mahesha
UNION, INTERSECT and
EXCEPT
3. Find the sids of all sailors who have reserved red
boats but
not green boats
Dr. Mahesha
Nested queries
Dr. Mahesha
Set – Comparison
Operators
1. Find sailors whose rating is better
than some sailor called Horatio
Dr. Mahesha
Set – Comparison
Operators
2. Find the sailors with the highest
rating
Dr. Mahesha
Aggregate
operation
Dr. Mahesha