SQL INTRODUCTION
SQLstands for Structured Query Language
Standard language for querying and manipulating data
Data Definition Language (DDL)
Create/alter/delete tables and their attributes
Data Manipulation Language (DML)
Query one or more tables
Insert/delete/modify tuples in tables
Slide
8-2
Many standards out there: ANSI SQL, SQL92 (a.k.a. SQL2), SQL99 (a.k.a. SQL3), …
3.
TABLES IN SQL
DNameDnumber MgrSsn Mgrstartdate
Gizmo 19 324521 1992-08-11
Powergizmo 29 624545 1982-01-21
SingleTouch 1 986133 1912-04-02
MultiTouch 2 1123455 2002-08-28
Department
Attribute names
Table name
Tuples or rows
4.
CREATE TABLE
Createsa new relation(table) in the database
Specifies relation’s attributes and their data types
Specifies constraints such as NOT NULL , UNIQUE ,CHECK etc…
CREATE TABLE DEPARTMENT
(DNAME VARCHAR(10) NOT NULL ,
DNUMBER INTEGER CHECK(DNUMBER >0 AND DNUMBER
<25),
MGRSSN CHAR(9),
MGRSTARTDATE DATE
);
Slide
8-4
5.
CREATE SCHEMA
Specifiesa new database schema by giving it a name
Example:
CREATE SCHEMA COMPANY AUTHORIZATION
username;
Slide
8-5
6.
Data Types
Numeric
integer
Smallint
Floating point
Decimal(Precision, Scale)
Numeric(Precision,Scale)
Character String
Char(n)
Varchar(n)
Nvarchar(n)
Bit-String
Bolean
7.
ADDITIONAL DATA TYPES
DATE:
Made up of year-month-day in the format yyyy-mm-dd
TIME:
Made up of hour:minute:second in the format hh:mm:ss
TIME(i):
Made up of hour:minute:second plus i additional digits
specifying fractions of a second
format is hh:mm:ss:ii...i
TIMESTAMP:
Has both DATE and TIME components
Slide
8-7
8.
CREATE DOMAIN
Wecan declare a domain in SQL
This makes it easier to change the data type of
numerous attributes in a schema
Improves Schema readability
Not available in many SQL implementation like (T-SQL)
CREATE DOMAIN SSN_TYPE AS CHAR(9);
Slide
8-8
9.
CONSTRAINTS IN SQL
CREATE TABLE command allows us to specify the
primary key, secondary keys, and foreign keys.
Key attributes can be specified via the PRIMARY KEY and
UNIQUE phrases
CREATE TABLE DEPARTMENT
( DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9) NULL,
MGRSTARTDATE CHAR(9),
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE
); Slide
8-9
10.
REFERENTIAL INTEGRITY OPTIONS
We can specify RESTRICT, CASCADE, SET NULL or SET
DEFAULT on foreign keys.
CREATE TABLE DEPARTMENT
( DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9) ,
MGRSTARTDATE CHAR(9),
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE
ON DELETE SET DEFAULT ON UPDATE CASCADE
);
Slide
8-10
CASCADE : to delete a row with a key referenced by foreign keys in existing rows in
other tables, all rows that contain those foreign keys are also deleted.
DROP COMMAND
DropCommand is used to delete schema or named
schema elements such as table, domains, or constraints
Example:
DROP TABLE DEPENDENT;
DROP TABLE EMPLOYEE CASCADE;
DROP SCHEMA COMPANY;
Slide
8-15
In SQL-Server (T-SQL), DROP TABLE cannot be used to drop a table that is referenced by a
FOREIGN KEY. The referencing FOREIGN KEY or the referencing table must first be dropped.
16.
ALTER COMMAND
Thedefinition of table or named schema elements can be
changed using ALTER command
ALTER can be used to add an attribute to the relation
Initially, the new attribute will have NULLs in all the tuples of the
relation
NOT NULL constraint is not allowed for such an attribute
Example :
ALTER TABLE EMPLOYEE ADD COLUMN JOB VARCHAR(12);
T-SQL syntax
ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12);
The database user have to enter a value for the new attribute JOB for
each EMPLOYEE tuple. Slide
8-16
17.
ALTER TABLE
ALTERcommand can be use to add or drop constraints
Example :
ALTER TABLE EMPLOYEE add constraint unEmp UNIQUE(NAME) ;
ALTER TABLE EMPLOYEE drop constraint unEmp ;
Slide
8-17
18.
SQL QUERIES
Notsame as the SELECT operation of the relational algebra
The result can have duplicate tuples
SQL relation is a multi-set (bag) of tuples; not a set of tuples
Slide
8-18
SELECT <attributes>
FROM <one or more relations>
WHERE <conditions>
Basic form:
SIMPLE SQL QUERIES
Basic SQL queries correspond to using the SELECT, PROJECT, and
JOIN operations of the relational algebra
Retrieve the birthdate and address of the employee whose name is
'John B. Smith'.
SELECT BDATE, ADDRESS
FROM EMPLOYEE
WHERE FNAME='John' AND MINIT='B’
AND LNAME='Smith’
Similar to a SELECT-PROJECT pair of relational algebra operations
Slide
8-23
24.
JOIN OPERATION
Retrievethe name and address of all employees who work for the
'Research' department.
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE AS E
JOIN DEPARTMENT AS D ON E.DNO = D.DNUMBER
WHERE D.DNAME = 'Research';
DNAME='Research’ is a selection condition
DNUMBER=DNO is a join condition
Slide
8-24
25.
JOIN(CONT.)
For everyproject located in 'Stafford', list the project number, the controlling
department number, and the department manager's last name, address, and
birthdate.
SELECT P.PNUMBER, P.DNUM, E.LNAME, E.BDATE, E.ADDRESS
FROM PROJECT AS P
JOIN DEPARTMENT AS D ON P.DNUM = D.DNUMBER
JOIN EMPLOYEE AS E ON D.MGRSSN = E.SSN
WHERE P.PLOCATION = 'Stafford';
Slide
8-25
26.
UNSPECIFIED WHERE-CLAUSE
MissingWHERE-clause
indicates there is no condition and is same as WHERE TRUE
Retrieve the SSN values for all employees.
SELECT SSN
FROM EMPLOYEE
If there is no join condition, then we get CARTESIAN PRODUCT
SELECT SSN, DNAME
FROM EMPLOYEE, DEPARTMENT
OR
SELECT E.SSN, D.DNAME
FROM EMPLOYEE AS E
CROSS JOIN DEPARTMENT AS D;
Slide
8-26
27.
USE OF *
To retrieve all the attribute values of the selected tuples, a * is
used, which stands for all the attributes
Examples:
SELECT *
FROM EMPLOYEE
WHERE DNO=5
SELECT *
FROM EMPLOYEE AS E
JOIN DEPARTMENT AS D ON E.DNO = D.DNUMBER
WHERE D.DNAME = 'Research';
Slide
8-27
28.
ALIASES
In SQL,we can use the same name for two (or more)
attributes as long as the attributes are in different relations
A query that refers to two attributes with the same name
must prefix the relation name to the attribute name
Example:
EMPLOYEE.DNO, DEPARTMENT.DNUMBER
Slide
8-28
29.
ALIASES
For eachemployee, retrieve the employee's name, and the name of his
or her immediate supervisor.
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE E S
WHERE E.SUPERSSN=S.SSN
Can also use the AS keyword to specify aliases
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE AS E
JOIN EMPLOYEE AS S ON E.SUPERSSN = S.SSN;
Slide
8-29
30.
ARITHMETIC OPERATIONS
Arithmeticoperators '+', '-'. '*', and '/’) can be applied to
numeric values in an SQL query result
Give all employees who work on the 'ProductX' project a 10%
raise.
SELECT E.FNAME, E.LNAME, 1.1 * E.SALARY
FROM EMPLOYEE AS E
JOIN WORKS_ON AS W ON E.SSN = W.ESSN
JOIN PROJECT AS P ON W.PNO = P.PNUMBER
WHERE P.PNAME = 'ProductX';
Slide
8-30
31.
ORDER BY
TheORDER BY clause sort the tuples in a query result
Retrieve a list of employees and the projects each works in, ordered
by the employee's department, and within each department ordered
alphabetically by employee last name, then first name.
SELECT D.DNAME, E.LNAME, E.FNAME, P.PNAME
FROM DEPARTMENT AS D
JOIN EMPLOYEE AS E ON D.DNUMBER = E.DNO
JOIN WORKS_ON AS W ON E.SSN = W.ESSN
JOIN PROJECT AS P ON W.PNO = P.PNUMBER
ORDER BY D.DNAME, E.LNAME, E.FNAME;
The default order is in ascending order of values
We can specify the keyword DESC if we want a descending order
ORDER BY Dname DESC, Lname ASC
Slide
8-31
32.
NULLS IN SQLQUERIES
SQL allows queries that check if a value is NULL
SQL uses IS or IS NOT to compare NULLs
Retrieve the names of all employees who do not have
supervisors.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE SUPERSSN IS NULL
Note: If a join condition is specified, tuples with NULL values for the
join attributes are not included in the result
Slide
8-32
33.
SUBSTRING COMPARISON
LIKEoperator is used to compare partial strings
Two reserved characters are used:
'%' (or '*' in some implementations) replaces an arbitrary
number of characters, and
'_' replaces a single arbitrary character
Retrieve all employees whose address is in Houston,
Texas.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE ADDRESS LIKE '%Houston,TX%’
Slide
8-33
34.
SUBSTRING COMPARISON (CONT.)
Retrieve all employees who were born during the 1950s.
Here, '5' must be the third character of the string , so the
BDATE value is ‘__5_______',.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE BDATE LIKE ‘__5_______',.
LIKE operator allows us to get around the fact that each value
is considered atomic and indivisible;
hence, in SQL, character string attribute values are not atomic
Slide
8-34
35.
JOINED RELATIONS INSQL
Allows the user to specify different types of joins (regular "theta" JOIN, NATURAL JOIN,
LEFT OUTER JOIN, RIGHT OUTER JOIN, CROSS JOIN, etc )
Example:
SELECTE.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE AS E , EMPLOYEE AS S
WHERE E.SUPERSSN=S.SSN
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM (EMPLOYEE AS E
JOIN EMPLOYEE AS S ON E.SUPERSSN = S.SSN);
SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE AS E
LEFT OUTER JOIN EMPLOYEE AS S ON E.SUPERSSN = S.SSN;
Slide
8-35
36.
JOINED RELATIONS FEATUREIN SQL
SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO
could be written as:
SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE JOIN DEPARTMENT
ON DNUMBER=DNO)
WHERE DNAME='Research’
or as:
SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT
AS DEPT(DNAME, DNO, MSSN, MSDATE)
WHERE DNAME='Research’
Slide
8-36
37.
JOINED RELATIONS FEATUREIN SQL
Example that illustrates multiple joins
SELECT PNUMBER, DNUM, LNAME,
FROM (PROJECT JOIN DEPARTMENT
ON DNUM=DNUMBER)
JOIN EMPLOYEE ON MGRSSN=SSN) )
WHERE PLOCATION='Stafford’
Slide
8-37
38.
SET OPERATIONS
SQLhas incorporated some set operations like
Union operation (UNION),
Set difference (EXCEPT) and
Intersection operation (INTERSECT)
Duplicate tuples are eliminated from the result
Requires union compatible relations
Slide
8-38
39.
SET OPERATIONS (CONT.)
Make a list of all project numbers for projects that involve an employee whose last
name is 'Smith' as a worker or as a manager of the department that controls the
project.
(SELECT P.PNAME
FROM PROJECT AS P
JOIN DEPARTMENT AS D ON P.DNUM = D.DNUMBER
JOIN EMPLOYEE AS E ON D.MGRSSN = E.SSN
WHERE E.LNAME = 'Smith’)
UNION
(SELECT P.PNAME
FROM PROJECT AS P
JOIN WORKS_ON AS W ON P.PNUMBER = W.PNO
JOIN EMPLOYEE AS E ON W.ESSN = E.SSN
WHERE E.LNAME = 'Smith');
Slide
8-39
40.
AGGREGATE FUNCTIONS
IncludeCOUNT, SUM, MAX, MIN, and AVG
Find the maximum salary, the minimum salary, and the average
salary among all employees.
SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
Some SQL implementations may not allow more than one function in
the SELECT-clause
Slide
8-40
41.
AGGREGATE FUNCTIONS (CONT.)
Retrieve the number of employees in the 'Research'
department
SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research’
Slide
8-41
42.
GROUPING
GROUP BY-clausespecifies the grouping attributes
For each department, retrieve the department number,
the number of employees in the department, and their
average salary.
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO
Slide
8-42
43.
GROUPING (CONT.)
Foreach project, retrieve the project number, project
name, and the number of employees who work on that
project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
The grouping and functions are applied after the joining of the two
relations
Group By clause specifies grouping attributes which should appear
in SELECT clause
Slide
8-43
44.
HAVING-CLAUSE
HAVING-clause specifya selection condition on groups
For each project on which more than two employees
work , retrieve the project number, project name, and
the number of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2
Slide
8-44
GROUP BY ANDHAVING
Count the total number of employees whose salaries
exceed $40,000 in each department, but only for
departments where more than five employees work
SELECT Dname, COUNT (*)
FROM DEPARTMENT, EMPLOYEE
WHERE Dnumber=Dno AND Salary>40000
GROUP BY Dname
HAVING COUNT (*) > 5;
Slide
8-47
48.
GENERAL FORM OFGROUPING AND
AGGREGATION
Evaluation steps:
1. Evaluate FROM-WHERE, apply condition C1
2. Group by the attributes a1,…,ak
3. Apply condition C2 to each group (may have aggregates)
4. Compute aggregates in S and return the result
SELECT S
FROM R1,…,Rn
WHERE C1
GROUP BY a1,…,ak
HAVING C2
49.
TWO EXAMPLES
Store(sid, sname)
Product(pid,pname, price, sid)
Find stores that sell only products with price > 100
same as:
Find stores s.t. all their products have price > 100)
50.
SELECT Store.name
FROM Store,Product
WHERE Store.sid = Product.sid
GROUP BY Store.sid, Store.name
HAVING 100 < min(Product.price)
SELECT Store.name
FROM Store
WHERE Store.sid NOT IN
(SELECT Product.sid
FROM Product
WHERE Product.price <= 100)
SELECT Store.name
FROM Store
WHERE
100 < ALL (SELECT Product.price
FROM product
WHERE Store.sid = Product.sid)
Almost equivalent…
Find stores s.t. all their
products have price > 100
51.
AGGREGATE EXAMPLE
Example:Count the number of distinct salary values in
the database.
SELECT COUNT (DISTINCT Salary)
FROM EMPLOYEE;
NULL values are discarded when aggregate functions
are applied to a particular attribute.
Slide
8-51
52.
SUMMARY OF SQLQUERIES
A query in SQL can consist of up to six clauses, but only the
first two, SELECT and FROM, are mandatory. The clauses
are specified in the following order:
SELECT<attribute list>
FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>]
A query is evaluated by first applying the WHERE-clause,
then GROUP BY and HAVING, and finally the SELECT-clause
Slide
8-52
53.
SUMMARY OF SQLQUERIES (CONT.)
The SELECT-clause lists the attributes or functions to be
retrieved
The FROM-clause specifies all relations (or aliases) needed in the
query but not those needed in nested queries
The WHERE-clause specifies the conditions for selection and join
of tuples from the relations specified in the FROM-clause
GROUP BY specifies grouping attributes
HAVING specifies a condition for selection of groups
ORDER BY specifies an order for displaying the result of a query
Slide
8-53
54.
SQL QUERIES
Thereare various ways to specify the same query in SQL
This is to give flexibility to user to specify queries
For query optimization, it is preferable to write a query
with as little nesting and implied ordering as possible.
Ideally, DBMS should process the same query in the
same way regardless of how the query is specified.
But this is quite difficult in practice, (chapter 19,20)
Slide
8-54
55.
SPECIFYING UPDATES INSQL
There are three SQL commands to modify the database;
INSERT,
DELETE, and
UPDATE
Slide
8-55
56.
INSERT
It isused to add one or more tuples to a relation
Example:
INSERT INTO EMPLOYEE
VALUES ('Richard','K','Marini', '653298653', '30-DEC-52',
'98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 )
Attribute values should be listed in the same order as
the attributes were specified in the CREATE TABLE
command
Slide
8-56
57.
INSERT (CONT.)
Analternate form of INSERT specifies explicitly the
attribute names that correspond to the values in the
new tuple
Example: Insert a tuple for a new EMPLOYEE for whom
we only know the FNAME, LNAME, and SSN attributes.
INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)
VALUES ('Richard', 'Marini', '653298653')
Attributes with NULL values can be left out
Slide
8-57
58.
INSERT (CONT.)
Supposewe want to create a temporary table that has the
name, number of employees, and total salaries for each
department.
A table DEPTS_INFO is created by Q1, and is loaded with the
information retrieved from the database by the query Q2.
Q1: CREATE TABLE DEPTS_INFO
(DEPT_NAME VARCHAR(10),
NO_OF_EMPS INTEGER,
TOTAL_SAL INTEGER);
Q2: INSERT INTO DEPTS_INFO (DEPT_NAME,
NO_OF_EMPS, TOTAL_SAL)
SELECT DNAME, COUNT (*), SUM
(SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO
GROUP BY DNAME ;
Slide
8-58
59.
DELETE
Removes tuplesfrom a relation
Tuples are deleted from only one table at a time (unless
CASCADE is specified on a referential integrity constraint)
Examples:
DELETE FROM EMPLOYEE
WHERE LNAME='Brown’
DELETE FROM EMPLOYEE
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research')
DELETE FROM EMPLOYEE Slide
8-59
60.
UPDATE
Used tomodify attribute values of selected tuples
Example: Change the location and controlling
department number of project number 10 to 'Bellaire'
and 5, respectively.
UPDATE PROJECT
SET PLOCATION = 'Bellaire', DNUM = 5
WHERE PNUMBER=10
Slide
8-60
61.
UPDATE (CONT.)
Example:Give all employees in the 'Research' department a
10% raise in salary.
UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER
FROMDEPARTMENT
WHERE DNAME='Research')
Slide
8-61
62.
NESTING OF QUERIES
A complete SELECT query, called a nested query , can be specified
within the WHERE-clause of another query, called the outer query
Retrieve the name and address of all employees who work for the
'Research' department.
SELECT E.FNAME, E.LNAME, E.ADDRESS
FROM EMPLOYEE AS E
WHERE E.DNO IN (SELECT D.DNUMBER
FROM
DEPARTMENT AS D
WHERE
D.DNAME = 'Research'
);
Slide
8-62
63.
CORRELATED NESTED QUERIES
If a condition in the nested query references an attribute of a relation
declared in the outer query , then two queries are said to be correlated
Retrieve the name of each employee who has a dependent with the same
first name and gender as the employee.
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE AS E
WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT AS D
WHERE E.SEX = D.SEX AND FNAME=DEPENDENT_NAME)
Slide
8-63
Nested query is evaluated once for each tuple in outer query
64.
CORRELATED NESTED QUERIES(CONT.)
A query written with nested SELECT... FROM... WHERE... blocks and
using the = or IN comparison operators can always be expressed as a
single block query.
For example, the query on previous slide can be written as
Retrieve the name of each employee who has a dependent with the
same first name as the employee.
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE E, DEPENDENT D
WHERE E.SSN=D.ESSN AND
E.FNAME=D.DEPENDENT_NAME
Slide
8-64
65.
NESTED QUERIES
Selectthe Essns of all employees who work the same (project,
hours) combination that ‘John Smith’ (whose Ssn =
‘123456789’) works on.
SELECT DISTINCT Essn
FROM WORKS_ON
WHERE (Pno, Hours) IN ( SELECT Pno, Hours
FROM WORKS_ON
WHERE Essn=‘123456789’ );
Slide
8-65
SQL allows use of tuples of values in comparisons
66.
EXISTS FUNCTION
EXISTSFunction checks whether the result of a nested query is
empty or not
Retrieve the name of each employee who has a dependent with the
same first name as the employee.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN AND
FNAME=DEPENDENT_NAME)
Slide
8-66
67.
EXISTS FUNCTION (CONT.)
Retrieve the names of employees who have no dependents.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
The above correlated nested query retrieves all DEPENDENT tuples
related to an EMPLOYEE tuple.
If none exist , the EMPLOYEE tuple is selected
EXISTS is necessary for the expressive power of SQL
Slide
8-67
68.
EXISTS FUNCTION (CONT.)
Find the names of managers who have at least one
dependents.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
AND
EXISTS (SELECT *
FROM DEPARTMENT
WHERE SSN=Mgr_SSN)
Slide
8-68
69.
EXISTS FUNCTION (CONT.)
Retrieve the name of each employee who works on all
the projects controlled by department number 5.
Set theory: S1 contains S2 if (S2 – S1 = 0)
Slide
8-69
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS (
(SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5)
EXCEPT
(SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN)
)
S1 = set of projects
of each employee
S2= set of DN0=5
projects
70.
NESTED QUERIES
Retrievethe name of each employee who works on all the
projects controlled by department number 5.
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE ( (SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN)
CONTAINS
(SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5) ) Slide
8-70
CONTAINS compares two sets , and returns TRUE if one set contains all values in
the other set.
Same as division operation of relational algebra
Most implementations of SQL do not have this operator
71.
NESTED CORRELATED QUERIES(CONTD)
SELECT name
FROM Product
WHERE price > ALL (SELECT price
FROM Purchase
WHERE maker=‘IBM’)
Product ( pname, price, category, maker)
Find products that are more expensive than all those produced
By “IBM”
You can also use: s > ALL R
s > ANY R
EXISTS R
72.
NESTED CORRELATED QUERIES(CONTD)
SELECT Fname
FROM Employee
WHERE Salary > ALL (SELECT Salary
FROM Employee
where Dno=5)
Find Employee whose salary is greater than the salary
of all employee in department 5
You can also use: s > ALL R
s > ANY R
EXISTS R
73.
COMPLEX CORRELATED QUERY
Product( pname, price, category, maker, year)
Find products (and their manufacturers) that are more expensive
than all products made by the same manufacturer before 1972
Very powerful ! Also much harder to optimize.
SELECT DISTINCT pname, maker
FROM Product AS x
WHERE price > ALL (SELECT price
FROM Product AS y
WHERE x.maker = y.maker AND x.pname!=y.pname
and
y.year < 1972)
74.
COMPLEX CORRELATED QUERY
Find Employee (his dno and salary) whose salary is greater than all
employees in the same department
SELECT Fname, Salary, Dno
FROM Employee as E
WHERE Salary > ALL (SELECT Salary
FROM Employee as S
WHERE E.dno=S.dno and E.ssn !=S.ssn )
75.
EXPLICIT SETS
Itis also possible to use an explicit (enumerated) set of
values in the WHERE-clause rather than a nested query
Retrieve the social security numbers of all employees
who work on project number 1, 2, or 3.
SELECT DISTINCT ESSN
FROM WORKS_ON
WHERE PNO IN (1, 2, 3)
Slide
8-75
76.
Chapter 9-76
VIEWS INSQL
A view is a “virtual” table that is derived from other
tables
Allows for limited update operations (since the table
may not physically be stored)
Allows full query operations
A convenience for expressing certain operations
They are used to:
• simplify complex queries, and
• define distinct conceptual interfaces for different users.
77.
Chapter 9-77
SQL VIEWS:AN EXAMPLE
Specify a different WORKS_ON table
CREATE VIEW WORKS_ON1 AS
SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER
Chapter 9-79
USING AVIRTUAL TABLE
We can specify SQL queries on a newly created view:
SELECT FNAME, LNAME
FROM WORKS_ON1
WHERE PNAME=‘ProductX’;
DBMS is responsible to keep view always up-to-date
When no longer needed, a view can be dropped:
DROP WORKS_ON1;
80.
Chapter 9-80
EFFICIENT VIEWIMPLEMENTATION
Query modification: present the view query in terms of a query
on the underlying base tables
SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME=‘PRODUCTX’
Disadvantage:
Inefficient for views defined via complex queries (esp if additional
queries are to be applied within a short time period )
81.
Chapter 9-81
EFFICIENT VIEWIMPLEMENTATION
View materialization: involves physically creating and
keeping a temporary table
assumption: other queries on the view will follow
concerns: maintaining correspondence between the base
table and the view when the base table is updated
strategy: incremental update
82.
Chapter 9-82
VIEW UPDATE
Single view without aggregate operations:
update may map to an update on the underlying
base table
Views involving joins:
an update may map to an update on the underlying
base relations
not always possible
Example:
UPDATE WORKS_ON1
SET PNAME=XYZ'
WHERE FNAME=‘JOHN AND
LNAME='SMITH' AND PNAME=‘PRODUCTX’
83.
A) UPDATE WORKS_ON1
SETPNO = (SELECT PNUMBER FROM PROJECT
WHERE PNAME=‘XYZ’)
WHERE ESSN IN (SELECT SSN FROM EMPLOYEE
WHERE LNAME=‘SMITH’ AND FNAME=‘JOHN’)
AND
PNO = (SELECT PNUMBER FROM PROJECT
WHERE PNAME=‘PRODUCTX’)
B)UPDATE PROJECT SET PNAME=‘XYZ’
WHERE PNAME=‘PRODUCTX’
Slide
8-83
84.
Chapter 9-84
UN-UPDATABLE VIEWS
Views defined using groups and aggregate functions are
not updateable
Views defined on multiple tables using joins are generally not
updateable
WITH CHECK OPTION: must be added to the definition of a
view if the view is to be updated
to allow check for updatability and to plan for an execution
strategy
85.
ASSERTION
In SQL,table constraints are associated with a single table.
CHECK(DNUMBER >0 AND DNUMBER <25)
CHECK (Dept_create_date <= Mgr_start_date)
Expression in the CHECK clause can refer to other tables but when a
constraint involves many tables, it becomes cumbersome
Assertions are constraints that are not associated with any one table.
SQL-server do not support assertion, however it do support
trigger and check constraint
Slide
8-85
86.
Chapter 9-86
ASSERTIONS: ANEXAMPLE
“The salary of an employee must not be greater than the
salary of the manager of the department that the employee
works for’’
CREATE ASSERTION SALARY_CONSTRAINT
CHECK (NOT EXISTS (SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT
D
WHERE E.SALARY > M.SALARY AND
E.DNO=D.NUMBER AND D.MGRSSN=M.SSN))
87.
Chapter 9-87
USING GENERALASSERTIONS
Specify a query that violates the condition; include
inside a NOT EXISTS clause
Query result must be empty
if the query result is not empty, the assertion has been
violated
Create Assertion to enforce the constraint that
The number of Employees in each department should be less than 20.
An employee should be assign a project of hisher department only.
The total working hours of all the employees in a department should be
less than 180.
88.
CHECK clausecan also be used to specify constraints on
individual attributes, domains and individual tuples
CONSTRAINT deptPK PRIMARY KEY(Dnumber)
CONSTRAINT deptSK UNIQUE(Dname)
CHECK (Dept_create_date <= Mgr_start_date)
Difference between CREATE ASSERTION and the
individual domain and tuple constraints is
CHECK on individual attributes, domains, and tuples are
checked only when tuples are inserted or updated.
Slide
8-88
89.
Chapter 9-89
SQL TRIGGERS
Objective: to monitor a database and take action when a
condition occurs
Triggers are expressed in a syntax similar to assertions
and include the following:
event (e.g., an update operation)
condition
action (to be taken when the condition is satisfied)
90.
Chapter 9-90
SQL TRIGGERS:AN EXAMPLE
A trigger to compare an employee’s salary to his/her
supervisor during insert or update operations:
CREATE TRIGGER INFORM_SUPERVISOR
BEFORE INSERT OR UPDATE OF
SALARY, SUPERVISOR_SSN ON EMPLOYEE
FOR EACH ROW
WHEN
(NEW.SALARY> (SELECT SALARY FROM EMPLOYEE
WHERE SSN=NEW.SUPERVISOR_SSN))
INFORM_SUPERVISOR
(NEW.SUPERVISOR_SSN,NEW.SSN;
91.
EXAMPLE: BOAT RENTAL
DATABASE
Consider the following Boat Rental database schema
SAILOR (SID, SName, Phone, City)
BOAT (BName, BType, Price, OID)
RESERVATION (SID, BName, Date, Duration)
OWNER (OID, OName, Phone, Street, City, Country)
Find the name and city of sailors who reserve every
‘Fishing’ boat.
Find the names of boats that are reserved by at least ten
different sailors.
List names, owner names, and prices of the boats which
were reserved in 2007 but not in 2008.
Slide
8-91
92.
EXAMPLE: BOAT RENTAL
DATABASE
Consider the following schema
SAILOR (SID, SName, Phone, City)
BOAT (BName, BType, Price, OID)
RESERVATION (SID, BName, Date, Duration)
OWNER (OID, OName, Phone, Street, City, Country)
Find the name and city of sailors who reserve every ‘Fishing’ boat.
SELECT SNAME, CITY
FROM SAILOR s
WHERE NOT EXISTS ( (SELECT BNAME
FROM BOAT
WHERE BTYPE=’Fishing’)
EXCEPT
(SELECT BNAME
FROM reservation r
WHERE r.SID=s.SID) )
Slide
8-92
93.
EXAMPLE: BOAT RENTAL
DATABASE
Consider the following schema
SAILOR (SID, SName, Phone, City)
BOAT (BName, BType, Price, OID)
RESERVATION (SID, BName, Date, Duration)
OWNER (OID, OName, Phone, Street, City, Country)
Find the names of boats that are reserved by at least ten
different sailors.
Select bname
From reservation r
Group by bname
Having count(DISTINCT SID) >9
Slide
8-93
94.
EXAMPLE: BOAT RENTAL
DATABASE
Consider the following schema
SAILOR (SID, SName, Phone, City)
BOAT (BName, BType, Price, OID)
RESERVATION (SID, BName, Date, Duration)
OWNER (OID, OName, Phone, Street, City, Country)
List names, owner names, and prices of the boats which were reserved in
2007 but not in 2008.
Select distinct b.bname, b.price, o.oname
From reservation r, boat b, owner o
Where r.bname = b.bname and b.oid=o.oid and r.date LIKE '%2007%'
and r.sid not in
(Select ic.sid
From reservation ic, boat ip
Where ic.bname = ip.bname and ip.date LIKE '%2008%' )
Slide
8-94
95.
EXAMPLE: BOAT RENTALDATABASE
Consider the following Boat Rental database schema:
SAILOR (SID, SName, Phone, City)
BOAT (BName, BType, Price, OID)
RESERVATION (SID, BName, Date, Duration)
OWNER (OID, OName, Phone, Street, City, Country)
SELECT DISTINCT Bname
FROM BOAT
WHERE Price > ALL (SELECT price
FROM BOAT b , OWNER o
WHERE b.oid=o.oid and Country=‘Pakistan’ )
What does the query do?
96.
EXAMPLE: BOAT RENTALDATABASE
Consider the following Boat Rental database schema:
SAILOR (SID, SName, Phone, City)
BOAT (BName, BType, Price, OID)
RESERVATION (SID, BName, Date, Duration)
OWNER (OID, OName, Phone, Street, City, Country)
Select bname,count(*)
From reservation r ,boat b,owner o
Where b.bname=r.bname and b. oid=o.oid and country=‘Pakistan’
Group by bname
Having count(*) > 5
What does the query do?
#9 You can create table in SQL-server without specifying Primary Key. But in this case the table will have duplicate value and will not fulfill the constraint of the relational DB
#10 For Set Default you should have assigned some default value to the foreign key Mgrssn in department table and that default value should be present in PK SSN in Employee table otherwise you can get an error when u delete a tuple. (because when tuple is deleted it will try to assign default value and if the default is not present then we get foreign key error)
#18 SQL relations can be constrained to be sets by specifying PRIMARY KEY or UNIQUE attributes, or by using the DISTINCT option in a query
#23 SELECT-clause specifies the projection attributes and the WHERE-clause specifies the selection condition
#25 In above example, there are two join conditions
The join condition DNUM=DNUMBER relates a project to its controlling department
The join condition MGRSSN=SSN relates the controlling department to the employee who manages that department
Step 1: Join PROJECT and DEPARTMENT → result A
Step 2: Join result A with EMPLOYEE → result B
Step 3: Filter result B where P.PLOCATION = 'Stafford'
Step 4: Output the selected columns from result B
#29 The alternate relation names E and S are called aliases or tuple variables for the EMPLOYEE relation
We can think of E and S as two different copies of EMPLOYEE; E represents employees in role of supervisees and S represents employees in role of supervisors
#31 ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC
#32 As it considers each NULL value distinct from other NULL values, so equality comparison is not appropriate .
NULL ≠ NULL → because each one could mean a different unknown value
Always use IS NULL / IS NOT NULL instead of = when checking for NULLs
#42 Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s)
Cannot include employee name in the select because not contained in group by
#51 If we write COUNT(SALARY) instead of COUNT(DISTINCT SALARY) in Q23, then
duplicate values will not be eliminated. However, any tuples with NULL for SALARY
will not be counted. In general, NULL values are discarded when aggregate functions
are applied to a particular column (attribute).
#58 Note: The DEPTS_INFO table may not be up-to-date if we change the tuples in either the DEPARTMENT or the EMPLOYEE relations after issuing U3B. We have to create a view (see later) to keep such a table up to date.
#59 A missing WHERE-clause specifies that all tuples in the relation are to be deleted; the table then becomes an empty table
Includes a WHERE-clause to select the tuples to be deleted
#60 A WHERE-clause selects the tuples to be modified
An additional SET-clause specifies the attributes to be modified and their new values
Each command modifies tuples in the same relation
Referential integrity should be enforced
#61 In this request, the modified SALARY value depends on the original SALARY value in each tuple
The reference to the SALARY attribute on the right of = refers to the old SALARY value before modification
The reference to the SALARY attribute on the left of = refers to the new SALARY value after modificatio
#62 Select fname, lname, address
from Employee,Department
where Dno=Dnumber and Dname='Research‘
The nested query selects the number of the 'Research' department
The outer query select an EMPLOYEE tuple if its DNO value is in the result of nested query
The comparison operator IN compares a value v with a set (or multi-set) of values V, and evaluates to TRUE if v is one of the elements in V
#63 select fname
from Employee, Dependent
where fname=dependent_name and ssn=essn
The result of a correlated nested query is different for each tuple (or combination of tuples) of the relation(s) in the outer query
#64 A DML statement that includes a subquery is referred to as the outer query. The following guidelines provide details about how to implement subqueries in your outer queries or in other subqueries:
You must enclose a subquery in parenthesis.
A subquery must include a SELECT clause and a FROM clause.
A subquery can include optional WHERE, GROUP BY, and HAVING clauses.
A subquery cannot include COMPUTE or FOR BROWSE clauses.
You can include an ORDER BY clause only when a TOP clause is included.
You can nest subqueries up to 32 levels.
#65 A subquery can be written in FROM clause. However, using subquery in FROM clause should generally be avoided if you can rewrite your query in a different way, the reason being that no indexes can be used on a temporary table in memory. Also, A subquery in the FROM clause can't be correlated subquery as it can't be evaluated per row of the outer query.
#85 although the conditional expression in the CHECK clause can refer to other tables. Table constraints are required to hold only if the associated table is nonempty. Thus, when a constraint involves two or more tables, the table constraint mechanism is sometimes cumbersome and not quite what is desired.
#87 CREATE ASSERTION DEPT_EMPs
CHECK( Not Exists (SELECT Dno
FROM Employee
Group By Dno
Having count(ssn) > 100))
*** Use table constarints in sql –server*****
ALTER TABLE Employee
ADD CONSTRAINT no_of_emp
CHECK( Not Exists (SELECT Dno
FROM Employee
Group By Dno
Having count(ssn) > 100))
#89 A manager may
want to be informed if an employee’s travel expenses exceed a certain limit by
receiving a message whenever this occurs. The action that the DBMS must take in
this case is to send an appropriate message to that user.
#90 For assertion on multiple table create triggers as sql server do not provide create assertion
CREATE TRIGGER trg ON tbl
Before INSERT, UPDATE
AS
...
IF EXISTS( SELECT * FROM ...)
ROLLBACK
#95 List the names of the most boats that are expensive then all boats owned by a Pakistani
#96 List the names of the boats that are owned by a Pakistani and were reserved by at least five sailors.