0% found this document useful (0 votes)
12 views114 pages

Module 5 Short

Uploaded by

unknownfanzhou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views114 pages

Module 5 Short

Uploaded by

unknownfanzhou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

Database Management Systems

CS 5200
Dr. Tehmina Amjad
Basic SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


2
Outline
• SQL Data Definition and Data Types
• Specifying Constraints in SQL
• Basic Retrieval Queries in SQL
• INSERT, DELETE, and UPDATE Statements in SQL
• Additional Features of SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


3
SQL Data Definition, Data Types, Standards
• Terminology:
• Table, row, and column used for relational model terms relation, tuple, and
attribute
• CREATE statement
• Main SQL command for data definition
• The language has features for : Data definition, Data Manipulation,
Transaction control (Transact-SQL, Ch. 20), Indexing (Ch.17), Security
specification (Grant and Revoke- see Ch.30), Active databases (Ch.26),
Multi-media (Ch.26), Distributed databases (Ch.23) etc.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


4
Schema and Catalog Concepts in SQL
• CREATE SCHEMA statement

• Catalog
• Named collection of schemas in an SQL environment
• SQL also has the concept of a cluster of catalogs.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


5
The CREATE TABLE Command in SQL
• Specifying a new relation
• Provide name of table
• Specify attributes, their types and initial constraints
• Can optionally specify schema:
• CREATE TABLE COMPANY.EMPLOYEE ...
or
• CREATE TABLE EMPLOYEE ...

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


6
The CREATE TABLE Command in SQL (cont’d.)
• Base tables (base relations)
• Relation and its tuples are actually created and stored as a file by the DBMS
• Virtual relations (views)
• Created through the CREATE VIEW statement. Do not correspond to any
physical file.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


7
COMPANY relational database
schema (Fig. 5.7)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


8
One possible database state for the COMPANY relational
database schema (Fig. 5.6)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


9
One possible database state for the COMPANY
relational database schema – continued (Fig. 5.6)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


10
SQL CREATE TABLE data definition statements
for defining the COMPANY schema from Figure
5.7 (Fig. 6.1)

continued on next slide


Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
11
SQL CREATE TABLE data definition statements for defining
the COMPANY schema from Figure 5.7 (Fig. 6.1)-continued

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


12
Attribute Data Types and Domains 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)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


14
Attribute Data Types and Domains in SQL
(cont’d.)
• Bit-string data types
• Fixed length: BIT(n)
• Varying length: BIT VARYING(n)
• 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
• Multiple mapping functions available in RDBMSs to change date formats

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


15
Attribute Data Types and Domains in SQL
(cont’d.)
• Additional data types
• Timestamp data type
Includes the DATE and TIME fields
• Plus a minimum of six positions for decimal fractions of seconds
• Optional WITH TIME ZONE qualifier
• INTERVAL data type
• Specifies a relative value that can be used to increment or
decrement an absolute value of a date, time, or timestamp
• DATE, TIME, Timestamp, INTERVAL data types can be cast
or converted to string formats for comparison.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


16
Attribute Data Types and Domains in SQL
(cont’d.)
• Domain
• Name used with the attribute specification
• Makes it easier to change the data type for a domain that is
used by numerous attributes
• Improves schema readability
• Example:
• CREATE DOMAIN SSN_TYPE AS CHAR(9);
• TYPE
• User Defined Types (UDTs) are supported for object-
oriented applications. (See Ch.12) Uses the command:
CREATE TYPE

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


17
Specifying Constraints in SQL
Basic constraints:
• Relational Model has 3 basic constraint types that are supported in
SQL:
• Key constraint: A primary key value cannot be duplicated
• Entity Integrity Constraint: A primary key value cannot be null
• Referential integrity constraints : The “foreign key “ must have a value that is
already present as a primary key, or may be null.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


18
Specifying Attribute Constraints
Other Restrictions on attribute domains:
• Default value of an attribute
• DEFAULT <value>
• NULL is not permitted for a particular attribute (NOT
NULL)
• CHECK clause
• Dnumber INT NOT NULL CHECK (Dnumber > 0
AND Dnumber < 21);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


19
Specifying Key and Referential Integrity
Constraints
• PRIMARY KEY clause
• Specifies one or more attributes that make up the primary key of a relation
• Dnumber INT PRIMARY KEY;
• UNIQUE clause
• Specifies alternate (secondary) keys (called CANDIDATE keys in the relational
model).
• Dname VARCHAR(15) UNIQUE;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


20
Specifying Key and Referential Integrity
Constraints (cont’d.)
• FOREIGN KEY clause
• Default operation: reject update on violation
• Attach referential triggered action clause
• Options include SET NULL, CASCADE, and SET DEFAULT
• Action taken by the DBMS for SET NULL or SET DEFAULT is the same for both ON
DELETE and ON UPDATE
• CASCADE option suitable for “relationship” relations

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


21
Giving Names to Constraints
• Using the Keyword CONSTRAINT
• Name a constraint
• The names of all constraints within a particular schema must be unique.
• A constraint name is used to identify a particular constraint in case the constraint must
be dropped later and replaced with another constraint (More details in Chapter 7)
• It is also possible to temporarily defer a constraint until the end of a transaction (Chapter
20)

• Useful for later altering

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


22
Default attribute values and referential integrity triggered
action specification (Fig. 6.2)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


23
Specifying Constraints on Tuples Using CHECK
• Additional Constraints on individual tuples within a relation are also possible
using CHECK
• CHECK clauses at the end of a CREATE TABLE statement
• Apply to each tuple individually
• CHECK (Dept_create_date <= Mgr_start_date);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


24
Basic Retrieval Queries in SQL
• SELECT statement
• One basic statement for retrieving information from a database
• SQL allows a table to have two or more tuples that are identical in all
their attribute values
• Unlike relational model (relational model is strictly set-theory based)
• Multiset or bag behavior
• Tuple-id may be used as a key

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


25
The SELECT-FROM-WHERE Structure of Basic
SQL Queries
• Basic form of the SELECT statement:

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


26
The SELECT-FROM-WHERE Structure of
Basic SQL Queries (cont’d.)

• Logical comparison operators


• =, <, <=, >, >=, and <>
• Projection attributes
• Attributes whose values are to be retrieved
• Selection condition
• Boolean condition that must be true for any retrieved
tuple. Selection conditions include join conditions (see
Ch.8) when multiple relations are involved.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


27
Basic Retrieval Queries

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


28
Basic Retrieval Queries (Contd.)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


29
Ambiguous Attribute Names
• Same name can be used for two (or more) attributes in different
relations
• As long as the attributes are in different relations
• Must qualify the attribute name with the relation name to prevent ambiguity

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


30
Aliasing, and Renaming
• Aliases or tuple variables
• Declare alternative relation names E and S to refer to the EMPLOYEE relation
twice in a query:

Query 8. For each employee, retrieve the employee’s first and last name and the first and last name
of his or her immediate supervisor.
• SELECT E.Fname, E.Lname, S.Fname, S.Lname
FROM EMPLOYEE AS E, EMPLOYEE AS S
WHERE E.Super_ssn=S.Ssn;
• Recommended practice to abbreviate names and to prefix same or similar
attribute from multiple tables.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
31
Aliasing, Renaming and Tuple Variables
(contd.)
• The attribute names can also be renamed
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex,
Sal, Sssn, Dno)
• Note that the relation EMPLOYEE now has a variable name E which
corresponds to a tuple variable
• The “AS” may be dropped in most SQL implementations

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


32
Unspecified WHERE Clause
and Use of the Asterisk
• Missing WHERE clause
• Indicates no condition on tuple selection
• Effect is a CROSS PRODUCT
• Result is all possible tuple combinations (or the Algebra operation of
Cartesian Product) result

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


33
Unspecified WHERE Clause
and Use of the Asterisk
• Specify an asterisk (*)
• Retrieve all the attribute values of the selected tuples
• The * can be prefixed by the relation name; e.g., EMPLOYEE *

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


34
Tables as Sets in SQL
• SQL does not automatically eliminate duplicate tuples in query results
• For aggregate operations (See sec 7.1.7) duplicates must be accounted for
• Use the keyword DISTINCT in the SELECT clause
• Only distinct tuples should remain in the result

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


35
Tables as Sets in SQL (cont’d.)
• Set operations
• UNION, EXCEPT (difference), INTERSECT
• Corresponding multiset operations: UNION ALL, EXCEPT ALL, INTERSECT
ALL
• Type compatibility is needed for these operations to be valid

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


36
Substring Pattern Matching and Arithmetic
Operators
• LIKE comparison operator
• Used for string pattern matching
• % replaces an arbitrary number of zero or more characters
• underscore (_) replaces a single character
• Examples: WHERE Address LIKE ‘%Houston,TX%’;
• WHERE Ssn LIKE ‘_ _ 1_ _ 8901’;
• BETWEEN comparison operator
E.g., in Q14 :
WHERE(Salary BETWEEN 30000 AND 40000)
AND Dno = 5;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


37
Arithmetic Operations
• Standard arithmetic operators:
• Addition (+), subtraction (–), multiplication (*), and division
(/) may be included as a part of SELECT

• Query 13. Show the resulting salaries if every employee working on the
‘ProductX’ project is given a 10 percent raise.

SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal


FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE E.Ssn=W.Essn AND W.Pno=P.Pnumber AND P.Pname=‘ProductX’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


38
Ordering of Query Results
• Use ORDER BY clause
• Keyword DESC to see result in a descending order of values
• Keyword ASC to specify ascending order explicitly
• Typically placed at the end of the query

ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


39
Basic SQL Retrieval Query Block

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


40
INSERT, DELETE, and UPDATE Statements in
SQL
• Three commands used to modify the database:
• INSERT, DELETE, and UPDATE
• INSERT typically inserts a tuple (row) in a relation (table)
• UPDATE may update a number of tuples (rows) in a relation (table)
that satisfy the condition
• DELETE may also update a number of tuples (rows) in a relation
(table) that satisfy the condition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


41
INSERT
• In its simplest form, it is used to add one or more tuples to a relation
• Attribute values should be listed in the same order as the attributes
were specified in the CREATE TABLE command
• Constraints on data types are observed automatically
• Any integrity constraints as a part of the DDL specification are
enforced

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


42
The INSERT Command
• Specify the relation name and a list of values for the tuple. All values
including nulls are supplied.

• The variation below inserts multiple tuples where a new table is


loaded values from the result of a query.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


43
BULK LOADING OF TABLES
• Another variation of INSERT is used for bulk-loading of several tuples into
tables
• A new table TNEW can be created with the same attributes as T and using
LIKE and DATA in the syntax, it can be loaded with entire data.
• EXAMPLE:

CREATE TABLE D5EMPS LIKE EMPLOYEE


(SELECT E.*
FROM EMPLOYEE AS E
WHERE E.Dno=5)
WITH DATA;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


DELETE
• Removes tuples from a relation
• Includes a WHERE-clause to select the tuples to be deleted
• Referential integrity should be enforced
• Tuples are deleted from only one table at a time (unless CASCADE is specified
on a referential integrity constraint)
• A missing WHERE-clause specifies that all tuples in the relation are to be
deleted; the table then becomes an empty table
• The number of tuples deleted depends on the number of tuples in the
relation that satisfy the WHERE-clause

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


45
The DELETE Command
• Removes tuples from a relation
• Includes a WHERE clause to select the tuples to be deleted. The number of
tuples deleted will vary.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


46
UPDATE
• Used to modify attribute values of one or more selected tuples
• 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 specified as part of DDL specification is enforced

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


47
UPDATE (contd.)
• Example: Change the location and controlling department number of
project number 10 to 'Bellaire' and 5, respectively

U5: UPDATE PROJECT


SET PLOCATION = 'Bellaire',
DNUM = 5
WHERE PNUMBER=10

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


48
UPDATE (contd.)
• Example: Give all employees in the 'Research' department a 10% raise in salary.
U6: UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research')

• 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 modification

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


49
Additional Features of SQL
• Techniques for specifying complex retrieval queries (see Ch.7)
• Writing programs in various programming languages that include SQL
statements: Embedded and dynamic SQL, SQL/CLI (Call Level Interface) and
its predecessor ODBC, SQL/PSM (Persistent Stored Module) (See Ch.10)
• Set of commands for specifying physical database design parameters, file
structures for relations, and access paths, e.g., CREATE INDEX

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


50
Additional Features of SQL (cont’d.)
• Transaction control commands (Ch.20)
• Specifying the granting and revoking of privileges to users (Ch.30)
• Constructs for creating triggers (Ch.26)
• Enhanced relational systems known as object-relational define
relations as classes. Abstract data types (called User Defined Types-
UDTs) are supported with CREATE TYPE
• New technologies such as XML (Ch.13) and OLAP (Ch.29) are added to
versions of SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


51
Summary
• SQL
• A Comprehensive language for relational database management
• Data definition, queries, updates, constraint specification, and view definition
• Covered :
• Data definition commands for creating tables
• Commands for constraint specification
• Simple retrieval queries
• Database update commands

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


52
Complex SQL Retrieval

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


53
Outline
• More Complex SQL Retrieval Queries
• Views (Virtual Tables) in SQL
• Schema Modification in SQL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


54
More Complex SQL Retrieval Queries
• Additional features allow users to specify more complex retrievals
from database:
• Nested queries, joined tables, and outer joins (in the FROM clause), aggregate
functions, and grouping

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


55
Comparisons Involving NULL and Three-
Valued Logic
• Meanings of NULL
• Unknown value A person’s date of birth is not known, so it is
represented by NULL in the database. An example of the other case
of unknown would be NULL for a person’s home phone because it is
not known whether or not the person has a home phone.
• Unavailable or withheld value A person has a home phone but does
not want it to be listed, so it is withheld and represented as NULL in
the database.
• Not applicable attribute
AnattributeLastCollegeDegreewouldbeNULLfora person who has no
college degrees because it does not apply to that person.
• NULL = NULL comparison is avoided
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
56
Comparisons Involving NULL and Three-
Valued Logic (cont’d.)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


57
Comparisons Involving NULL and Three-
Valued Logic (cont’d.)
• SQL allows queries that check whether an attribute value is NULL
• IS or IS NOT NULL

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


58
Subquery: Query inside Query
<Main Query> <Sub Query>

SELECT
SELECT FROM
WHERE
FROM GROUP BY

WHERE

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


59
Type 1: Sub Query in Where
<Main Query> <Sub Query>

SELECT

FROM

WHERE SELECT FROM


WHERE
GROUP BY

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


60
Type 1-1: Single row subquery
<Main Query> <Sub Query>

mysql> select fname, lname


SELECT
from employee
where ssn = (select min(essn)
FROM from dependent
where sex = ‘F’
);
WHERE col = ( SELECT FROM
WHERE
GROUP BY )
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
61
Type 1-2: Multiple rows subquery
<Main Query> <Sub Query>

mysql> select distinct essn


SELECT -> from works_on
-> where (pno,hours) IN (select pno, hours

FROM -> from works_on


-> where essn='123456789');

WHERE col IN ( SELECT FROM


WHERE
GROUP BY )
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
62
Type 2: InLine View (FROM)
<Main Query> <Sub Query>

mysql> select e.dno, count(*)


from employee e,
SELECT (select dno from employee
group by dno

FROM ( SELECT FROM having count(*)>1) bigdept


WHERE where salary>40000
GROUP BY )t and e.dno = bigdept.dno

WHERE group by 1;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


63
Type 3: Scalar subquery (SELECT)
<Main Query> <Sub Query>
Must return ”Single column” and “Single Value”

mysql> select (select max(salary)


SELECT SELECT FROM
WHERE from employee e
GROUP BY where e.dno = d.dnumber

FROM group by e.dno limit 1)


from department d;

WHERE

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


64
Type 4: WITH (Common Table Expression)
<Sub Query>
WITH cte ( SELECT FROM mysql> with cte as (
WHERE
GROUP BY ) select dno
from employee
SELECT group by dno
having count(*) > 1
)
FROM <Main Query>
select e.dno, count(*)
from employee e, cte

WHERE where e.salary>40000


and e.dno = cte.dno
group by e.dno;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


65
Nested Queries, Tuples, and Set/Multiset
Comparisons
• Nested queries
• Complete select-from-where blocks within WHERE clause of another query
• Outer query and nested subqueries
• Comparison operator IN
• Compares value v with a set (or multiset) of values V
• Evaluates to TRUE if v is one of the elements in V

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


66
Nested Queries
Q4A: Make a list of all project numbers for projects that involve an employee whose last name is
‘SMITH’, either as a worker or as a manager of the department that controls the project.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


67
Nested Queries
• Use tuples of values in comparisons
• Place them within parentheses

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


68
Nested Queries
• Use other comparison operators to compare a single
value v
• = ANY (or = SOME) operator
• Returns TRUE if the value v is equal to some value in the set V and is
hence equivalent to IN
• Other operators that can be combined with ANY (or SOME): >,
>=, <, <=, and <>
• ALL: value must exceed all values from nested query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


69
Nested Queries
• Avoid potential errors and ambiguities
• Create tuple variables (aliases) for all tables referenced in SQL query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


70
Correlated Nested Queries
• Correlated nested query
• Evaluated once for each tuple in the outer query
• For each EMPLOYEE tuple, evaluate the nested query, which retrieves
the Essn values for all DEPENDENT tuples with the same sex and
name as that EMPLOYEE tuple; if the Ssn value of the EMPLOYEE tuple
is in the result of the nested query, then select that EMPLOYEE tuple.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


71
Correlated Nested Queries
• 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
FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn=D.Essn AND E.Sex=D.Sex
AND E.Fname=D.Dependent_name;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


72
The EXISTS and UNIQUE Functions in SQL for
correlating queries
• EXISTS function
• Check whether the result of a correlated nested query is empty or not. They
are Boolean functions that return a TRUE or FALSE result.
• EXISTS and NOT EXISTS
• Typically used in conjunction with a correlated nested query
• SQL function UNIQUE(Q)
• Returns TRUE if there are no duplicate tuples in the result of query Q

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


73
USE of EXISTS
Q7: List the names of managers who have at least one dependent
SELECT Fname, Lname
FROM Employee
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE Ssn= Essn)

AND EXISTS (SELECT *


FROM Department
WHERE Ssn= Mgr_Ssn)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


74
USE OF NOT EXISTS
Retrieve the name of each employee who works on all the projects con- trolled by
department number 5 can be written using EXISTS and NOT EXISTS
SELECT Fname, Lname
FROM Employee
WHERE NOT EXISTS ( (SELECT Pnumber
FROM PROJECT
WHERE Dno=5)

EXCEPT (SELECT Pno


FROM WORKS_ON
WHERE Ssn= ESsn))
The above is equivalent to double negation: List names of those
employees for whom there does NOT exist a project managed by
department no. 5 that they do NOT work on.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
75
Double Negation to accomplish “for all” in
SQL
To achieve the “for all” (universal quantifier) effect, we use double negation this way in SQL:
Q3B: SELECT Lname, Fname
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM WORKS_ON B
WHERE B.Pno IN ( SELECT Pnumber
FROM PROJECT
WHERE Dnum=5
AND NOT EXISTS (SELECT *
FROM WORKS_ON C
WHERE C.Essn=Ssn
AND C.Pno=B.Pno )
)
);
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
The above is a direct rendering of: List names of those employees for whom there does NOT exist a project managed by department no. 5 that they do
76 NOT
work on.
Explicit Sets and Renaming of Attributes in
SQL
• Can use explicit set of values in WHERE clause
Q17: SELECT DISTINCT Essn
FROM WORKS_ON
WHERE Pno IN (1, 2, 3);
• Use qualifier AS followed by desired new name
• Rename any attribute that appears in the result of a query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


77
Specifying Joined Tables in the FROM Clause
of SQL
• Joined table
• Permits users to specify a table resulting from a join operation in the FROM
clause of a query
• The FROM clause in Q1A
• Contains a single joined table. JOIN may also be called INNER JOIN

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


78
Different Types of JOINed Tables in SQL
• Specify different types of join
• NATURAL JOIN
• Various types of OUTER JOIN (LEFT, RIGHT, FULL )
• NATURAL JOIN on two relations R and S
• No join condition specified
• Is equivalent to an implicit EQUIJOIN condition for each pair
of attributes with same name from R and S

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


79
NATURAL JOIN
• Rename attributes of one relation so it can be joined with another using
NATURAL JOIN:

Q1B: SELECT Fname, Lname, Address


FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT
(Dname, Dno, Mssn, Msdate)
)
)
WHERE Dname=‘Research’;

The above works with EMPLOYEE.Dno = DEPT.Dno as an implicit join condition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


80
INNER and OUTER Joins
• INNER JOIN (versus OUTER JOIN)
• Default type of join in a joined table
• Tuple is included in the result only if a matching tuple exists in the other relation
• LEFT OUTER JOIN
• Every tuple in left table must appear in result
• If no matching tuple
• Padded with NULL values for attributes of right table
• RIGHT OUTER JOIN
• Every tuple in right table must appear in result
• If no matching tuple
• Padded with NULL values for attributes of left table
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
81
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
82
Practice
• Create “STUDENT” table
mysql> create table student (sid int, sname varchar(10), dno int);
mysql> insert into student values (1,'Lee',20),(2,'Patel',30),(3,'Peng',40);

• Create “DEPT” table


mysql> create table dept (dnumber int, dname varchar(10), dlocation varchar(10));
mysql> insert into dept values (10,'EE','NY'),(20,'CS','SJ'),(30,'DS','SF');

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


83
STUDENT DEPT
sid sname dno dnumber dname dlocation
1 Lee 20 10 EE NY
2 Patel 30 Inner Join 20 CS SJ
3 Peng 40 (dno = dnumber) 30 DS SF

mysql> select * from student inner join dept on dno = dnumber;

+------+-------+------+---------+-------+-----------+
| sid | sname | dno | dnumber | dname | dlocation |
+------+-------+------+---------+-------+-----------+
| 1 | Lee | 20 | 20 | CS | SJ |
| 2 | Patel | 30 | 30 | DS | SF |
+------+-------+------+---------+-------+-----------+

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


84
STUDENT DEPT
sid sname dno dnumber dname dlocation
1 Lee 20 10 EE NY
2 Patel 30 Left Outer Join 20 CS SJ
3 Peng 40 (dno = dnumber) 30 DS SF

mysql> select * from student left outer join dept on dno = dnumber;

+------+-------+------+---------+-------+-----------+
| sid | sname | dno | dnumber | dname | dlocation |
+------+-------+------+---------+-------+-----------+
| 1 | Lee | 20 | 20 | CS | SJ |
| 2 | Patel | 30 | 30 | DS | SF |
| 3 | Peng | 40 | NULL | NULL | NULL |
+------+-------+------+---------+-------+-----------+

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


85
STUDENT DEPT
sid sname dno dnumber dname dlocation
1 Lee 20 10 EE NY
2 Patel 30 Right Outer Join 20 CS SJ
3 Peng 40 (dno = dnumber) 30 DS SF

mysql> select * from student right outer join dept on dno = dnumber;

+------+-------+------+---------+-------+-----------+
| sid | sname | dno | dnumber | dname | dlocation |
+------+-------+------+---------+-------+-----------+
| NULL | NULL | NULL | 10 | EE | NY |
| 1 | Lee | 20 | 20 | CS | SJ |
| 2 | Patel | 30 | 30 | DS | SF |
+------+-------+------+---------+-------+-----------+

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


86
STUDENT DEPT
sid sname dno dnumber dname dlocation
1 Lee 20 10 EE NY
2 Patel 30 Full Outer Join 20 CS SJ
3 Peng 40 (dno = dnumber) 30 DS SF

M y S QL !
mysql> select * from student p p or t
fulled inouter join dept on dno = dnumber;
Not Su
mysql> select * from student left outer join dept on dno = dnumber
-> union
-> select * from student right outer join dept on dno = dnumber;
+------+-------+------+---------+-------+-----------+
| sid | sname | dno | dnumber | dname | dlocation |
+------+-------+------+---------+-------+-----------+
| 1 | Lee | 20 | 20 | CS | SJ |
| 2 | Patel | 30 | 30 | DS | SF |
| 3 | Peng | 40 | NULL | NULL | NULL |
| NULL | NULL |Copyright
NULL© 2016
| Ramez Elmasri
10and|Shamkant
EE B. Navathe
| NY |
87
+------+-------+------+---------+-------+-----------+
Example: LEFT OUTER JOIN

SELECT E.Lname AS Employee_Name


S.Lname AS Supervisor_Name

FROM Employee AS E LEFT OUTER JOIN EMPLOYEE AS S


ON E.Super_ssn = S.Ssn)

ALTERNATE SYNTAX:
SELECT E.Lname , S.Lname
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn = S.Ssn (+)
M y S QL !
p or te d in
p
Not Su g Oracle !!
sin
Only u
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
88
Multiway JOIN in the FROM clause
• FULL OUTER JOIN – combines result if LEFT and RIGHT OUTER JOIN
• Can nest JOIN specifications for a multiway join:

Q2A: SELECT Pnumber, Dnum, Lname, Address, Bdate


FROM ((PROJECT JOIN DEPARTMENT ON Dnum=Dnumber) JOIN EMPLOYEE ON
Mgr_ssn=Ssn)
WHERE Plocation=‘Stafford’;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


89
Aggregate Functions in SQL
• Used to summarize information from multiple tuples into a single-
tuple summary
• Built-in aggregate functions
• COUNT, SUM, MAX, MIN, and AVG
• Grouping
• Create subgroups of tuples before summarizing
• To select entire groups, HAVING clause is used
• Aggregate functions can be used in the SELECT clause or in a
HAVING clause
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
90
Aggregate Functions
● COUNT()
● AVG()
● MAX()
● MIN()
● STD()
● STDDEV()
● SUM()
● More . . .

91
GROUP BY

SELECT DNO, COUNT(*), AVG(SALARY)


FROM EMPLOYEE
GROUP BY DNO;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


92
Renaming Results of Aggregation
• Following query returns a single row of computed values from EMPLOYEE
table:

Q19: SELECT SUM (Salary), MAX (Salary), MIN (Salary),


AVG (Salary)
FROM EMPLOYEE;
• The result can be presented with new names:
Q19A: SELECT SUM (Salary) AS Total_Sal,
MAX (Salary) AS Highest_Sal,
MIN (Salary) AS Lowest_Sal,
AVG (Salary) AS Average_Sal
FROM EMPLOYEE;
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
93
Aggregate Functions in SQL
• NULL values are discarded when aggregate functions are applied to a
particular column

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


94
Aggregate Functions on Booleans
• SOME and ALL may be applied as functions on Boolean Values.
• SOME returns true if at least one element in the collection is TRUE
(similar to OR)
• ALL returns true if all of the elements in the collection are TRUE
(similar to AND)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


95
Grouping: The GROUP BY Clause
• Partition relation into subsets of tuples
• Based on grouping attribute(s)
• Apply function to each such group independently
• GROUP BY clause
• Specifies grouping attributes
• COUNT (*) counts the number of rows in the group

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


96
Examples of GROUP BY
• The grouping attribute must appear in the SELECT clause:
Q24: SELECT Dno, COUNT (*), AVG (Salary)
FROM EMPLOYEE
GROUP BY Dno;
• If the grouping attribute has NULL as a possible value, then a separate group is
created for the null value (e.g., null Dno in the above query)
• GROUP BY may be applied to the result of a JOIN:
Q25: SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


97
Grouping: The GROUP BY and HAVING
Clauses (cont’d.)
• HAVING clause
• Provides a condition to select or reject an entire group:
• Query 26. For each project on which more than two employees work, retrieve the project number,
the project name, and the number of employees who work on the project.

Q26: SELECT Pnumber, Pname, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE Pnumber=Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


98
GROUP BY

Result of Having
SELECTDNO, COUNT(*), AVG(SALARY)
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*) > 3;
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
99
Combining the WHERE and the HAVING
Clause
• Consider the query: we want to count the total number of employees whose
salaries exceed $40,000 in each department, but only for departments where
more than five employees work.

• INCORRECT QUERY:
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000
GROUP BY Dno
HAVING COUNT (*) > 5;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


100
Combining the WHERE and the HAVING
Clause (continued)
Correct Specification of the Query:
• Note: the WHERE clause applies tuple by tuple whereas HAVING
applies to entire group of tuples

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


101
Use of WITH
• The WITH clause allows a user to define a table that will only be used
in a particular query (not available in all SQL implementations)
• Used for convenience to create a temporary “View” and use that
immediately in a query
• Allows a more straightforward way of looking a step-by-step query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


102
Example of WITH
• See an alternate approach to doing Q28:

• Q28’: WITH BIGDEPTS (Dno) AS


( SELECT Dno
FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN BIGDEPTS
GROUP BY Dno;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


103
Use of CASE
• SQL also has a CASE construct
• Used when a value can be different based on certain conditions.
• Can be used in any part of an SQL query where a value is expected
• Applicable when querying, inserting or updating tuples

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


104
EXAMPLE of use of CASE
• The following example shows that employees are receiving different
raises in different departments (A variation of the update U6)

• U6’: UPDATE EMPLOYEE


SET Salary =
CASE WHEN Dno = 5 THEN Salary + 2000
WHEN Dno = 4 THEN Salary + 1500
WHEN Dno = 1 THEN Salary + 3000

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


105
Recursive Queries in SQL
• An example of a recursive relationship between tuples of the same
type is the relationship between an employee and a supervisor.
• This relationship is described by the foreign key Super_ssn of the
EMPLOYEE relation
• An example of a recursive operation is to retrieve all supervisees of a supervisory employee e at
all levels—that is, all employees e¢ directly supervised by e, all employees e¢’ directly supervised
by each employee e¢, all employees e²¢ directly supervised by each employee e², and so on. Thus
the CEO would have each employee in the company as a supervisee in the resulting table.
Example shows such table SUP_EMP with 2 columns (Supervisor,Supervisee(any level)):

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


106
An EXAMPLE of RECURSIVE Query
• Q29: WITH RECURSIVE SUP_EMP (SupSsn, EmpSsn) AS
SELECT SupervisorSsn, Ssn
FROM EMPLOYEE
UNION
SELECT E.Ssn, S.SupSsn
FROM EMPLOYEE AS E, SUP_EMP AS S
WHERE E.SupervisorSsn = S.EmpSsn)
SELECT *
FROM SUP_EMP;
• The above query starts with an empty SUP_EMP and successively builds SUP_EMP table
by computing immediate supervisees first, then second level supervisees, etc. until a
fixed point is reached and no more supervisees can be added
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
107
EXPANDED Block Structure of SQL Queries

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


108
Summary of SQL Syntax

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


109
Summary of SQL Syntax

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


110
Summary
• Complex SQL:
• Nested queries, joined tables (in the FROM clause), outer joins, aggregate
functions, grouping

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


111
Homework
• Exercise Lab 5: Basic SQL
• Assignment 1: Creating University Database
• Assignment 2: More Queries with UNIVERSITY database
• Solve at least 5 queries from Exercise 2. Create SQL script for each query with the
file name including proper number. For example, 1.sql, 2.sql, 3.sql …
• Create a zip file, ex-lab5.zip. Then, submit it on Canvas
• Note: You don’t have to submit Exercise 1 part
• Homework 5:
• SQL
• SQL Workshop
• Submit WS5-3.sql
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
112
[Optional Assignments]
• WATCH: Role of SQL
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=7f7725ef-
b7cb-4c73-a54a-ac52014a1946&start=0
• Quick Review: SQL Style
• https://northeastern.instructure.com/courses/123286/pages/15-min-skim-sql-style-
recommendations
• WATCH: DDL
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=4ac9add4
-98eb-442a-8e5d-abed010a41b7&start=0
• WATCH: Simple SQL
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=b43f7938
-f0d5-4e87-bd86-ac5400292bfd&start=0
• WATCH: Retrieving Select Rows with WHERE
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=e064745c
-71a7-43d0-8c09-accd017ad22d&start=0
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
113
• WATCH: Aggregating Data (Group By)
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=9d
d5c7a0-64aa-4a66-b884-ac9900ec6d6e&start=0
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=d1
200056-3f7b-46cd-b960-ac9900ec9045&start=0
• WATCH: Self-Join
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=aa
7d0c6b-77b5-4360-a730-ac520105ed19&start=0
• WATCH: Sub-Query
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=bf
144f2b-1096-4209-985c-ac9900eca5bb&start=0
• WATCH: JOIN
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=d5
fce32d-7885-4e25-8f42-ac9900ec605e&start=0
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe
114
• WATCH: Reclusive
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=87
af9a63-bf7a-4bc9-8fb8-abe60140d284&start=0
• https://northeastern.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=1d
0c33b6-670f-4411-864b-abe701817843&start=0

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe


115

You might also like