Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.

Slides:



Advertisements
Similar presentations
SQL DESIGN AND IMPLEMENTATION CONTENT SOURCES: ELAMSARI AND NAVATHE, FUNDAMENTALS OF DATABASE MANAGEMENT SYSTEMSELAMSARI AND NAVATHE, FUNDAMENTALS OF.
Advertisements

COMPANY schema EMPLOYEE
Basic Queries. 2 Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the.
SQL Query Slides Sharif University Of Technology Database Systems CE 384 Prepared By: Babak Bagheri Hariri
Your Logo Fundamentals of Database Systems Fourth Edition El Masri & Navathe Instructor: Mr. Ahmed Al Astal Chapter 8 (Cont.) SQL-99: Schema Definition,
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
1 CSE 480: Database Systems Lecture 10: SQL - DML Reference: Read Chapter 4 of the textbook.
METU Department of Computer Eng Ceng 302 Introduction to DBMS SQL-99: Schema Definition, Basic Constraints, and Queries by Pinar Senkul resources: mostly.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
Copyright © 2004 Pearson Education, Inc.. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries.
Database Systems Chapter 8 ITM 354. Data Definition, Constraints, and Schema Changes Used in SQL to Create, Drop, and Alter the descriptions of the tables.
관계 연산자 & SQL. Selection SELECT * FROM r WHERE A=B AND D>5.
SQL The relational DB Standard CS-450 Dr. Ali Obaidi.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1 CREATE/DROP/ALTER TABLE Data types : char, varchar, decimal, date CREATE TABLE DEPARTMENT.
Al-Imam University Girls Education Center Collage of Computer Science 1 ST Semester, 1432/1433H Chapter 8 Part 4 SQL-99 Schema Definition, Constraints,
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: Constraints, and Queries and Views.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
1 CSE 480: Database Systems Lecture 11: SQL. 2 SQL Query SELECT FROM WHERE –In MySQL, FROM and WHERE clauses are optional –Example:
SQL: Schema Definition, Constraints, & Queries and Views.
Relational Algebra - Chapter (7th ed )
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
 Employee (fname, minit, lname, ssn, bdate, address, sex, salary, superssn, dno)  Department (dname, dnumber, mgrssn, mgrstartdate) 
Database Management Systems. NESTING OF QUERIES  Some queries require that existing values in the database be retrieved and then used in a comparison.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
Announcements Written Homework 1 due Friday –If you have fourth edition make sure you do the right problems Program 3 out today, due next Friday Nov 10.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
Copyright © 2004 Pearson Education, Inc.. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Copyright © 2004 Pearson Education, Inc.. Lecture-7 Chapter 8 SQL: Schema Definition, Basic Constraints, and Queries.
Chapter 7 SQL HUANG XUEHUA. AGGREGATE FUNCTIONS Include COUNT, SUM, MAX, MIN, and AVG Query 15: Find the maximum salary, the minimum salary, and the.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
Copyright © 2004 Pearson Education, Inc. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries.
Copyright © 2004 Pearson Education, Inc.. Lecture-7 Chapter 8 SQL: Schema Definition, Basic Constraints, and Queries.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Slide 8- 1 THE HAVING-CLAUSE Provides a condition on the summary information Sometimes we want to retrieve the values of these functions for only those.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
Copyright © 2004 Pearson Education, Inc.. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries.
Structured Query Language (2) The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems,
Chapter 11 SQL DML. Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not.
1 Chapter 5 The SQL Language Data Definition Language The Data Definition Language (DDL) is used to create and destroy databases and database.
Announcements Written Homework 1 due Nov 2 –See course web page –Exercises 5.12, 5.15, 6.17, 6.20, 6.22 (a,c,f only). Today –continue with SQL (chapter.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
Chapter SQL DML. Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the.
COMP163 Database Management Systems September 18, 2008 Lecture 8 – Sections SQL Queries.
ISC321 Database Systems I Chapter 5: SQL: Advanced Queries, Assertions, Triggers, and Views Fall 2015 Dr. Abdullah Almutairi.
SQL Aggregeringsfunktioner. AGGREGATE FUNCTIONS Include COUNT, SUM, MAX, MIN, and AVG Query 15: Find the maximum salary, the minimum salary, and the average.
Copyright © 2004 Pearson Education, Inc.. Chapter 8 SQL-99: Schema Definition, Basic Constraints, and Queries.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 (SQL Basics) Lecture # 9 July 7,2012.
Copyright © 2004 Pearson Education, Inc. Schema Definition, Basic Constraints, and Queries.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
CS580 Advanced Database Topics Chapter 8 SQL Irena Pevac.
CS580 Advanced Database Topics
Chapter 4 Basic SQL.
6/22/2018.
Retrieval Queries in SQL(DML)
Subject Name: DATA BASE MANAGEMENT SYSTEM Subject Code: 10cs54
376a. Database Design Dept. of Computer Science Vassar College
11/9/2018.
SQL-99: Schema Definition, Constraints, and Queries and Views
SQL Grouping, Ordering & Arithmetics Presented by: Dr. Samir Tartir
Presentation transcript:

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 2 SQL as a DML  Data manipulation commands in SQL SELECT: the query command to retrieve data  Based on but not strictly conformant with relational algebra UPDATE: change the state of existing tuples INSERT: Add new tuples to tables DELETE: remove tuples from tables

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 3 The COMPANY Database Schema

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 4 A Simple SQL Query  Retrieve the name and address of all employees who work for the 'Research' department. SELECT Fname, Lname, Address FROM EMPLOYEE, DEPARTMENT WHERE Dname='Research' AND Dnumber=Dno;  The “FROM” clause is equivalent to a Cartesian product Temp1 = EMPLOYEE  DEPARTMENT  The “WHERE” clause is equivalent to a select operator Temp2 =  Dname='Research' AND Dnumber=Dno (Temp1)  The “SELECT” part is a project operator Result =  Fname, Lname, Address (Temp2)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 5 General Form Select Attribute1, Attribute2, … from Table1, Table2, … where Select_Conditions; is equivalent to  Attribute1, Attribute2, …  Select_Conditions ( Table1  Table 2  …))  The “where” clause (the select) is optional.  If there is only one table in the “from” clause, there is no cross referencing (Cartesian product).

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 6 More Simple Queries  Retrieve the birth date and address of the employee whose name is 'John Smith'. Select Bdate, Address from EMPLOYEE whereFname='John' AND Lname='Smith'; There is no cross referencing, for there is only one table involved.  Retrieve the Fname and Lname of all employees. Select Fname, Lname from EMPLOYEE; Recall that duplicates in results are not eliminated.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 7 Pitfalls  It is extremely important not to overlook specifying any selection and join conditions in the WHERE- clause; otherwise, incorrect and very large relations may result.  Bad example: SELECT SSN, Dname FROM EMPLOYEE, DEPARTMENT; Every possible (SSN, Dname) will be in the results, regardless whether the person actually works for the named department.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8 Example  List the names and salary of department managers who earn more than $200,000.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 9 Exercise  For every project located in 'Stafford', list the project number, the controlling department number, and the department manager's last name, and address.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 10 USE OF *  To retrieve all the attribute values of the selected tuples, a * is used, which stands for all the attributes  Example: SELECT * FROM EMPLOYEE WHERE Dno=5; SELECT * FROM EMPLOYEE, DEPARTMENT WHERE Dname='Research' AND Dno=Dnumber ;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 11 Eliminate Duplicates in Results  SQL does not treat a relation as a set; duplicate tuples can appear  To eliminate duplicates, DISTINCT is used  Examples: the result of Query Q1 may have duplicate SALARY values whereas Q2 does not have any duplicates. Q1: SELECT Sex FROMEMPLOYEE Q2: SELECT DISTINCT Sex FROMEMPLOYEE

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 12 Disambiguate Attributes Names  A query that refers to two or more attributes with the same name must qualify the attribute name with the relation name by prefixing the relation name to the attribute name  Examples: WORKS_ON.Essn DEPENDENT.Essn

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 13 Example  List the names of those departments located in Houston.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 14 Aliases  When using the same relation twice, aliases are given to the relation.  Example: retrieve the employee's name and the name of his/her immediate supervisor. Select E.Fname, E.Lname, S.Fname, S.Lname from EMPLOYEE AS E, EMPLOYEE AS S where E.superssn=S.ssn;  The “from” clause is equivalent to  E (EMPLOYEE)   S (EMPLOYEE)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 15 Set Operators  SQL has directly incorporated some set operations  There is a union operation (UNION), and in some versions of SQL there are set difference (MINUS) and intersection (INTERSECT) operations Oracle and MySQL support only UNION  The resulting relations of these set operations are sets of tuples; duplicate tuples are eliminated from the result  The set operations apply only to union compatible relations; the two relations must have the same attributes and the attributes must appear in the same order

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 16 Example  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 Pname from PROJECT, DEPARTMENT, EMPLOYEE where Dnum=Dnumber AND mgrssn=ssn AND Lname='Smith') UNION (Select Pname from PROJECT, WORKS_ON, EMPLOYEE where Pnumber=Pno AND Essn=Ssn AND Lname='Smith')

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 17 Heed the NULLs  Results of a Boolean expressions can be 0 (False), 1 (True), or NULL.  Any comparion (=, >, <, !=, …) that involve NULL values results in NULL.  NULL is not equal to NULL. Recall that NULL may represent ‘not available,’ ‘not applicable’, or ‘unknown’. Someone without a phone number is not equal another one who withholds his/her phone information.  Use IS NULL or IS NOT NULL operators to check the NULL values of attributes the NULL results of Boolean expressions.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 18 Example of Testing NULLs  List the SSNs of employees who does not have a supervisor.  Wrong answer: select ssn from EMPLOYEE where superssn=null;  Even for those whose superssn has the value NULL, the result of the = operator is NULL, not True.  Therefore, no one is listed, and the result table is empty.  Correct answer: select ssn from EMPLOYEE where superssn is null;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 19 Arithmetic Operations  The standard arithmetic operators '+', '-'. '*', and '/' can be applied to numeric values in an SQL query result  Example 1: Show the effect of a 10% pay raise on all employees. SELECT Fname, Lame, 1.1*Salary FROMEMPLOYEE;  List the names of those employees whose salary would exceed $100,000 if given a 20% + $5000 pay raise. SELECT Fname, Lname FROMEMPLOYEE WHERE(Salary* ) >= ;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 20 Substring Comparison  The LIKE comparison operator 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  Example: SELECT FNAME, LNAME FROMEMPLOYEE WHEREADDRESS LIKE '%TX%'; All addresses that contains substring ‘TX’ will produces TRUE in the WHERE clause

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 21 Substring Comparison (contd.)  Example: Retrieve all employees born in January. Select Fname, Lname fromEMPLOYEE whereBdate LIKE '____-01-__';  The LIKE operator allows us to get around the fact that each value is considered atomic and indivisible  For instance, if we consistently uses the format “LastName,M FirstName” in a Name attribute, then Name effectively becomes composite. Exercise: list all names with LastName=‘Smith’ Middle initial ? First Name ?

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 22 Heed the NULLs --- Again  Any arithmetic expression involving NULL produces NULL. If an employee’s salary is NULL, the expression (salary* ) results in NULL. The WHERE condition (salary* )>= also results in NULL.  Any substring matching invoving a NULL string results in NULL. If some employees is NULL, then the WHERE condition Address Like ‘%TX%’ results in NULL.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 23 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 INSERT INTO EMPLOYEE VALUES ('Richard', 'K', 'Marini', ' ', ‘ ', '98 Oak Forest,Katy,TX', 'M', 37000, ' ', 4 );

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 24 INSERT (contd.)  An alternate form of INSERT specifies explicitly the attribute names that correspond to the values in the new tuple INSERT INTO EMPLOYEE (Fname, Lname, SSN) VALUES ('Richard', ‘Smith', ' ');  Attributes with NULL values can be left out.  Attributes with default values can be left out.  Integrity constraints are automatically enforced with updates and insertions. Example: you cannot add a new department whose mgr_ssn does not exist in EMPLOYEE yet.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 25 Insertions of Query Results  With one INSERT, you can add to a table all results of a query.  Example: Create a temporary table of those managers whose salary exceeds $200,000. Create table HiPayManager ( SSNchar(9), DeptNoINT, SalaryDEC(12,2); Primary Key (SSN)); Insert into HiPayManager Select SSN, Dno, Salary from Employee, Department where Salary>= && Dno=Dnumber;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 26 Exercise  Create a table MGR_WORKS_ON that includes the managers and the projects they work on. Create table MGR_WORKS_ON ( ESSN char(9), Pno INT, Hours INT, Primary Key (ESSN)); INSERT

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 27 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 © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 28 Delete Examples  To delete an entry --- the entry is identified by its key. DELETE From EMPLOYEE WHERESSN=' ’;  You can also delete multiple entries that satisfy a condition (or any Boolean expression). DELETE from EMPLOYEE WHERELname=‘Huang’;  You can also empty the whole table with one delete. DELETE from DEPENDENT;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 29 A Quick Review of Referential Integrity Create table EMP( … ESSNCHAR(9), DNOINTEGER DEFAULT 1, SUPERSSNCHAR(9), PRIMARY KEY (ESSN), FOREIGN KEY (DNO) REFERENCES DEPT ON DELETE SET DEFAULT ON UPDATE CASCADE, FOREIGN KEY (SUPERSSN) REFERENCES EMP ON DELETE SET NULL ON UPDATE CASCADE);

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 30 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 should be enforced

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 31 UPDATE 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;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 32 Exercise  Give a 100% pay raise to all Huangs.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 33 Nesting OF Quires  A complete SELECT query, called a nested query, can be specified within the WHERE-clause of another query, called the outer query  Example: Retrieve the name and address of all employees who work for the 'Research' department. SELECTFname, Lname, Address FROM EMPLOYEE WHERE Dno IN (SELECT Dnumber FROM DEPARTMENT WHERE Dname='Research');  NOT IN can also be used.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 34 Exercises  Rewrite the previous query without using nesting.  List the employees not working for the ‘Research’ Department with/without nested queries.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 35 Correlated Nested Queries  If a nested query references an attribute of a relation in the outer query, the two queries are said to be correlated.  A reference to an unqualified attribute refers to the relation in the innermost nested query Attributes from the outer query must be qualified in the inner query.  Example: Retrieve the name of each employee who has a dependent with the same first name as the employee. SELECT E.Fname, E.Lname FROMEMPLOYEE AS E WHERESSN IN (SELECT Essn FROMDEPENDENT WHEREEssn=E.SSN AND E.Fname=DEPENDENT.Name)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 36 Example  Rewrite the previous query without nesting.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 37 UPDATE with the IN Operator  Example: Give all employees in the 'Research' department a 10% raise in salary. UPDATE EMPLOYEE SETSALARY = SALARY *1.1 WHEREDno IN (SELECTDnumber FROMDEPARTMENT WHEREDname='Research');

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 38 The IN Operator Explained  The operator IN tests a value v exists in the results of an inner query. It is equal to operator “ = Any ”  A similar operator is “ = All ” Can you guess its meaning ?  We also have “ > Any ”, “ <= All ”, …  NOT IN is equivalent to ?  Simply put, IN and NOT IN are both comparison operators that produces Boolean results. They can be used with other Boolean operators to form complex expressions.  Example: name the eldest employee. Select Fname, Lname fromEMPLOYEE whereBdate >= ALL (Select Bdate from EMPLOYEE);

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 39 Exercise: Explain the following query SelectFname, Lname, fromEMPLOYEE whereSSN NOT IN (Select SSN from EMPLOYEE, DEPARTMENT where SSN = Mgr_ssn; AND Salary (SelectSalary fromEMPLOYEE, DEPARTMENT whereSSN = Mgr_ssn);

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 40 Aggregate Functions  COUNT, SUM, MAX, MIN, and AVG  Example 1: Find the maximum salary, the minimum salary, and the average salary among all employees. SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROMEMPLOYEE;  Example 2: Find the max/min/avg salaries among employees who work for the 'Research' department. SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROMEMPLOYEE, DEPARTMENT WHEREDno=Dnumber && Dname='Research';

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 41 Aggregate Functions (contd.)  Examples: Retrieve the total number of employees in the company (Q1), and the number of employees in the 'Research' department (Q2). Q1:SELECT COUNT (*) FROMEMPLOYEE Q2:SELECT COUNT (*) FROMEMPLOYEE, DEPARTMENT WHEREDno=Dnumber AND Dname='Research’  All aggregate functions are computed after WHERE aggregate functions themselves cannot be used in WHERE

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 42 Heed the Duplications  Keep in mind duplication eliminations are not performed by aggregate functions.  Example: predict the result the following query. Select COUNT(sex) from EMPLOYEE;  To produce the correct sex count, use Select COUNT(distinct sex) from EMPLOYEE; The result can be 0, 1, 2, or 3. Why 0 ? Why 3 ?

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 43 Discussions  Which one of the following queries produces the correct salary budget for the company. Select SUM(Salary) from EMPLOYEE; Select SUM(distinct Salary) from EMPLOYEE;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 44 GROUPING  A GROUP BY clause can be used to specify the grouping attributes, so that we apply the aggregate functions to subgroups of tuples in a relation  For each department, retrieve the department number, the number of employees in the department, and their average salary. SELECT Dno, COUNT(*), AVG(SALARY) FROMEMPLOYEE GROUP BYDno;  This is identical to the relational algebra expression DNO ℱ COUNT SSN, AVERAGE Salary ( EMPLOYEE )

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 45 Grouping by Dno

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 46 GROUPING (contd.)  For each project, retrieve the project number, project name, and the number of employees who work on that project. SELECT Pnumber, Pname, COUNT(*) FROMPROJECT, WORKS_ON WHEREPnumber=Pno GROUP BYPnumber, Pname;  In this case, the grouping and functions are applied after the joining of the two relations

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 47 Exercise  Give the relational expression of the previous SQL query.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 48 Explicit JOINs in the FROM Clause  In the FROM clause, the commas that separate table names are really cross product (  ) operators.  We can also use other join operators in FROM regular "theta" JOIN, Natural JOIN, Left Outer JOIN, Right Outer JOIN, …

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 49 Explicit Joins Select Fname, Lname, Dname from EMPLOYEE, DEPARTMENT where SSN=Mgr_SSN;  Is equivalent to Select Fname, Lname, Dname FROM EMPLOYEE JOIN DEPARTMENT ON (SSN=Mgr_SSN);  Notice that the ON/join condition is part of the FROM clause.  The WHERE clause can be used to add more selection conditions.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 50 Natural Joins in FROM  Example: List the those department names in ‘Houston’ (recall that a department may have more than on location). Select Dname FROM DEPARTMENT AS D, DEPT_LOCATIONS AS L WhereD.Dnumber = L.Dnumber AND Dlocation = ‘Houston’;  Is equivalent to Select Dname FROM DEPARTMENT NATURAL JOIN DEPT_LOCATIONS Where Dlocation=‘Houston’;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 51 Renaming Attributes to Use Natural Joins in FROM  Examples: SelectFname, Lname, Address from EMPLOYEE, DEPARTMENT whereDname='Research' AND Dnumber=DNO;  could be written as: SelectFname, Lname, Address fromEMPLOYEE JOIN DEPARTMENT ON Dnumber=Dno whereDname='Research';  or as: Select Fname, LNAME, ADDRESS from (EMPLOYEE NATURAL JOIN DEPARTMENT AS DEPT(Dname,Dno,MSSN,Date) where Dname='Research’; Benefits ?

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 52 Review Outer Joins  T = EMPLOYEE ssn=mgr_ssn DEPARTMENT  RESULT =  Fname, Minit, Lname, Dname (T)

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 53 Outer Joins in FROM  Example: list the names of those employees who are not managers Select Fname, Minit, Lname fromEMPLOYEE Left Outer Joins DEPARTMENT ON SSN=mgr_ssn; whereDnumber IS NULL;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 54 Multiple JOINs in FROM  A previous exercise: For every project located in 'Stafford', list the project number, the controlling department number, and the department manager's last name, and address. Select Pnumber,Dnum,Lname,Address from(PROJECT JOIN DEPARTMENT ON Dnum=Dnumber) JOIN EMPLOYEE ON MgrSSN=SSN)) where Plocation='Stafford’;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 55 Exercise  List the names of the employees with no dependents. Use NOT IN with nested queries Use Outer Joins

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 56 Single-value Ouput of SELECT  Unlike the relational algebra, a single number output of SELECT can be treated as a scalar and involves in comparison and arithmetic operations.  Example: print the names of employees with the highest salary. SelectLname, Lname fromEMPLOYEE whereSalary = (Select max(salary) from EMPLOYEE);

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 57 Performance Considerations  Explicit joins are not strictly necessary.  However, using them correctly improves performance by forcing the orders of join/selection conditions.  A further improvement of the above example Select Pnumber,Dnum,Lname,Address from (PROJECT JOIN DEPARTMENT ON Dnum=Dnumber AND Plocation='Stafford’) JOIN EMPLOYEE ON MgrSSN=SSN));  This informs the DBMS to filter out projects not located in Stafford early.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 58 Performance Considerations Con’t  Modern DBMS use sophisticated, automatic query optimization techniques to improve performance for straightforward queries. This is one reason why relational databases remain an active research area and enjoys intensive competitions in industry. Modern DBMS even have their own file systems (bypassing the OS file system) to best use raw disks.  Example: Oracle and MySQL  Manually spelling out join/selection orders does not necessarily improve performance.  For guidelines on performance, read the manuals.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 59 The HAVING Clause  Sometimes we want to retrieve the values of these functions for only those groups that satisfy certain conditions  The HAVING clause is used for specifying a selection condition on groups (rather than on individual tuples)  This solves the restrictions that aggregate functions cannot be used in the WHERE clause.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 60 THE HAVING-CLAUSE (contd.)  Example: 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(*) FROMPROJECT, WORKS_ON WHEREPnumber=Pno GROUP BYPnumber, Pname HAVINGCOUNT(*) > 2;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 61 The ORDER BY Clause  The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s)  Example: List all employees in the alphabetic order of last names; for the same last names, ordered by first names; given the same last and first names, ordered by SSN; Select* FromEMPLOYEE Order ByLname, Fname, SSN;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 62 ORDER BY (contd.)  The default order is in ascending order of values  We can specify the keyword DESC if we want a descending order; the keyword ASC can be used to explicitly specify ascending order, even though it is the default Select* FromEMPLOYEE Order ByLname ASC, Fname ASC, SSN DESC;

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 63 Summary of SQL Queries  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 FROM [WHERE ] [GROUP BY ] [HAVING ] [ORDER BY ]

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 64 Conceptual Execution of SELECT  Step 1: The FROM clause corresponds to cross product and/or join operator in the relational algebra. The result table is the input the WHERE clause.  Step 2: The WHERE clause corresponds to a select operator . The result is the input to GROUP BY.  Step 3: The GROUP BY is a script F operator.  Step 4: HAVING is a second select operator that takes the output of the script F as input.  This is the reason aggregate functions are allowed only in GROUP BY, but not WHERE --- their inputs are not ready when the WHERE clause is executed.  Step 5: ORDER BY is a sort operation. This is not part of the relational algebra.  Step 6: A project operator is used to select the attributes required.  Further cross references are implied if GROUP BY is used.

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 65 Final Discussions  Not all data manipulations can be performed with one SQL command.  If necessary, we need to use create temporary tables and use multiple commands.  Example: to give a manager a $5000 bonus for each department under his control that have 100 or more employees.