chapter 8: sql-99

99
Chapter 8: SQL-99 Chapter 8: SQL-99 [email protected] 1 www.bookspar.com | Website for students | VTU NOTES

Upload: keefer

Post on 15-Jan-2016

50 views

Category:

Documents


0 download

DESCRIPTION

Chapter 8: SQL-99. [email protected]. Objectives. SQL standard Data Definitions, Constraints, and Schema Changes in SQL2 Queries in SQL (basic and complex SQL Queries) Update operations (delete, insert, and update statements) Views (or Virtual Tables ) in SQL - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 8: SQL-99

Chapter 8: SQL-99Chapter 8: [email protected]

1www.bookspar.com | Website for students | VTU NOTES

Page 2: Chapter 8: SQL-99

ObjectivesObjectivesSQL standard

◦Data Definitions, Constraints, and Schema Changes in SQL2

◦Queries in SQL (basic and complex SQL Queries)

◦Update operations (delete, insert, and update statements)

◦Views (or Virtual Tables ) in SQL◦Specifying General Constraints as

Assertions

2www.bookspar.com | Website for students | VTU NOTES

Page 3: Chapter 8: SQL-99

History of SQLHistory of SQLSQL stands for Structured Query

LanguageDeveloped by IBMadopted as standard language

for commercial RDBMS:◦ SQL-86 (or SQL-1) joint effort by ANSI and OSI◦ SQL-92 (or SQL2)◦ SQL-99( or SQL3)

CORE OPTIONAL

3www.bookspar.com | Website for students | VTU NOTES

Page 4: Chapter 8: SQL-99

SQL (cont.)SQL (cont.)

A comprehensive non-procedural database language package that supports standard◦Supports both DDL and DML ◦Provides facilities to specify security,

authorization, and constraints

4www.bookspar.com | Website for students | VTU NOTES

Page 5: Chapter 8: SQL-99

SQL Data Definition and Data SQL Data Definition and Data typestypesSQL uses

◦ Table (or relation)◦ Row (or tuple)◦ Column (or attribute)

Data Definition Commands◦ Create Schema ◦ Create tables ◦ Create Domain◦ Create view◦ Alter Table/Schema◦ Drop Table/Schema

5www.bookspar.com | Website for students | VTU NOTES

Page 6: Chapter 8: SQL-99

SchemaSchemaSQL schema

◦Used to group tables and related constructs

◦identified by Schema Name Elements

tables constraints view, domains authorization constructs

6www.bookspar.com | Website for students | VTU NOTES

Page 7: Chapter 8: SQL-99

Create SchemaCreate SchemaSchema is created using

◦CREATE SCHEMA◦E.g.,

CREATE SCHEMA Company AUTHORIZATION JSMITH

JSMITH is the Schema Owner ◦Catalog

Named collection of schemas Information_schema

7www.bookspar.com | Website for students | VTU NOTES

Page 8: Chapter 8: SQL-99

Create Table Command in Create Table Command in SQLSQLCREATE TABLE

◦used to specify a new relation (or base table) CREATE TABLE EMPLOYEE CREATE TABLE COMPANY.EMPLOYEE

◦CREATE VIEW Used to create virtual tables

◦Attributes are ordered

8www.bookspar.com | Website for students | VTU NOTES

Page 9: Chapter 8: SQL-99

Create table: exampleCreate table: example CREATE TABLE DEPARTMENT (

DNAME VARCHAR(10) NOT NULL,DNUMBER INTEGER NOT NULL,MGRSSN CHAR(9),MGRSTARTDATE CHAR(9) );

9www.bookspar.com | Website for students | VTU NOTES

Page 10: Chapter 8: SQL-99

More exampleMore example Key attributes can be specified via the PRIMARY KEY and

UNIQUE phrasesCREATE TABLE DEPT (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(SSN) );

10www.bookspar.com | Website for students | VTU NOTES

Page 11: Chapter 8: SQL-99

SQL: Basic Data TypesSQL: Basic Data Types◦ Basic Data types

Numeric Integer, Real

Char string Fixed length (CHAR(n)) Varying length (VARCHAR(n)

bit-string, Fixed (BIT(n)) or varying VARYING(n)

date/time Boolean (T,F, Unknown) Timestamps (includes both date and time)

11www.bookspar.com | Website for students | VTU NOTES

Page 12: Chapter 8: SQL-99

SQL: User Defined Data SQL: User Defined Data TypeType

◦User defined data type Domain in SQL

CREATE DOMAIN SSN_TYPE AS CHAR (9);

12www.bookspar.com | Website for students | VTU NOTES

Page 13: Chapter 8: SQL-99

Specifying Constraints Specifying Constraints using SQLusing SQLConstraints and default values

can be specified on each ◦attributes◦tuple◦table

13www.bookspar.com | Website for students | VTU NOTES

Page 14: Chapter 8: SQL-99

Specifying NULL and Default ValuesNULLS can be used as attribute

valuesA NOT NULL constraint can be

used to specify that NULL is not permitted

DEFAULT Value

www.bookspar.com | Website for students | VTU NOTES 14

Page 15: Chapter 8: SQL-99

15

www.bookspar.com | Website for students | VTU NOTES 15

Page 16: Chapter 8: SQL-99

CHECK Clause

CHECK Clause ◦ Used to restrict attribute or domain values

E.g.,◦ To restrict department numbers between

integer 1-20 integer DNUMBER INT NOT NULL CHECK (DNUMBER>0 AND

DNUMBER <21)◦ Check clause can also be used to create the

domain CREATE DOMAIN D_NUM AS INTEGER CHECK (D_NUM>0

AND D_NUM <21) D_NUM can be used as attribute domain for

DNO Dnumber Dum

www.bookspar.com | Website for students | VTU NOTES 16

Page 17: Chapter 8: SQL-99

Specifying Key and Specifying Key and referential Integrity referential Integrity ConstraintsConstraints◦PRIMARY KEY CLUASE used to

specify PK E.g., PRIMARY KEY (DNUMBER); E.g., Dnumber INT PRIMARY KEY;

◦FOREIGN KEY CLUASE used to specify FK FOREIGN KEY (DNUMBER) REFERENCES

DEPARTMENT (DUNMBER)

◦UNIQUE CLAUSE Used for secondary keys

◦ Figure 8.1

17www.bookspar.com | Website for students | VTU NOTES

Page 18: Chapter 8: SQL-99

18www.bookspar.com | Website for students | VTU NOTES

Page 19: Chapter 8: SQL-99

Violation of Integrity Violation of Integrity Constraints (IC)Constraints (IC) Update/delete/insertion of tuples may violate

referential integrity constraints◦ The default action is Reject the operation

Schema Designer can specify an alternative action using referential triggered action clause to any FK constraint◦ Option include

SET DEFAULT SET NULL CASACADE

◦Option must be qualified ON DELETE or ON UPDATE

19www.bookspar.com | Website for students | VTU NOTES

Page 20: Chapter 8: SQL-99

20

Referential IntegrityReferential Integrity

MINT

EMPLOEE

FNAME LNAME SSN BDATE ADDRESS SEX SUPERSSN DNO

DEPT

DEPT_LOC

SNAME DNUM MGRSSNMSDATE

DNUM DLOC

DNO should be Null or

should match a PK of DEPT

www.bookspar.com | Website for students | VTU NOTES 20

Page 21: Chapter 8: SQL-99

21www.bookspar.com | Website for students | VTU NOTES

Page 22: Chapter 8: SQL-99

Named constraintsNamed constraintsNames to constraints

◦Used to identify/modify a particular constraint

◦Works like CONSTANT declaration in Program Languages

◦ Figure 8.2

22www.bookspar.com | Website for students | VTU NOTES

Page 23: Chapter 8: SQL-99

23

www.bookspar.com | Website for students | VTU NOTES 23

Page 24: Chapter 8: SQL-99

Specifying Constraints on Specifying Constraints on Tuples Using CHECKTuples Using CHECK

◦Used at the end of schema◦Applies to individual tuples◦Use CHECK for more general

constraints E.g.,

CHECK (DEPT_CREATE_DATE < MGRSTARTDATE);

24www.bookspar.com | Website for students | VTU NOTES

Page 25: Chapter 8: SQL-99

SCHEMA CHANGE SCHEMA CHANGE COMMANDS IN SQLCOMMANDS IN SQLTHE DROP COMMAND

◦CASCADE◦RESTRICT◦Used to drop the named schema

elements from database schema◦E.g.,

DROP SCHEMA COMPANY CASCADE DROP TABLE DEPENDENT CASCADE

◦RESTRCIT Used to drop the schema if it has no

elements in it◦Delete vs. Drop

Use delete if you want to delete the records but not the table definition

25www.bookspar.com | Website for students | VTU NOTES

Page 26: Chapter 8: SQL-99

The ALTER TABLE The ALTER TABLE CommandCommandUsed to change the definition of

base table◦ E.g.,

ALTER TABLE COMPANY.EMPLOYEE ADD JOB VARCHAR(12)

ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS CASCADE;

ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN DROP DEFAULT;

ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN SET DEFAULT “344556677”

ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK CASCADE

26www.bookspar.com | Website for students | VTU NOTES

Page 27: Chapter 8: SQL-99

Basic Queries in SQLBasic Queries in SQLSQL has only one basic

statement to retrieve information ◦SELECT◦FROM◦WHERE

no relationship to the operation of relational algebra

Important features◦supports the notion of multi-set (or

Bag)

27www.bookspar.com | Website for students | VTU NOTES

Page 28: Chapter 8: SQL-99

The Select-From-Where The Select-From-Where Structure of SQL QueriesStructure of SQL QueriesGeneral Form:

◦SELECT <attributes list>◦FROM <tables list>◦WHERE <condition>;

28www.bookspar.com | Website for students | VTU NOTES

Page 29: Chapter 8: SQL-99

Some example: Query 0Some example: Query 0Get the birthday and address of

the employee(s) whose name is ‘John B. Smith’◦SELECT BDATE, ADDRESS◦FROM EMPLOYEE◦WHERE FNAME=‘John’ AND MINIT

=‘B’ AND LNAME = ‘SMITH’

29www.bookspar.com | Website for students | VTU NOTES

Page 30: Chapter 8: SQL-99

30www.bookspar.com | Website for students | VTU NOTES

Page 31: Chapter 8: SQL-99

Query 1Query 1Get the name and address of

all employee who work for the ‘Research’ Dept.◦SELECT FNAME, LNAME, ADDRESS ◦FROM EMPLOYEE, DEPARTMENT◦WHERE DNAME=‘Research’ AND

DNUMBER =DNO

31www.bookspar.com | Website for students | VTU NOTES

Page 32: Chapter 8: SQL-99

Query 2Query 2

For every project located in ‘Stafford’, list the project number, the controlling department number, and the department manager’s last name, address, and birthrate◦ SELECT PNUMBER, DNUM, LNAME, ADDRESS, BDATE

◦ FROM PROJECT, DEPARTMENT, EMPLOYEE

◦ WHERE DNUM=DNUMBER AND MGRSSN=SSN

AND PLOCATION = ‘Stafford’

32www.bookspar.com | Website for students | VTU NOTES

Page 33: Chapter 8: SQL-99

Ambiguous Attribute Names and Ambiguous Attribute Names and

RenamingRenaming In SQL, same name can be used

◦For more than one attribute in different tables

◦used in recursive queries

33www.bookspar.com | Website for students | VTU NOTES

Page 34: Chapter 8: SQL-99

Example 1: Same name Example 1: Same name different tablesdifferent tablesTo remove ambiguity, we need to

qualify the attributes : use ‘.’ separator to qualify the attribute

e.g., suppose LNAME=NAME, and DNO=DNUMBER , DNAME=NAME SELECT FNAME, EMPLOYEE.NAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE DEPARTMENT.DNUMBER =

EMPLOYEE.DNUMBER AND DEPARTMENT.NAME = ‘Research

34www.bookspar.com | Website for students | VTU NOTES

Page 35: Chapter 8: SQL-99

Example 2: Recursive Example 2: Recursive relationshipsrelationshipsFor each employee, find the

employee’s first and last name and the first and last name of her/his immediate supervisor◦ SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME◦ FROM EMPLOYEE AS E, EMPLOYEE AS S◦ WHERE E.SUPERSSN=S.SSN

35www.bookspar.com | Website for students | VTU NOTES

Page 36: Chapter 8: SQL-99

Result of QueryE.Fname E.Lname S.Fname S.Lname

Jongm Smith Franklin Wong

Franklin Wong James Borg

Alicia Zelaya Jennifer Wallace

… … … …

.

www.bookspar.com | Website for students | VTU NOTES 36

Page 37: Chapter 8: SQL-99

SQL: Unspecified WHERE-SQL: Unspecified WHERE-ClauseClauseNo WHERE-clause means no

conditions No condition means Cross

product operations ()

37www.bookspar.com | Website for students | VTU NOTES

Page 38: Chapter 8: SQL-99

Example Q10: No WHERE Example Q10: No WHERE ClauseClauseGet all combinations of

EMPLOYEE.SSN and DEPARTMENT.DNAME ◦SELECT SSN, DNAME◦FROM EMPLOYEE, DEPARTMENT

Get all Employee SSN◦SELECT SSN◦FROM EMPLOYEE

38www.bookspar.com | Website for students | VTU NOTES

Page 39: Chapter 8: SQL-99

Example: Use of ‘*’ in Example: Use of ‘*’ in selectselectUse * to get all attributesGet all employees working for Dept. 5

◦SELECT *◦FROM EMPLOYEE◦WHERE DNO=5

E.g., 2◦SELECT *◦FROM EMPLOYEE, DEPARTMENT;◦WHERE DNO=5 and Dname=‘Research’

39www.bookspar.com | Website for students | VTU NOTES

Page 40: Chapter 8: SQL-99

Tables as Set in SQLTables as Set in SQL SQL treats tables as a multi-set (i.e., a set

having duplicates) Why?

◦ Duplicate elimination is an expensive operation (sort and delete)

◦ user may be interested in the result of a query◦ in case of aggregate function, we do not want to

eliminate duplicatesSQL Table with a key is a SET by definition

◦ Why? Because key must be unique To treat tables as sets use DISTINCT in

SELECT statement

40www.bookspar.com | Website for students | VTU NOTES

Page 41: Chapter 8: SQL-99

Query 11 (Query 11 (ALLALL))◦Retrieve the salary of every employee,

SELECT ALL SALARY FROM EMPLOYEE

41

Salary

3000

4000

2500

2500

www.bookspar.com | Website for students | VTU NOTES

Page 42: Chapter 8: SQL-99

Query 12 (Query 12 (DISTINCTDISTINCT))Get the salary of every employee

USING distinct (set)◦SELECT DISTINCT SALARY◦FROM EMPLOYEE

42

Salary

3000

4000

2500

4300

5500

…www.bookspar.com | Website for students | VTU NOTES

Page 43: Chapter 8: SQL-99

SQL and NULLSQL and NULL

NULL represents◦ Value is not known

e.g., an unknown address◦ Value is not available

E.g., unlisted phone number◦ Value does not apply

E.g., Unmarried employee has no name for his/her spouse

43www.bookspar.com | Website for students | VTU NOTES

Page 44: Chapter 8: SQL-99

NULL and Comparison Operators Comparisons involving NULL

◦ When NULL is involved in comparison, then the result considered to be unknown

◦ Unknown (maybe true or maybe false) SQL uses 3-valued logic

◦ TRUE,◦ FALSE, ◦ UNKNOWN

How define the SQL evaluate the 3-valued logical expressions involving ◦ AND◦ OR ◦ NOT

www.bookspar.com | Website for students | VTU NOTES 44

Page 45: Chapter 8: SQL-99

Truth table for 3-valued logicTruth table for 3-valued logicx y x AND y x OR y Not x

TRUE TRUE TRUE TRUE FALSE

TRUE UNKNOWN UNKNOWN TRUE FALSE

TRUE FALSE FALSE TRUE FALSE

UNKNOWN TRUE UNKNOWN TRUE UNKNOWN

UNKNOWN UNKNOWN UNKNOWN UNKNOWN UNKNOWN

UNKNOWN FALSE FALSE UNKNOWN UNKNOWN

FALSE TRUE FALSE TRUE TRUE

FALSE UNKNOWN FALSE UNKNOWN TRUE

FALSE FALSE FALSE FALSE TRUE

45www.bookspar.com | Website for students | VTU NOTES

Page 46: Chapter 8: SQL-99

More on 3-valueIn SELECT-PROJECT-JOIN queries,

only those combinations of tuples that are evaluated to TRUE are selected

www.bookspar.com | Website for students | VTU NOTES 46

Page 47: Chapter 8: SQL-99

Query involved NULLQuery involved NULLQ18: Get the names of all

employees who do not have supervisors◦SELECT Fname, Lname◦FROM EMPLOYEE◦WHER Super_ssn IS NULL

47www.bookspar.com | Website for students | VTU NOTES

Page 48: Chapter 8: SQL-99

Query using Query using Union, Union, Intersection, EXECEPTIntersection, EXECEPTComplex SQL queries can be

formulated using ◦UNION◦INTERSECTION◦EXECEPT

48www.bookspar.com | Website for students | VTU NOTES

Page 49: Chapter 8: SQL-99

Example of UNION: Q4AExample of UNION: Q4AMake a list of Project numbers for

projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manger of the department that controls the project

49www.bookspar.com | Website for students | VTU NOTES

Page 50: Chapter 8: SQL-99

Query 4: Using Union Query 4: Using Union QueryQuery

◦ (SELECT DISTINCT PNUMBER ◦ FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME=‘Smith’)◦ UNION◦ (SELECT DISTINCT PNUMBER ◦ FROM WORKS_ON, EMPLOYEE , PROJECT◦ WHERE PNUMBR = PNO AND ESSN=SSN AND

LNAME=‘Smith’)

50www.bookspar.com | Website for students | VTU NOTES

Page 51: Chapter 8: SQL-99

Complex SQL Queries: Complex SQL Queries: Nested QueriesNested QueriesSome queries need the existing

values in the database to be retrieved & compared

Nested queries ◦used to formulate such queries

51www.bookspar.com | Website for students | VTU NOTES

Page 52: Chapter 8: SQL-99

Q4: Using Nested queryQ4: Using Nested queryMake a list of Project numbers for

projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manger of the department that controls the project

52www.bookspar.com | Website for students | VTU NOTES

Page 53: Chapter 8: SQL-99

Query Q4A: Using nested Query Q4A: Using nested queryquery

SELECT DISTINCT PNUMBER FROM PROJECT

WHERE PNUMBER IN (SELECT PNUMBER

FROM DEPARTMENT, EMPLOYEE , PROJECT WHERE DNUM = DNUMBE AND MGRSSN = SSN AND LNAME =

‘Smith’) OR

PNUMBER IN ( SELECT PNO

FROM WORKS_ON, EMPLOYEE WHERE ESSN=SSN AND LNAME = ‘Smith’);

53www.bookspar.com | Website for students | VTU NOTES

Page 54: Chapter 8: SQL-99

Correlated nested queriesCorrelated nested queriesCorrelated Queries:

◦When a condition in WHERE clause of a nested query references attribute(s) of a relation defined in the outer query

54www.bookspar.com | Website for students | VTU NOTES

Page 55: Chapter 8: SQL-99

Query 16:Example of Query 16:Example of Correlated queryCorrelated query Get the name of each employee who has a

dependent with the same first name and the same sex as the employee

SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN

FROM DEPENDENT

WHERE E.FNAME=DEPENDENT_NAME

AND E.SEX=SEX);

55www.bookspar.com | Website for students | VTU NOTES

Page 56: Chapter 8: SQL-99

Q16B: Alternative QueryQ16B: Alternative QueryA nested query involving ‘=‘ or ‘IN’ can be

replaced by simple query◦ SELECT E.FNAME,E.LNAME◦ FROM EMPLOYEE AS E, DEPEDENT AS D◦ WHERE E.SSN=D.ESSN AND E.FNAME=D.DEPENDENT_NAME

AND E.SEX=D.SEX;

56www.bookspar.com | Website for students | VTU NOTES

Page 57: Chapter 8: SQL-99

More on Set comparisonsMore on Set comparisonsGet SSN of all employees who

work on the same combination (project, hours) on some project that employee ‘John Smith’ with SSN=‘123456789’◦ SELECT DISTINCT ESSN◦ FROM WORKS_ON◦ WHERE (PNO, HOURS) IN (SELECT PNO, HOURS FROM WORKS_ON WHERE ESSN=‘123456789’)

57www.bookspar.com | Website for students | VTU NOTES

Page 58: Chapter 8: SQL-99

THE EXISTS AND UNIQUE THE EXISTS AND UNIQUE FUNCTIONS IN SQLFUNCTIONS IN SQLEXISTS:

◦Checks the result (i.e, SET) of the correlated nested query to see if it is empty or not If the result (i.e., set) is non-empty it

returns TRUE If the result is empty it returns FALSE

58www.bookspar.com | Website for students | VTU NOTES

Page 59: Chapter 8: SQL-99

Query 16: example of Query 16: example of EXISTS EXISTS Find the name of each employee

who has a dependent with the same first name and same sex as the employee◦SELECT E.FNAME, E.LNAME◦FROM EMPLOYEE AS E◦WHERE EXISTS ( SELECT * ◦ FROM DEPENDENT ◦ WHERE E.SSN=ESSN

AND SEX=E.SEX AND E.FNAME=DEPENT_NAME)

59www.bookspar.com | Website for students | VTU NOTES

Page 60: Chapter 8: SQL-99

Query 16: example of NOT Query 16: example of NOT EXISTS EXISTS Find the name of each employee

who has no dependent ◦ SELECT FNAME, LNAME◦ FROM EMPLOYEE E◦ WHERE NOT EXISTS ◦ (SELECT * ◦ FROM DEPENDENT ◦ WHERE SSN=ESSN)

60www.bookspar.com | Website for students | VTU NOTES

Page 61: Chapter 8: SQL-99

EXPLICIT SETS AND NULLS EXPLICIT SETS AND NULLS IN SQLIN SQLRetrieve SSNs of all employees

who work on project number 12,22,or 33◦SELECT DISTINCT ESSN◦FROM WORKS_ON◦WHERE PNO IN (12,22,33)

61www.bookspar.com | Website for students | VTU NOTES

Page 62: Chapter 8: SQL-99

Join (revisited): FROM Join (revisited): FROM CLAUSECLAUSEJoin operation can be specified in

FROM clause◦Understandability◦Use AS construct to Rename join

attributes◦Default is inner join

62www.bookspar.com | Website for students | VTU NOTES

Page 63: Chapter 8: SQL-99

Example 1: Join in FORMExample 1: Join in FORMFind the name and address of

employees who work in Research department◦SELECT FNAME, LNAME, ADDRESS◦FROM (EMPLOYEE JOIN DEPARTMENT

ON DNO=DNUMBER)

◦WHERE DNAME = ‘Research’

63www.bookspar.com | Website for students | VTU NOTES

Page 64: Chapter 8: SQL-99

Example 2: Renaming and Example 2: Renaming and NATURAL JOINNATURAL JOIN

◦SELECT FNAME, LNAME, ADDRESS◦FROM ( EMPLOYEE NATURAL JOIN

(DEPARTMENT AS DEPT (DNAME, DNO, MSSN, MSDATE)))

◦WHERE DNAME =‘Research’

64www.bookspar.com | Website for students | VTU NOTES

Page 65: Chapter 8: SQL-99

The keyword ALLThe keyword ALLALL is comparison operatorsCan be used with any other

comparison operators◦ E.g.

v> ALL V where V is a SET It returns TRUE if v > every element in V

65www.bookspar.com | Website for students | VTU NOTES

Page 66: Chapter 8: SQL-99

Example KEYWORD ALLExample KEYWORD ALLget the names of all employees

whose salary is greater than the salary of ALL the employees in department 5◦SELECT LNAME, FNAME◦FROM EMPLOYEE◦WHERE SALARY > ALL

(SELECT SALARY FROM EMPLOYEE WHERE DNO=5);

66www.bookspar.com | Website for students | VTU NOTES

Page 67: Chapter 8: SQL-99

SCOPE of nested queriesSCOPE of nested queriesE.g.,

◦SELECT E.FNAME, E.LNAME◦FROM EMPLOYEE AS E◦WHERE E.SSN ◦IN (SELECT ESSN FROM DEPENDENT ◦ WHERE ESSN=E.SSN AND

E.FNAM=DEPENDENT_NAME AND SEX=E.SEX

67www.bookspar.com | Website for students | VTU NOTES

Page 68: Chapter 8: SQL-99

Aggregate FunctionsAggregate FunctionsQ20: Find the sum of the salaries of all employees

in the ‘Research’ dept, as well as the max salary, the min salary, and average in that dept.

◦SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY) AVG(SALARY)

◦FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT(Dname, Dno, Mssn, Msdate)))

◦WHERE DNAME=‘Research’

68www.bookspar.com | Website for students | VTU NOTES

Page 69: Chapter 8: SQL-99

Example of grouping and Example of grouping and COUNTCOUNT GROUP BY CLUASE

◦ Used to partition the relation into sub-relation◦ Works with aggregate functions (e.g. COUNT)

grouping attribute Grouping attribute (s) need to be specified in SELECT clause Create separate group for the grouping attribute with NULL

values

69www.bookspar.com | Website for students | VTU NOTES

Page 70: Chapter 8: SQL-99

QUERY 24 (GROUP BY)QUERY 24 (GROUP BY)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; Figure.8.6.(a)

70www.bookspar.com | Website for students | VTU NOTES

Page 71: Chapter 8: SQL-99

Figure 8.4Figure 8.4

71www.bookspar.com | Website for students | VTU NOTES

Page 72: Chapter 8: SQL-99

HAVING ClauseHAVING ClauseUsed with GROUP BY clauseUsed as a condition on the sub-

relations or groups◦ Groups satisfying the conditions are selected

72www.bookspar.com | Website for students | VTU NOTES

Page 73: Chapter 8: SQL-99

Query 26Query 26For each project on which more than two

employees work, get the project number, the project name, the number of employees who work on the project◦SELECT PNUMBER, PNAME, COUNT(*)◦FROM PROJECT, WORKS_ON◦WHERE PNUMBER=PNO◦GROUP BY PNAME, PNUMBER◦HAVING COUNT(*)>2;◦Fig.8.6.(b) and (c)

73www.bookspar.com | Website for students | VTU NOTES

Page 74: Chapter 8: SQL-99

Figure 8.4Figure 8.4

74www.bookspar.com | Website for students | VTU NOTES

Page 75: Chapter 8: SQL-99

Q28: COUNT and HAVING Q28: COUNT and HAVING Clauses (revisited)Clauses (revisited)Count the total number of

employees whose salaries exceed $40,000 in each department, but only for department where more than five employees work

75www.bookspar.com | Website for students | VTU NOTES

Page 76: Chapter 8: SQL-99

Version 1: ?Version 1: ?SELECT DNAME, COUNT (*)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNO AND

SALARY>40000GROUP BY DNAMEHAVING COUNT (*)>5;Wrong

◦ Selects only department having more than 5 employees who ALL make more than 40K

76www.bookspar.com | Website for students | VTU NOTES

Page 77: Chapter 8: SQL-99

Version 2: Correct OneVersion 2: Correct OneSELECT DNUMBER, COUNT (*)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNO AND

SALARY>4000 AND DNO IN ◦(SELECT DNO ◦ FROM EMPLOYEE ◦ GROUP BY DNO ◦ HAVING COUNT(*)>5)

GROUP BY DNUMBER

77www.bookspar.com | Website for students | VTU NOTES

Page 78: Chapter 8: SQL-99

Precedence rule Precedence rule The processing steps

◦1) the WHERE Clause is executed to select individual tuples

◦2) HAVING clause executed to select individual groups of tuples

78www.bookspar.com | Website for students | VTU NOTES

Page 79: Chapter 8: SQL-99

SQL: Insert, Delete, and SQL: Insert, Delete, and Update commandsUpdate commandsThe Insert Command

◦To add a new tuple to employee INSERT INTO EMPLOYEE VALUES

(‘Richard’,’K’,’Marini’,653298653,’30-dec-52’, ‘98 Oak Forest, Katy, TX’,’M’, 37000,’987654321’, 4)

79www.bookspar.com | Website for students | VTU NOTES

Page 80: Chapter 8: SQL-99

More on InsertMore on InsertTo enter a new tuple using

known attributes◦INSERT INTO EMPLOYEE (FNAME,

LNAME, SSN)◦VALUES (‘Richard’, ’Marini’,

‘653298653’); the tuple is accepted, if no constraint is

violated,

80www.bookspar.com | Website for students | VTU NOTES

Page 81: Chapter 8: SQL-99

Insert Multiple tuplesInsert Multiple tuples INSERT command can be used to load

multiple tuples as the same time◦ Suppose

CREAT TABLE DEPT_INFO (DEPT_NAME VARCHAR(15), NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER);

INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS,TOTAL_SAL)

SELECT DNAME, COUNT(*), SUM (SALARY)FROM (DEPARTMENT JOIN EMPLOYEE ON

DNUMBER=DNO)GROUP BY DNAME;

81www.bookspar.com | Website for students | VTU NOTES

Page 82: Chapter 8: SQL-99

The DELECT CommandThe DELECT CommandRemoves tuples from a relation

one at a time◦DELETE FROM EMPLOYEE◦WHERE LNAME=‘Brown’

82www.bookspar.com | Website for students | VTU NOTES

Page 83: Chapter 8: SQL-99

Multiple DELETESMultiple DELETESOne or more tuples can be

deleted◦E.g.. Delete all employees who work

for “Research” dept. DELETE FROM EMPLOYEE WHERE DNO IN

(SELECT DNUMBER FROM DEPARTMENT WHERE DNAME=‘Research’);

83www.bookspar.com | Website for students | VTU NOTES

Page 84: Chapter 8: SQL-99

More on DELETEMore on DELETEDELETE FROM EMPLOYEE

◦Creates empty table

84www.bookspar.com | Website for students | VTU NOTES

Page 85: Chapter 8: SQL-99

The UPDATE CommandThe UPDATE Command

Used to modify values of one (or multiple) selected tuples associated with ONE relation

E.g.◦ Change the location and controlling

department number of project number 10 to ‘Grand Forks’ and 5

◦ UPDATE PROJECT◦ SET PLOCATION = ‘Grand Forks’, DNUM=5◦ WHERE PNUMBER=10;

85www.bookspar.com | Website for students | VTU NOTES

Page 86: Chapter 8: SQL-99

Example: Multiple Example: Multiple changeschangesE.g.,

◦ Give all employees working in ‘Research’ department a 10 percent salary raise UPDATE EMPLOYEE SET SALARY = SALARY *1.1 WHERE DNO IN ( SELECT DNUMBER

FROM DEPARTMENT WHERE DNAME = ‘Research’);

86www.bookspar.com | Website for students | VTU NOTES

Page 87: Chapter 8: SQL-99

Additional featuresAdditional featuresSpecifying ASSERTIONS/TriggersCreating ViewsWriting programsSpecifying physical DBGranting and revoking privilegesSpecifying Complex ObjectsConcurrency Control/Recovery

mechanisms

87www.bookspar.com | Website for students | VTU NOTES

Page 88: Chapter 8: SQL-99

Specifying General Specifying General ConstraintsConstraintsgeneral constraints can be

specified as follows◦ CREATE ASSETION SALARY_CONSTRAINT

CHECK ( NOT EXISTS ( SELECT * FROM EMPLOYEE AS E,

EMPLOYEE AS M, DEPARTMENTAS D WHERE E.SALARY > M.

SALARY AND E.DNO=D.NUMBER

AND D.MGRSSN=M.SSN));

88www.bookspar.com | Website for students | VTU NOTES

Page 89: Chapter 8: SQL-99

Constraints vs. TriggersConstraints vs. TriggersConstraints

◦Prevent the data from being made inconsistent by any kind of statement

Triggers◦Maintain database consistency and

defined operationally

89www.bookspar.com | Website for students | VTU NOTES

Page 90: Chapter 8: SQL-99

Views in SQLViews in SQL A view refers to a single table that is derived

from other tables◦ CREAT VIEW WORKS_ON1◦ AS SELECT FNAME, LNAME, PNAME, HOURS

FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER

90

FNAME LNAME PNAME HOURS

WORKS_ON1

www.bookspar.com | Website for students | VTU NOTES

Page 91: Chapter 8: SQL-99

Example 2Example 2◦ CREAT VIEW DEPT_INFO(DEPT_NAME,

NO_OF_EMPS, TOTAL_SAL)◦ AS SELECT DNAME, COUNT(*), SUM(SALARY)

FROM EMPLOYEE, DEPARTMENT WHERE DNUMBER=DNO GROUP BY DNAME;

91

DEPT_NAME TOTAL_SALNO_OF_EMPS

DEPT_INFO

www.bookspar.com | Website for students | VTU NOTES

Page 92: Chapter 8: SQL-99

Query on ViewQuery on ViewSELECT Fname, LnameFROM WORKS_ON1WHERE Pname =‘ProjectX’;

92www.bookspar.com | Website for students | VTU NOTES

Page 93: Chapter 8: SQL-99

DROP VIEWDROP VIEWDROP VIEW WORKS_ON1;

93www.bookspar.com | Website for students | VTU NOTES

Page 94: Chapter 8: SQL-99

Database Views: Database Views: applications applications Used as subroutine mechanism

◦make a complex query easier to understand/reuse

◦easier to debugused as a flexible mechanism for

access CONTROL to the data (security)

94www.bookspar.com | Website for students | VTU NOTES

Page 95: Chapter 8: SQL-99

View PropertiesView PropertiesA View is always up to dateA view is realized at the time we

execute a query

95www.bookspar.com | Website for students | VTU NOTES

Page 96: Chapter 8: SQL-99

View ImplementationView ImplementationTwo strategies to implement a

view◦Query modification

Maps the view into the base tables

◦View materialization Create a temporary view table Uses incremental approach to keep a

materialized table up-date Removes the view table if it is not

accessed for certain period of time

96www.bookspar.com | Website for students | VTU NOTES

Page 97: Chapter 8: SQL-99

Query ModificationQuery ModificationQuery on

◦SELECT Fname, Lname◦FROM WORKS_ON1◦WHERE Pname =‘ProjectX’;

Translated to◦ SELECT Fname, Lname,

FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER AND Pname =‘ProjectX’;

97www.bookspar.com | Website for students | VTU NOTES

Page 98: Chapter 8: SQL-99

Updating of ViewsUpdating of ViewsUpdating the views can be

complicated and ambiguousan update on a view defined on a

single table without any aggregate functions can be mapped to an update on the base table

98www.bookspar.com | Website for students | VTU NOTES

Page 99: Chapter 8: SQL-99

Table: 8.1 (SQL Summary)Table: 8.1 (SQL Summary)

99www.bookspar.com | Website for students | VTU NOTES