Presentation is loading. Please wait.

Presentation is loading. Please wait.

Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.

Similar presentations


Presentation on theme: "Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems."— Presentation transcript:

1 Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems (Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries)

2 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries1 Outline Introduction Data Definition Language CREATE TABLE ALTER TABLE DROP TABLE Data Manipulation Language SELECT Statement INSERT Statement DELETE Statement UPDATE Statement

3 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries2 Introduction SQL: Structured Query Language. Standard for commercial relational DBMSs, a joint effort by ANSI & ISO. Benefits of a standardized relational language: Reduced training costs. Productivity. Application portability. Application longevity. Reduced dependence on a single vendor. Cross-system communication.

4 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries3 “Declarative” Versus “Procedural” Most DBMSs provide the user with a high-level declarative language interface. The user has just to specify “what” results he/she would like, leaving the “how” to the DBMS.

5 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries4 Schema and Catalog Concepts in SQL The concept of an SQL Schema was incorporated to group together tables & other constructs that belong to the same database application. Schema: the structure that contains descriptions of objects created by the user (tables, constraints, views, domains, character sets, triggers, rules). Catalog: a set of schemas that constitute the description of a database.

6 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries5 Types of SQL Statements Data Definition Language (DDL): Commands that define a database. E.g. CREATE, ALTER, DROP,...etc. Data manipulation language (DML): Commands that maintain and query a database. E.g. SELECT, INSERT, UPDATE, DELETE. Data Control Language (DCL): Commands that control a database, including administering privileges and committing data. E.g. CONNECT, GRANT, REVOKE,...etc.

7 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries6 CREATE Statements Major CREATE statements: CREATE SCHEMA: Defines a portion of the database owned by a particular user. CREATE SCHEMA COMPANY AUTHORIZATION JSMITH. CREATE TABLE: Defines a table and its columns. CREATE VIEW: Defines a logical table from one or more views. Other CREATE statements: DOMAIN, CHARACTER SET, COLLATION, TRANSLATION, ASSERTION.

8 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries7 CREATE TABLE Construct CREATE TABLE name ( column-1 TYPE [DEFAULT value] [constraints], column-2 TYPE [DEFAULT value] [constraints], : column-n TYPE [DEFAULT value] [constraints], [table-constraints]); Where: name: table name. column-1 to column-n: column names. TYPE: data type. [DEFAULT value]: optional default value. [constraints]: optional constraints, can be specified at column level or at table level.

9 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries8 SQL Data Types (From Oracle) CHAR(n): a fixed-length string n characters long (default 1, max 255 character). VARCHAR2(n): a variable string up to n character long ( max 2000 ). LONG: a variable length character string up to 2 GB long. NUMBER: a signed floating point number up to 38 digits in length. NUMBER(n,d): a signed number n digits long including d decimal places. NUMBER(n): a signed integer n digits long (max 38 digits). DATE: a valid date and time. RAW: binary data up to 64K in size (image data for example). LONG RAW: binary data up to 2 GB in size. CLOB: character large object up to 4GB in size. BLOB: binary large object up to 4GB in size.

10 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries9 CREATE DOMAIN Construct A domain can be declared, and the domain name is used with the attribute specification. This makes it easier to change the data type for a domain that is used by numerous attributes in a schema, and improves schema readability. Examples: CREATE DOMAIN SSN_TYPE AS CHAR(9) CREATE DOMAIN DNUM_TYPE AS NUMBER(2) CHECK (DNUM>0 AND DNUM<21)

11 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Constraints There are essentially five types of constraints: NOT NULL constraints. UNIQUE value constraints. PRIMARY KEY constraints. FOREIGN KEY constraints. CHECK constraints. The syntax of these constraints varies according to whether they are specified at column level or at table level. Any constraints which apply to multiple columns must be defined as table level constraints. 10

12 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Constraints The syntax for each of the column level constraints is: NOT NULL UNIQUE PRIMARY KEY REFERENCES table (key) CHECK (condition) 11

13 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Constraints The syntax for each of the table level constraints is: UNIQUE (column-list) [CONSTRAINT name] PRIMARY KEY (column-list) [CONSTRAINT name] FOREIGN KEY (column-list) REFERENCES table (column-list) CHECK (condition) An additional ON DELETE clause may be applied to a foreign key constraint: ON DELETE CASCADE causes all referencing child records to be deleted whenever a parent record is deleted. ON DELETE SET NULL causes all referencing child records to be set to NULL whenever a parent record is deleted. 12

14 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Steps in Table Creation Identify data types for attributes. Determine default values. Identify columns that can and cannot be null. Identify columns that must be unique (candidate keys). Identify primary key - foreign key mates. Identify constraints on columns (domain specifications). Create the table and associated indexes. 13 To improve access speed

15 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries CREATE TABLE Example CREATE TABLE EMPLOYEE ( FNAME VARCHAR2(15) NOT NULL, MINIT CHAR, LNAME VARCHAR2(15) NOT NULL, SSN CHAR(9), BDATE DATE, ADDRESS VARCHAR2(30), SEX CHAR CHECK (LOWER(SEX) IN ('m', 'f')), SALARY NUMBER(10,2), SUPERSSN CHAR(9), DNO NUMBER(2) NOT NULL, CONSTRAINT EMP_PKEY PRIMARY KEY (SSN), CONSTRAINT EMP_FKEY1 FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE (SSN), CONSTRAINT EMP_FKEY2 FOREIGN KEY (DNO) REFERENCES DEPARTMENT (DNUMBER)) 14

16 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries ALTER TABLE Construct Tables can be changed in a number of ways using the SQL statement ALTER TABLE. Possible actions include: Adding or dropping a column. Adding or dropping a constraint. Changing a column definition. 15

17 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries ALTER TABLE Construct To add two columns to the EMPLOYEE table: ALTER TABLE EMPLOYEE ADD ( TITLE CHAR(3) CHECK(LOWER(TITLE) IN ('mr', 'mrs', 'ms')), TEL_NO CHAR(7)) To add a constraint to the DEPARTMENT table: ALTER TABLE DEPARTMENT ADD ( CONSTRAINT D_FKEY FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE (SSN) ON DELETE CASCADE) To increase the width of LNAME column: ALTER TABLE EMPLOYEE MODIFY ( LNAME VARCHAR2(20)) 16

18 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries ALTER TABLE Construct To add a NOT NULL constraint to the ADDRESS column: ALTER TABLE EMPLOYEE MODIFY ( ADDRESSNOT NULL) To drop the attribute ADDRESS from the EMPLOYEE table: ALTER TABLE EMPLOYEE DROP (ADDRESS) CASCADE CONSTRAINTS To drop a constraint named D_FKEY from DEPARTMENT table: ALTER TABLE DEPARTMENT DROP CONSTRAINT D_FKEY 17

19 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries ALTER TABLE Construct To drop an existing default clause: ALTER TABLE DEPARTMENT ALTER MGRSSN DROP DEFAULT To define a new default clause: ALTER TABLE DEPARTMENT ALTER MGRSSN SET DEFAULT '333445555' 18

20 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries DROP TABLE Construct The DROP TABLE command deletes all information about the dropped relation from the database. Syntax: DROP TABLE name [CASCADE CONSTRAINTS] Where: name: is the name of the table to be dropped. CASCADE CONSTRAINTS: drops all referential integrity constraints which refer to keys in the dropped table. 19

21 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Basic Queries in SQL SQL has one basic statement for retrieving data from a database, the SELECT statement. This is not the same as the SELECT operation of the relational algebra. 20

22 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The SQL SELECT Statement It consists of the following basic clauses: SELECT specifies the columns which are to be retrieved FROM specifies the tables from which data is to be retrieved WHERE defines any selection criteria required GROUP BY specifies how output is to be grouped & summarized HAVING determines which group summaries to include in the output ORDER BY defines how the output will be stored 21 Mandatory

23 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The SELECT-FROM-WHERE Structure The basic form of the SELECT statement is: SELECT[DISTINCT] item-list FROMtable-list WHEREcondition Where: item-list: a comma-separated list of items to be retrieved. (database attributes, functions, fixed text,...etc.) table-list: a comma-separated list of tables from which the attributes are to be retrieved. condition: a conditional (Boolean) expression that identifies the tuples to be retrieved by the query. [DISTINCT]: ensures only unique tuples will be returned. The result of an SQL query is a relation (can be a multiset) 22

24 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The SELECT-FROM-WHERE Structure Query: retrieve the birthdate and address of the employee(s) whose name is ‘John B. Smith’. SELECTBDATE, ADDRESS FROMEMPLOYEE WHEREFNAME= ' John ' AND MINIT= ' B ' AND LNAME= ' Smith ' Is it similar to a tuple relational expression? Any differences? SELECT Statement Relational Algebra SELECT clause project operation FROM clause cartesian product operation WHERE clause select condition 23

25 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The SELECT-FROM-WHERE Structure Query: retrieve the name and address of all employees who work for the ‘Research’ department. Query: for every project located in ‘Stafford’, list the project number, the controlling department number, and the department manager’s last name, address, and birthdate. 24 SELECTFNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHEREDNAME='Research' AND DNUMBER=DNO SELECTPNUMBER, DNUM, LNAME, ADDRESS, BDATE FROM PROJECT, DEPARTMENT, EMPLOYEE WHEREDNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford'

26 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Ambiguous Attribute Names, Aliasing, and Tuple Variables In SQL if the same attribute name is used in more than one relation, the attribute names must be qualified. Assume that DNO attribute of the EMPLOYEE relation was called DNUMBER. Query: retrieve the name and address of all employees who work for the ‘Research’ department. SELECTFNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHEREDNAME= ' Research ' AND EMPLOYEE.DNUMBER=DEPARTMENT.DNUMBER 25

27 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Ambiguous Attribute Names, Aliasing, and Tuple Variables Ambiguity also arise in the case of queries that refer to the same relation twice, as in the following example. Query: for each employee, retrieve the employee’s first and last name and the first and last name of his or her immediate supervisor. SELECTE.FNAME, E.LNAME, S.FNAME, S.LNAME FROMEMPLOYEE E, EMPLOYEE S WHEREE.SUPERSSN=S.SSN 26

28 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Unspecified WHERE Clause Query: select all EMPLOYEE SSNs. SELECTSSN FROMEMPLOYEE Query: select all combinations of EMPLOYEE SSN and DEPARTMENT DNAME. 27 SELECTSSN, DNAME FROMEMPLOYEE, DEPARTMENT

29 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The Use of Asterisk Query: retrieve all the attribute values of any EMPLOYEE who work in DEPARTMENT 5. SELECT* FROMEMPLOYEE WHEREDNO =5 Query: retrieve all the attributes of an EMPLOYEE and all the attributes of the DEPARTMENT in which he or she works for every employee of the ‘Research’ department. 28 SELECT* FROMEMPLOYEE, DEPARTMENT WHEREDNAME='Research' AND DNO=DNUMBER

30 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Tables as Sets in SQL Query: retrieve the salary of every employee. SELECTSALARY FROMEMPLOYEE Query: retrieve all distinct salary values. SELECTDISTINCTSALARY FROMEMPLOYEE 29 A set

31 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The UNION, INTERSECT, & MINUS SET OPERATORS The relations resulting from these set operations are sets of tuples; that is, duplicate tuples are eliminated from the result. Query: make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manager of the department that controls the project. SELECTDISTINCTPNUMBER FROMPROJECT, DEPARTMENT, EMPLOYEE WHEREDNUM=DNUMBER AND MGRSSN=SSN AND LNAME= ' Smith ' UNION SELECTDISTINCTPNUMBER FROMPROJECT, WORKS_ON, EMPLOYEE WHEREPNUMBER=PNO AND ESSN=SSN AND LNAME= ' Smith ' 30 Union compatible

32 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Conditional Operators Main conditional operators include: =, <>, >, =, <=. Other conditional operators: IN: tests if an item value appears in a specified list of values. BETWEEN: tests if an item value lies (inclusively) between two specified values. IS NULL: tests if an item has a Null value. Null is neither zero (in a numeric item), nor spaces (in a character item). LIKE: tests if an item value matches a string containing wildcard characters. The wildcard characters are: %: meaning zero or more occurrences of any character. _: meaning a single occurrence of any characters. The keyword NOT can be used in conjunction with all the above operators to revise the test. 31

33 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Conditional Operators Query: retrieve the names of all employees whose salary is not (20000, 30000, or 40000). Query: retrieve all employees in department 5 whose salary is between $30,000 and $40,000. 32 SELECTFNAME, LNAME FROMEMPLOYEE WHERESALARY NOT IN (20000, 30000, 40000) SELECT* FROMEMPLOYEE WHERE(SALARY BETWEEN 30000 AND 40000) AND DNO = 5

34 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Conditional Operators Query: retrieve the names of all employees who do not have supervisors. Query: retrieve all employees whose address is in Houston, Texas. 33 SELECTFNAME, LNAME FROMEMPLOYEE WHERESUPERSSN IS NULL SELECTFNAME, LNAME FROMEMPLOYEE WHEREADDRESS LIKE '%Houston, TX%'

35 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Arithmetic Operations The standard arithmetic operations (+, -, *, /) can be applied to numeric values or attributes with numeric domains. Query: show the resulting salaries if every employee working on the ‘ProductX’ project is given 10 percent raise. SELECTFNAME, LNAME, 1.1*SALARY INCREASED_SAL FROMEMPLOYEE, WORKS_ON, PROJECT WHERESSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' 34

36 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Ordering of Query Results SQL allows the user to order the tuples in the result of a query by the values of one or more attributes, using the ORDER BY clause. Query: retrieve a list of employees and the projects they are working on, ordered by department and, within each department, ordered alphabetically by last name, first name. SELECTDNAME, LNAME, FNAME, PNAME FROMDEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHEREDNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER ORDER BYDNAME, LNAME, FNAME The default order is in ascending order. ORDER BY DNAME DESC, LNAME ASC, FNAME ASC 35

37 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The Three Valued Logic Any comparison with Null returns unknown, for example, 5 < Null. Three- valued logic using the truth value unknown: OR: (unknown OR true) = true. (unknown OR false) = unknown. (unknown OR unknown) = unknown. AND: (unknown AND true) = unknown. (unknown AND false) = false. (unknown AND unknown) = unknown. NOT: (NOT unknown) = unknown. 36

38 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Nested Queries Some queries require that existing values in the database be fetched and then used in a comparison condition. Such queries can be conveniently formulated by using nested queries. Nested queries: complete select-from-where blocks usually within the WHERE clause of another query. That other query is called the outer query. 37

39 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Nested Queries Query: make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manager of the department that controls the project. SELECTDISTINCTPNUMBER FROMPROJECT WHEREPNUMBER IN (SELECT PNUMBER FROM PROJECT, EMPLOYEE, DEPARTMENT WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') OR PNUMBER IN (SELECT PNO FROM WORKS_ON, EMPLOYEE WHEREESSN=SSN AND LNAME='Smith') 38

40 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Nested Queries SQL allows the use of tuples of values in comparisons by placing them within parentheses. Example: SELECTDISTINCTESSN FROMWORKS_ON WHERE(PNO, HOURS) IN (SELECT PNO, HOURS FROMWORKS_ON WHEREESSN='123456789') 39

41 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Nested Queries In addition to the IN operator, a number of other comparison operators can be used to compare a single value (attribute) to a set or multiset. The keywords ANY or ALL can be combined with the following operators: >, >=,. (= ANY is equivalent to IN) Query: list the names of employees whose salary is greater than the the salary of all the employees in department 5. 40 SELECTLNAME, FNAME FROMEMPLOYEE WHERESALARY > ALL (SELECTSALARY FROMEMPLOYEE WHEREDNO=5)

42 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Correlated Nested Queries Whenever a condition in the WHERE clause of a nested query references some attribute of a relation declared in the outer query, the two queries are said to be correlated. The result of a correlated nested query is different for each tuple (or combination of tuples) of the relation(s) the outer query. Query: retrieve the name of each employee who has a dependent with the same name and same sex as the employee. 41 SELECTE.FNAME, E.LNAME FROMEMPLOYEE E WHEREE.SSN IN (SELECTESSN FROMDEPENDENT WHEREE.FNAME=DEPENDENT_NAME AND E.SEX=SEX)

43 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Correlated Nested Queries In general, a query with nested select-from-where blocks and using the = or IN comparison operators can always be expressed as a single block query. Query: retrieve the name of each employee who has a dependent with the same name and same sex as the employee. 42 SELECTE.FNAME, E.LNAME FROMEMPLOYEE E, DEPENDENT D WHEREE.SSN=D.ESSN AND E.SEX=D.SEX AND E.FNAME=D.DEPENDENT_NAME

44 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries43 The EXISTS Function in SQL This function checks whether the result of a correlated nested query is empty (contains no tuples) or not. Query: retrieve the name of each employee who has a dependent with the same first name and same sex as the employee. SELECTE.FNAME, E.LNAME FROMEMPLOYEE E WHEREEXISTS (SELECT * FROMDEPENDENT WHEREE.SSN=ESSN AND E.SEX=SEX AND E.FNAME=DEPENDENT_NAME)

45 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries44 The EXISTS Function in SQL Query: retrieve the names of employees who have no dependents. SELECTFNAME, LNAME FROMEMPLOYEE WHERENOT EXISTS (SELECT* FROMDEPENDENT WHERESSN=ESSN)

46 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries45 The EXISTS Function in SQL Query: list the names of managers who have at least one dependent. SELECTFNAME, LNAME FROMEMPLOYEE WHEREEXISTS(SELECT * FROMDEPENDENT WHERESSN=ESSN) AND EXISTS(SELECT* FROMDEPARTMENT WHERESSN=MGRSSN)

47 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries46 The EXISTS Function in SQL Query: retrieve the name of each employee who works on all the projects controlled by department number 5. SELECTFNAME, LNAME FROMEMPLOYEE WHERENOT EXISTS ((SELECT PNUMBER FROMPROJECT WHEREDNUM=5) MINUS (SELECTPNO FROMWORKS_ON WHERESSN=ESSN) )

48 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Renaming of Attributes in SQL It is possible to rename any attribute that appears in the result of a query. Alias names are specified following the selected attributes and must be bounded by double quotes if they contain spaces. Attribute aliases can be referenced only in the ORDER BY clause. Example: SELECTE.LNAME Name, S.LNAME "Supervisor name" FROMEMPLOYEE E, EMPLOYEE S WHEREE.SUPERSSN=S.SSN 47

49 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Outer Join An outer join is specified by appending a parenthesized plus sign (+) to the name of the foreign key in the join condition. Example: SELECTFNAME, LNAME, DEPENDENT_NAME FROMEMPLOYEE, DEPENDENT WHERESSN=ESSN(+) ORDER BYFNAME Even when no dependents exist for a particular employee, that employee’s name is retrieved. Null value will be replaced in the dependent’s name. 48

50 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Aggregate Function in SQL A number of built-in functions exist: COUNT, SUM, MAX, MIN, and AVG. These functions can be used in the SELECT clause or in the HAVING clause. The functions SUM, MAX, MIN, and AVG are applied to a set or multiset of numeric values. The functions MAX and MIN can also be used with attributes that have nonnumeric domains if the domain values have a total ordering among one another. Null values are discarded when aggregate functions are applied to a particular attribute. 49

51 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Aggregate Function in SQL Query: find the sum of the salaries of all employees, the maximum salary, the minimum salary, and the average salary. Query: find the sum of the salaries of all employees of the ‘Research’ department, as well as the maximum salary, the minimum salary, and the average salary in this department. 50 SELECTSUM (SALARY), MAX (SALARY), MIN (SALARY), AVG (SALARY) FROMEMPLOYEE SELECTSUM (SALARY), MAX (SALARY), MIN (SALARY), AVG (SALARY) FROMEMPLOYEE, DEPARTMENT WHEREDNO=DNUMBER AND DNAME='Research'

52 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Aggregate Function in SQL Query: retrieve the total number of employees in the company. Query: retrieve the total number of employees in the ‘Research’ department. 51 SELECTCOUNT(*) FROMEMPLOYEE SELECTCOUNT(*) FROMEMPLOYEE, DEPARTMENT WHEREDNO=DNUMBER AND DNAME='Research'

53 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries Aggregate Function in SQL Query: Count the number of distinct salary values in the database. Query: retrieve the names of all employees who have two or more dependents. 52 SELECTCOUNT(DISTINCT SALARY) FROMEMPLOYEE SELECTLNAME, FNAME FROMEMPLOYEE WHERE(SELECTCOUNT(*) FROMDEPENDENT WHERESSN=ESSN) >= 2

54 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The GROUP BY Clause This clause enables aggregates to be accumulated and grouped on output. Query: for each department, retrieve the department number, the number of employees in the department, and their average salary. SELECTDNO, COUNT(*), AVG(SALARY) FROMEMPLOYEE GROUP BYDNO If Nulls exist in the grouping attribute, then a separate group is created for all tuples with a NULL value in the grouping attribute. 53

55 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The GROUP BY Clause Query: for each project, retrieve the project number, the project name, and the number of employees who work on that project. 54 SELECTPNUMBER, PNAME, COUNT(*) FROMPROJECT, WORKS_ON WHEREPNUMBER=PNO GROUP BYPNUMBER, PNAME

56 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The HAVING Clause This clause specifies which groups are to be selected for output. Groups are only output if they match the condition(s) specified by the HAVING clause. Query: for each project on which more than two employees work, retrieve the project number, the project name, and the number of employees who work on the project. SELECTPNUMBER, PNAME, COUNT(*) FROMPROJECT, WORKS_ON WHEREPNUMBER=PNO GROUP BYPNUMBER, PNAME HAVINGCOUNT(*) >2 55

57 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The GROUP BY and HAVING Clauses Query: for each project, retrieve the project number, the project name, and the number of employees from department 5 who work on the project. 56 SELECTPNUMBER, PNAME, COUNT(*) FROMPROJECT, WORKS_ON, EMPLOYEE WHEREPNUMBER=PNO AND SSN=ESSN AND DNO=5 GROUP BYPNUMBER, PNAME

58 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The GROUP BY and HAVING Clauses Query: for each department that has more than five employees, retrieve the department number and the number of its employees who are making more than $40,000. 57 SELECTDNUMBER, COUNT(*) FROMDEPARTMENT, EMPLOYEE WHEREDNUMBER=DNO AND SALARY>40000 AND DNO IN (SELECT DNO FROM EMPLOYEE GROUP BY DNO HAVING COUNT(*) >5) GROUP BYDNUMBER

59 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries INSERT, DELETE, and UPDATE Statements In SQL, three commands can be used to modify the database: INSERT. DELETE. UPDATE. 58

60 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The INSERT Statement Using the SQL INSERT statement, rows may be inserted into tables in two ways: As lists of values, one row at a time. From another table using a query. 59

61 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries INSERT Using a Value List Syntax: INSERT INTO table [(attribute-list)] VALUES (value-list) Where: table: the name of the table to update. attribute-list: a list of attributes in the specified table. value-list: the list of values to be inserted for the row. 60

62 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries INSERT Using a Value List Example: INSERT INTO PROJECT VALUES('ProductZ', 1, NULL, 2) Example: INSERT INTO PROJECT (PNAME, PNUMBER, DNUM) VALUES('ProductZ', 1, 2) Example: INSERT INTO PROJECT (PNAME, PNUMBER, DNUM) VALUES('&PN', &P_NO, &D_NO) 61 Each time it is run, the user will be prompted for a new set of values

63 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries INSERT Using a Query Syntax: INSERT INTO table [(attribute-list)] SELECT statement There are no limitation concerning the SELECT statement. 62

64 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries INSERT Using a Query Example: CREATE TABLEDEPTS_INFO ( DEPT_NAMEVARCHAR2(15), NO_OF_EMPSNUMBER(5), TOTAL_SALNUMBER(15)) INSERT INTODEPTS_INFO SELECTDNAME, COUNT(*), SUM (SALARY) FROMDEPARTMENT, EMPLOYEE WHEREDNUMBER=DNO GROUP BYDNAME 63

65 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The DELETE Statement Syntax: DELETEFROM table [WHERE conditions] Example: DELETEFROM EMPLOYEE WHERELNAME='Brown' Example: DELETEFROM EMPLOYEE WHEREDNO IN (SELECTDNUMBER FROMDEPARTMENT WHEREDNAME='Research') Example: DELETEFROM EMPLOYEE 64

66 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries The UPDATE Statement The UPDATE statement can be used: With individual values. In conjunction with a SELECT statement. 65

67 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries UPDATE Using Fixed Values Syntax: UPDATEtable SETattribute-1 = value-1, attribute-2 = value-2, : attribute-n = value-n [WHERE conditions] Example: UPDATEPROJECT SETPLOCATION = 'Bellaire' WHEREPNUMBER=10 Example: UPDATEEMPLOYEE SETSALARY = SALARY * 1.25 66

68 Chapter 8: SQL-99: Schema Definition, Basic Constraints and Queries UPDATE Using a Query Syntax: UPDATEtable SET(attribute-list) = (SELECT statement) [WHERE conditions] Example: UpdateEMPLOYEE SET(SALARY) = ( SELECTSALARY FROMEMPLOYEE WHERESSN='987654321') WHEREFNAME = 'John' AND LNAME='Smith' 67

69 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Specifying General Constraints as Assertions In, SQL, users can specify general constraints via declarative assertions, using the CREATE ASSERTION statement. Example: specify the following constraint “the salary of an employee must not be greater than the salary of the manager of the department that the employee works for”. CREATE ASSERTION SALARY_CONSTRAINT CHECK (NOT EXISTS (SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.Salary> M.Salary AND E.Dno=D.Dnumber AND D.Mgr_ssn=M.Ssn) ); The DBMS is responsible for ensuring that the condition is not violated. 69

70 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Specifying General Constraints as Triggers Objective: to monitor a database and take initiate action when a condition occurs Triggers are expressed in a syntax similar to assertions and include the following: Event Such as an insert, deleted, or update operation Condition Action To be taken when the condition is satisfied 69

71 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Specifying General Constraints as Triggers: Example A trigger to compare an employee’s salary to his/her supervisor during insert or update operations: CREATE TRIGGER INFORM_SUPERVISOR 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); 69

72 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Concept of a View (Virtual Table) in SQL A view is a customized representation of one or more underlying tables or other views (or a mixture of both). A view does not necessarily exist in physical form. Allows full query operations. Allows limited update operations (since the table may not physically be stored). Convenience for expressing certain operations. 70

73 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Concept of a View (Virtual Table) in SQL Advantages of views: Simplify query commands. Provide data security. Enhance programming productivity. 71

74 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Specification of Views in SQL Example: CREATE VIEWWORKS_ON1AS SELECTFname, Lname, Pname, Hours FROMEMPLOYEE, PROJECT, WORKS_ON WHERESsn=Essn AND Pno=Pnumber; Example: CREATE VIEWDEPT_INFO(Dept_name, No_of_emps, Total_sal) AS SELECTDname, COUNT(*), SUM(Salary) FROMDEPARTMENT, EMPLOYEE WHEREDnumber=Dno GROUP BYDname; 72

75 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Specification of Views in SQL Query: retrieve the last name and first name of all employees who work on ‘ProjectX’. SELECTFname, Lname FROMWORKS_ON1 WHEREPname='ProjectX'; A view is supposed to be always up to date. When no longer needed, a view can be dropped: DROP VIEW name 73

76 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Effective View Implementation Two main approaches have been suggested: Query modification: involves modifying the view query into a query on the underlying base tables. I.e, the previous query would be automatically modified to: SELECT Fname, Lname FROM EMPLOYEE, PROJECT, WORKS_ON WHERE Ssn=Essn AND Pno=Pnumber AND Pname='ProjectX'; View Materialization: involves physically creating a temporary view table (should be kept up to date). 74

77 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views View Update A view with a single defining table is updatable if the view attributes contain the primary key of the base relation, as well as all attributes with the NOT NULL constraint that do not have default values specified. Views defined on multiple tables using joins are generally not updatable. Views defined using grouping and aggregate functions are not updatable. 75

78 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views View Update In SQL, the clause WITH CHECK OPTION must be added at the end of the new definition if the view is to be updated. 76

79 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views Recap of SQL Queries 76 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 ] There are three SQL commands to modify the database: INSERT, DELETE, and UPDATE

80

81 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views77 http://www.sqlcourse.com/

82 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views http://www.webcheatsheet.com/sql/interactive_sql_tutorial/ 78

83 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views http://sqlzoo.net/ 79

84 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views80 http://www.sql-tutorial.com/

85 Chapter 8: SQL-99: Schema Definition, Constraints, Queries, and Views81 http://www.onlinecomputerbooks.com/free-sql-books.php


Download ppt "Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems."

Similar presentations


Ads by Google