Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views."— Presentation transcript:

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

2 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

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

4 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)

5 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).

6 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.

7 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.

8 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.

9 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.

10 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 ;

11 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

12 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

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

14 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)

15 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

16 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')

17 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.

18 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;

19 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*1.2 + 5000) >= 100000;

20 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

21 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 ?

22 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*1.2 + 5000) results in NULL. The WHERE condition (salary*1.2+5000)>=200000 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.

23 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', '653298653', ‘1952-12-30', '98 Oak Forest,Katy,TX', 'M', 37000, '987654321', 4 );

24 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', '653298653');  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.

25 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>=200000 && Dno=Dnumber;

26 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

27 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

28 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='123456789’;  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;

29 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);

30 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

31 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;

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

33 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.

34 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.

35 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)

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

37 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');

38 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);

39 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);

40 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';

41 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

42 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 ?

43 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;

44 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 )

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

46 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

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

48 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, …

49 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.

50 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’;

51 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 ?

52 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)

53 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;

54 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’;

55 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

56 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);

57 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.

58 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.

59 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.

60 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;

61 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;

62 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;

63 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 ]

64 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.

65 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.


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

Similar presentations


Ads by Google