1c. Advanced SQL (Selected) | PDF
0% found this document useful (0 votes)
38 views

1c. Advanced SQL (Selected)

Advanced sql

Uploaded by

The Real Stuff
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

1c. Advanced SQL (Selected)

Advanced sql

Uploaded by

The Real Stuff
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Chapter 7 Outline

 More Complex SQL Retrieval Queries


 Specifying Semantic Constraints as Assertions
and Actions as Triggers
 Views (Virtual Tables) in SQL
 Schema Modification in SQL
Advanced SQL: Complex Queries,
Triggers, Views, and Schema
Modification

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 1 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 3

More Complex SQL Retrieval Comparisons Involving NULL


Queries and Three-Valued Logic
 Meanings of NULL
 Additional features allow users to specify more
complex retrievals from database:  Unknown value
 Nested queries, joined tables, and outer joins (in  Unavailable or withheld value
the FROM clause), aggregate functions, and  Not applicable attribute
grouping  Each individual NULL value considered to be
different from every other NULL value
 SQL uses a three-valued logic:
 TRUE, FALSE, and UNKNOWN (like Maybe)
 NULL = NULL comparison is avoided

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 4 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 5

Comparisons Involving NULL Comparisons Involving NULL


and Three-Valued Logic (cont’d.) 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 Slide 7- 6 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 7

1
Nested Queries, Tuples,
and Set/Multiset Comparisons Nested Queries (cont’d.)
 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 Slide 7- 8 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 9

Nested Queries (cont’d.) Nested Queries (cont’d.)


 Use tuples of values in comparisons  Use other comparison operators to compare a
 Place them within parentheses 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 Slide 7- 10 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 11

Nested Queries (cont’d.) Correlated Nested Queries


 Avoid potential errors and ambiguities  Queries that are nested using the = or IN
 Create tuple variables (aliases) for all tables comparison operator can be collapsed into one
referenced in SQL query single block: E.g., Q16 can be written as:

 Q16A: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT AS D
WHERE E.Ssn=D.Essn AND E.Sex=D.Sex
AND
E.Fname=D.Dependent_name;

 Correlated nested query


 Evaluated once for each tuple in the outer query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 11 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 13

2
The EXISTS and UNIQUE Functions
in SQL for correlating queries USE of EXISTS
 EXISTS function Q7:
 Check whether the result of a correlated nested
SELECT Fname, Lname
query is empty or not. They are Boolean functions FROM Employee
that return a TRUE or FALSE result. WHERE EXISTS (SELECT *
FROM DEPENDENT
 EXISTS and NOT EXISTS WHERE Ssn= Essn)

 Typically used in conjunction with a correlated AND EXISTS (SELECT *


nested query FROM Department
WHERE Ssn= Mgr_Ssn)
 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 Slide 7- 14 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 15

Double Negation to accomplish “for


USE OF NOT EXISTS all” in SQL
To achieve the “for all” (universal quantifier- see Ch.8) effect,  Q3B: SELECT Lname, Fname
FROM EMPLOYEE
we use double negation this way in SQL: WHERE NOT EXISTS ( SELECT *
Query: List first and last name of employees who work on FROM WORKS_ON B
ALL projects controlled by Dno=5. WHERE ( B.Pno IN ( SELECT Pnumber
FROM PROJECT
SELECT Fname, Lname WHERE Dnum=5
FROM Employee AND
WHERE NOT EXISTS ( (SELECT Pnumber
FROM PROJECT NOT EXISTS (SELECT *
WHERE Dno=5) FROM WORKS_ON C
WHERE C.Essn=Ssn
EXCEPT (SELECT Pno AND C.Pno=B.Pno )));
FROM WORKS_ON
The above is a direct rendering of: List names of those employees for whom
WHERE Ssn= ESsn)
there does NOT exist a project managed by department no. 5 that they
The above is equivalent to double negation: List names of those
employees for whom there does NOT exist a project managed by do NOT work on.
department no. 5 that they do NOT work on.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 16 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 16

Explicit Sets and Renaming of Specifying Joined Tables in the


Attributes in SQL FROM Clause of SQL
 Can use explicit set of values in WHERE clause  Joined table
Q17: SELECT DISTINCT Essn  Permits users to specify a table resulting from a
FROM WORKS_ON join operation in the FROM clause of a query
WHERE Pno IN (1, 2, 3);
 The FROM clause in Q1A
 Use qualifier AS followed by desired new name
 Contains a single joined table. JOIN may also be
 Rename any attribute that appears in the result of
called INNER JOIN
a query

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 18 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 19

3
Different Types of JOINed Tables in
SQL NATURAL JOIN
 Specify different types of join  Rename attributes of one relation so it can be joined with
another using NATURAL JOIN:
 NATURAL JOIN
 Various types of OUTER JOIN (LEFT, RIGHT, Q1B: SELECT Fname, Lname, Address
FULL ) FROM (EMPLOYEE NATURAL JOIN
 NATURAL JOIN on two relations R and S (DEPARTMENT AS DEPT (Dname, Dno, Mssn,
Msdate)))
 No join condition specified WHERE Dname=‘Research’;
 Is equivalent to an implicit EQUIJOIN condition for
each pair of attributes with same name from R and The above works with EMPLOYEE.Dno = DEPT.Dno as an
S implicit join condition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 20 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 20

INNER and OUTER Joins Example: LEFT OUTER JOIN


 INNER JOIN (versus OUTER JOIN)
 Default type of join in a joined table
SELECT E.Lname AS Employee_Name
 Tuple is included in the result only if a matching tuple exists S.Lname AS Supervisor_Name
in the other relation
FROM Employee AS E LEFT OUTER JOIN EMPLOYEE AS S
 LEFT OUTER JOIN ON E.Super_ssn = S.Ssn)
 Every tuple in left table must appear in result

 If no matching tuple
ALTERNATE SYNTAX:
 Padded with NULL values for attributes of right table SELECT E.Lname , S.Lname
 RIGHT OUTER JOIN FROM EMPLOYEE E, EMPLOYEE S
WHERE E.Super_ssn + = S.Ssn
 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 Slide 7- 22 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 22

Multiway JOIN in the FROM clause Aggregate Functions in SQL


 FULL OUTER JOIN – combines result if LEFT  Used to summarize information from multiple
and RIGHT OUTER JOIN tuples into a single-tuple summary
 Can nest JOIN specifications for a multiway join:  Built-in aggregate functions
 COUNT, SUM, MAX, MIN, and AVG
Q2A: SELECT Pnumber, Dnum, Lname, Address, Bdate  Grouping
FROM ((PROJECT JOIN DEPARTMENT ON
Dnum=Dnumber) JOIN EMPLOYEE ON  Create subgroups of tuples before summarizing
Mgr_ssn=Ssn)  To select entire groups, HAVING clause is used
WHERE Plocation=‘Stafford’;
 Aggregate functions can be used in the SELECT
clause or in a HAVING clause

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 23 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 24

4
Renaming Results of Aggregation Aggregate Functions in SQL (cont’d.)
 Following query returns a single row of computed values  NULL values are discarded when aggregate
from EMPLOYEE table: functions are applied to a particular column

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 Slide 7- 25 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 26

Aggregate Functions on Booleans Grouping: The GROUP BY Clause


 SOME and ALL may be applied as functions on  Partition relation into subsets of tuples
Boolean Values.  Based on grouping attribute(s)
 SOME returns true if at least one element in the  Apply function to each such group independently
collection is TRUE (similar to OR)  GROUP BY clause
 ALL returns true if all of the elements in the  Specifies grouping attributes
collection are TRUE (similar to AND)  COUNT (*) counts the number of rows in the
group

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 27 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 28

Grouping: The GROUP BY and


Examples of GROUP BY HAVING Clauses (cont’d.)
 The grouping attribute must appear in the SELECT  HAVING clause
clause:
 Provides a condition to select or reject an entire
Q24: SELECT Dno, COUNT (*), AVG (Salary)
group:
FROM EMPLOYEE
 Query 26. For each project on which more than two employees work,
GROUP BY Dno;
retrieve the project number, the project name, and the number of
 If the grouping attribute has NULL as a possible value, employees who work on the project.
then a separate group is created for the null value (e.g.,
null Dno in the above query) Q26: SELECT Pnumber, Pname, COUNT (*)
 GROUP BY may be applied to the result of a JOIN: FROM PROJECT, WORKS_ON
Q25: SELECT Pnumber, Pname, COUNT (*) WHERE Pnumber=Pno
FROM PROJECT, WORKS_ON GROUP BY Pnumber, Pname
WHERE Pnumber=Pno HAVING COUNT (*) > 2;
GROUP BY Pnumber, Pname;
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 29 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 31

5
Combining the WHERE and the Combining the WHERE and the
HAVING Clause HAVING Clause (continued)
 Consider the query: we want to count the total number of Correct Specification of the Query:
employees whose salaries exceed $40,000 in each
 Note: the WHERE clause applies tuple by tuple
department, but only for departments where more than
five employees work. whereas HAVING applies to entire group of
tuples
 INCORRECT QUERY:
SELECT Dno, COUNT (*)
FROM EMPLOYEE
WHERE Salary>40000
GROUP BY Dno
HAVING COUNT (*) > 5;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 31 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 32

Use of WITH Example of WITH


 The WITH clause allows a user to define a table  See an alternate approach to doing Q28:
that will only be used in a particular query (not
 Q28’: WITH BIGDEPTS (Dno) AS
available in all SQL implementations) ( SELECT Dno
FROM EMPLOYEE
 Used for convenience to create a temporary GROUP BY Dno
“View” and use that immediately in a query HAVING COUNT (*) > 5)
SELECT Dno, COUNT (*)
 Allows a more straightforward way of looking a FROM EMPLOYEE
step-by-step query WHERE Salary>40000 AND Dno IN BIGDEPTS
GROUP BY Dno;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 33 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 34

Use of CASE EXAMPLE of use of CASE


 SQL also has a CASE construct  The following example shows that employees are
 Used when a value can be different based on receiving different raises in different departments
certain conditions. (A variation of the update U6)
 Can be used in any part of an SQL query where a
 U6’: UPDATE EMPLOYEE
value is expected SET Salary =
 Applicable when querying, inserting or updating CASE WHEN Dno = 5THEN Salary + 2000
tuples WHEN Dno = 4THEN Salary + 1500
WHEN Dno = 1THEN Salary + 3000

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 35 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 36

6
Recursive Queries in SQL An EXAMPLE of RECURSIVE Query
Q29: WITH RECURSIVE SUP_EMP (SupSsn, EmpSsn) AS
 An example of a recursive relationship between 

SELECT SupervisorSsn, Ssn


tuples of the same type is the relationship FROM EMPLOYEE
between an employee and a supervisor. UNION
SELECT E.Ssn, S.SupSsn
 This relationship is described by the foreign key FROM EMPLOYEE AS E, SUP_EMP AS S
Super_ssn of the EMPLOYEE relation WHERE E.SupervisorSsn = S.EmpSsn)
 An example of a recursive operation is to retrieve all supervisees of SELECT *
a supervisory employee e at all levels—that is, all employees e FROM SUP_EMP;
directly supervised by e, all employees e’ directly supervised by each
 The above query starts with an empty SUP_EMP and
employee e, all employees e directly supervised by each employee
e, and so on. Thus the CEO would have each employee in the successively builds SUP_EMP table by computing
company as a supervisee in the resulting table. Example shows such immediate supervisees first, then second level
table SUP_EMP with 2 columns (Supervisor,Supervisee(any level)): supervisees, etc. until a fixed point is reached and no
more supervisees can be added
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 37 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 38

EXPANDED Block Structure of SQL


Specifying Constraints as Assertions
Queries
and Actions as Triggers

 Semantic Constraints: The following are beyond


the scope of the EER and relational model
 CREATE ASSERTION
 Specify additional types of constraints outside
scope of built-in relational model constraints
 CREATE TRIGGER
 Specify automatic actions that database system
will perform when certain events and conditions
occur

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 40 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 41

Specifying General Constraints as


Assertions in SQL Introduction to Triggers in SQL
 CREATE ASSERTION  CREATE TRIGGER statement
 Specify a query that selects any tuples that violate  Used to monitor the database
the desired condition  Typical trigger has three components which make
 Use only in cases where it goes beyond a simple it a rule for an “active database “ (more on active
CHECK which applies to individual attributes and databases in section 26.1) :
domains
 Event(s)
 Condition
 Action

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 41 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 43

7
USE OF TRIGGERS Views (Virtual Tables) in SQL
 AN EXAMPLE with standard Syntax.(Note : other  Concept of a view in SQL
SQL implementations like PostgreSQL use a  Single table derived from other tables called the
different syntax.) defining tables
 Considered to be a virtual table that is not
R5: necessarily populated
CREATE TRIGGER SALARY_VIOLATION
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)

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 44 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 45

Specification of Views in SQL


Specification of Views in SQL (cont’d.)
 CREATE VIEW command  Once a View is defined, SQL queries can use the
 Give table name, list of attribute names, and a query to View relation in the FROM clause
specify the contents of the view  View is always up-to-date
 In V1, attributes retain the names from base tables. In
 Responsibility of the DBMS and not the user
V2, attributes are assigned names
 DROP VIEW command
 Dispose of a view

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 46 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 47

View Implementation, View Update,


and Inline Views View Materialization
 Complex problem of efficiently implementing a  Strategy 2: View materialization
view for querying  Physically create a temporary view table when the
 Strategy1: Query modification approach view is first queried
 Compute the view as and when needed. Do not  Keep that table on the assumption that other
store permanently queries on the view will follow
 Modify view query into a query on underlying base  Requires efficient strategy for automatically updating
tables the view table when the base tables are updated
 Disadvantage: inefficient for views defined via  Incremental update strategy for materialized
complex queries that are time-consuming to views
execute  DBMS determines what new tuples must be inserted,
deleted, or modified in a materialized view table
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 48 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 49

8
View Materialization (contd.) View Update
 Multiple ways to handle materialization:  Update on a view defined on a single table without any
aggregate functions
 immediate update strategy updates a view as
 Can be mapped to an update on underlying base
soon as the base tables are changed
table- possible if the primary key is preserved in the
 lazy update strategy updates the view when view
needed by a view query
 Update not permitted on aggregate views. E.g.,
 periodic update strategy updates the view UV2: UPDATE DEPT_INFO
periodically (in the latter strategy, a view query SET Total_sal=100000
may get a result that is not up-to-date). This is WHERE Dname=‘Research’;
commonly used in Banks, Retail store operations, cannot be processed because Total_sal is a computed value
etc. in the view definition

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 49 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 51

View Update and Inline Views Views as authorization mechanism


 View involving joins  SQL query authorization statements (GRANT and
REVOKE) are described in detail in Chapter 30
 Often not possible for DBMS to determine which
of the updates is intended  Views can be used to hide certain attributes or
 Clause WITH CHECK OPTION tuples from unauthorized users
 Must be added at the end of the view definition if a  E.g., For a user who is only allowed to see
view is to be updated to make sure that tuples employee information for those who work for
being updated stay in the view department 5, he may only access the view
DEPT5EMP:
 In-line view CREATE VIEW DEPT5EMP AS
 Defined in the FROM clause of an SQL query (e.g., SELECT *
we saw its used in the WITH example) FROM EMPLOYEE
WHERE Dno = 5;

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 51 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 52

Schema Change Statements in SQL The DROP Command


 Schema evolution commands  DROP command
 DBA may want to change the schema while the  Used to drop named schema elements, such as
database is operational tables, domains, or constraint
 Does not require recompilation of the database  Drop behavior options:
schema  CASCADE and RESTRICT
 Example:
 DROP SCHEMA COMPANY CASCADE;
 This removes the schema and all its elements
including tables,views, constraints, etc.

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 54 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 55

9
The ALTER table command Adding and Dropping Constraints
 Alter table actions include:  Change constraints specified on a table
 Adding or dropping a column (attribute)  Add or drop a named constraint
 Changing a column definition
 Adding or dropping table constraints
 Example:
 ALTER TABLE COMPANY.EMPLOYEE ADD
COLUMN Job VARCHAR(12);

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 56 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 57

Table 7.2 Summary of SQL


Dropping Columns, Default Values Syntax
 To drop a column
 Choose either CASCADE or RESTRICT
 CASCADE would drop the column from views etc.
RESTRICT is possible if no views refer to it.
ALTER TABLE COMPANY.EMPLOYEE DROP COLUMN
Address CASCADE;
 Default values can be dropped and altered :
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn
DROP DEFAULT;
ALTER TABLE COMPANY.DEPARTMENT ALTER COLUMN Mgr_ssn SET
DEFAULT ‘333445555’;

continued on next slide

Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 57 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 59

Table 7.2 (continued)


Summary of SQL Syntax Summary
 Complex SQL:
 Nested queries, joined tables (in the FROM
clause), outer joins, aggregate functions, grouping
 Handling semantic constraints with CREATE
ASSERTION and CREATE TRIGGER
 CREATE VIEW statement and materialization
strategies
 Schema Modification for the DBAs using ALTER
TABLE , ADD and DROP COLUMN, ALTER
CONSTRAINT etc.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 60 Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe Slide 7- 61

10

You might also like