Download presentation
Presentation is loading. Please wait.
Published byTabitha Morgan Modified over 9 years ago
1
Database Systems 主講人 : 陳建源 日期 :99/9/14 研究室 : 法 401 Email: cychen07@nuk.edu.tw Chapter 8 SQL99 - The Relational Database Standard
2
1. Data Definition in SQL 2. Characteristics of Relations 3. Retrieval Queries in SQL 4. More Complex Queries 5. Specifying Updates in SQL 6. Relational Views in SQL 7. Summary Outline
3
Schema and Catalog Concepts in SQL2 An SQL schema is identified by A schema name An authorization identifier to indicate the user or account who owns the schema Descriptors for each element in the schema Schema elements include the tables, constraints, views, domains, and other constructs (such as authorization grants) that describe the schema 1.Data Definition in SQL
4
A schema is created via the CREATE SCHEMA statement Example Create a schema called COMPANY, owned by the user with authorization identifier JSMITH: CREATE SCHEMA COMPANY AUTHORIZATION JSMITH; 1.Data Definition in SQL
5
Catalog A named collection of schemas in an SQL environment A catalog always contains a special schema called INFORMATION_SCHEMA, which provides information on all the element descriptors of all the schemas in the catalog to authorized users 1.Data Definition in SQL
6
Purpose Used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database CREATE TABLE Specifies a new base relation by giving it a name, and specifying each of its attributes and their data types 1.Data Definition in SQL
7
Data types in SQL2 Numeric INT or INTEGER SMALLINT FLOAT REAL DOUBLE PRECISION DEC(i, j) or DECIMAL(i,j) or NUMERIC(i,j) Character-string CHAR(n) or CHARACTER(n) VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n) 1.Data Definition in SQL
8
Bit-string BIT(n) BIT VARYING(n) Date In the form YYYY-MM-DD Time In the form HH:MM:SS TIME(i) Made up of hour:minute:second plus i additional digits specifying fractions of a second format is hh:mm:ss:ii...i 1.Data Definition in SQL
9
TIMESTAMP Has both DATE and TIME components INTERVAL Specifies a relative value rather than an absolute value Can be DAY/TIME or YEAR/MONTH intervals Can be positive or negative when added to or subtracted from an absolute value, the result is an absolute value 1.Data Definition in SQL
10
In SQL2, it is possible to specify the domain of each attribute and declare the domain name, e.g., CREATE DOMAIN SSN_TYPE AS CHAR(9); We can use SSN_TYPE in place of CHAR(9) 1.Data Definition in SQL
11
A constraint NOT NULL may be specified on an attribute CREATE TABLE DEPARTMENT ( DNAMEVARCHAR(10)NOT NULL, DNUMBER INTEGERNOT NULL, MGRSSNCHAR(9), MGRSTARTDATECHAR(9) ); In SQL2, the CREATE TABLE can be used to specify the primary key, secondary keys, and referential integrity constraints (foreign keys) 1.Data Definition in SQL
12
Primary key attributes can be specified via the PRIMARY KEY Key attributes can be specified via UNIQUE Referential integrity is specified via the FOREIGN KEY clause CREATE TABLE DEPT (DNAMEVARCHAR(10)NOT NULL, DNUMBERINTEGERNOT NULL, MGRSSNCHAR(9), MGRSTARTDATECHAR(9), PRIMARY KEY (DNUMBER), UNIQUE (DNAME), FOREIGN KEY (MGRSSN) REFERENCES EMP); 1.Data Definition in SQL
13
It is also possible to define a default value for an attribute by appending the clause DEFAULT to an attribute definition 1.Data Definition in SQL
15
In SQL2, action can be specified if a referential integrity constraint is violated upon deletion of a referenced tuple or upon modification of a referenced primary key Attaching a referential triggered action clause to any foreign key constraint The options include SET NULL, CASCADE, and SET DEFAULT An option must be qualified with either ON DELETE or ON UPDATE 1.Data Definition in SQL
16
SET NULL (DEFAULT) ON DELETE: the value of the deleted referencing attributes is changed to NULL or the specified default value SET NULL (DEFAULT) ON UPDATE: the value of the updated referencing attributes is changed to NULL or the specified default value CASCADE ON DELETE: delete all the referencing tuples CASCADE ON UPDATE: change the value of the foreign key to the updated (new) primary key value for all referencing tuples 1.Data Definition in SQL
17
A constraint may be given a name, following the keyword CONSTRAINT The names of all constraints within a particular schema must be unique 1.Data Definition in SQL
18
Base tables (or base relations) The relations declared through CREATE TABLE statements are called The relation and its tuples are actually created and stored as a file by the DBMS Virtual relations The relations created through the CREATE VIEW statement The relations may or may not correspond to an actual physical file 1.Data Definition in SQL
19
DROP SCHEMA Used to a whole schema There are two drop behavior options CASCADE: remove the database schema and all its tables, domains, and other elements, e.g., DROP SCHEMA COMPANY CASCADE; RESTRICT: the schema is dropped only if it has no elements 1.Data Definition in SQL
20
DROP TABLE Used to remove a relation (base table) and its definition The relation can no longer be used in queries, updates, or any other commands since its description no longer exists DROP TABLE DEPENDENT; 1.Data Definition in SQL
21
Two options CASCADE: all constraints and views that reference the table are dropped automatically along with the table itself DROP TABLE DEPENDENT CASCADE; RESTRICT: a table is dropped only if it is not referenced in any constraints or views 1.Data Definition in SQL
22
ALTER TABLE Used to change the base relation definition Possible actions include adding or dropping a column (attribute) changing a column definition adding or dropping table constraints Example ALTER TABLE COMPANY.EMPLOYEE ADD JOB VARCHAR(12); 1.Data Definition in SQL
23
The new attribute will have NULLs in all the tuples of the relation Hence, the NOT NULL constraint is not allowed for such an attribute The database users must still enter a value for the new attribute JOB for each EMPLOYEE tuple This can be done using the UPDATE command 2. Characteristics of Relations
24
To drop a column, we must choose either CASCADE or RESTRICT for drop behavior CASCADE: all constraints and views that reference the column are dropped automatically along with the column RESTRICT: the column is drop only if no views or constraints reference the column Example ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS CASCADE; 2. Characteristics of Relations
25
It is also possible to alter a column definition by dropping an existing default clause or by defining a new default clause Example 1 ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN DROP DEFAULT; Example 2 ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN SET DEFAULT "333445555"; 2. Characteristics of Relations
26
Preliminary SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the same as the SELECT operation of the relational algebra 3. Retrieval Queries in SQL
27
Important distinction between SQL and the formal relational model SQL allows a table (relation) to have two or more identical tuples Hence, an SQL relation (table) is a multi-set (sometimes called a bag) of tuples; it is not a set of tuples SQL relations can be constrained to be sets by specifying PRIMARY KEY or UNIQUE attributes, or by using the DISTINCT option in a query 3. Retrieval Queries in SQL
28
Basic form of the SQL SELECT statement SELECT FROM WHERE is a list of attribute names whose values are to be retrieved by the query is a list of the relation names required to process the query is a conditional (Boolean) expression that identifies the tuples to be retrieved by the query 3. Retrieval Queries in SQL
29
Simple SQL Queries Basic SQL queries correspond to using the SELECT, PROJECT, and JOIN operations of the relational algebra All subsequent examples use the COMPANY database Example of a simple query on one relation 3. Retrieval Queries in SQL
32
Query 0: Retrieve the birthdate and address of the employee whose name is 'John B. Smith' Q0:SELECT BDATE, ADDRESS FROM EMPLOYEE WHEREFNAME='John' AND MINIT='B' AND LNAME='Smith’; Similar to a SELECT-PROJECT pair of relational algebra operations the SELECT-clause specifies the projection attributes the WHERE-clause specifies the selection condition 3. Retrieval Queries in SQL
33
BDATE,ADDRESS ( FNAME=‘John’ AND MINIT=‘B’ AND LNAME=‘Smith’ (EMPLOYEE)) However, the result of the query may contain duplicate tuples Result of Q0 BDATEADDRESS 1965-01-09731 Fondren, Houston, TX 3. Retrieval Queries in SQL
34
Query 1: Retrieve the name and address of all employees who work for the 'Research' department Q1:SELECTFNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHEREDNAME='Research' AND DNUMBER=DNO; Similar to a SELECT-PROJECT-JOIN sequence of relational algebra operations (DNAME='Research') is a selection condition (DNUMBER=DNO) is a join condition 3. Retrieval Queries in SQL
35
Query 2: For every project located in 'Stafford', list the project number, the controlling department number, and the department manager's last name, address, and birthdate. Q2:SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROMPROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford’; 3. Retrieval Queries in SQL
36
In Q2, there are two join conditions The join condition DNUM=DNUMBER relates a project to its controlling department The join condition MGRSSN=SSN relates the controlling department to the employee who manages that department 3. Retrieval Queries in SQL
37
Aliases (Renaming) with SQL In SQL, we can use the same name for two (or more) attributes as long as the attributes are in different relations 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 e.g., EMPLOYEE.LNAME, DEPARTMENT.DNAME 3. Retrieval Queries in SQL
38
Some queries need to refer to the same relation twice; In this case, aliases are given to the relation name Query 8: For each employee, retrieve the employee's name, and the name of his or her immediate supervisor Q8:SELECTE.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S WHEREE.SUPERSSN=S.SSN; 3. Retrieval Queries in SQL
39
In Q8, the alternate relation names E and S are called aliases for the EMPLOYEE relation We can think of E and S as two different copies of the EMPLOYEE relation E represents employees in the role of supervisees S represents employees in the role of supervisors We an also use the AS keyword to specify aliases, e.g., for Q8 FROM EMPLOYEE E S FROM EMPLOYEE AS E, EMPLOYEE AS S 3. Retrieval Queries in SQL
40
Aliasing can also be used in any SQL query for convenience Q1B: SELECTE.FNAME, E.NAME, E.ADDRESS FROM EMPLOYEE E, DEPARTMENT D WHERE D.NAME=‘Research’ AND D.DNUMBER=E.DNUMBER; 3. Retrieval Queries in SQL
41
Unspecified WHERE-clause A missing WHERE-clause indicates no condition; hence, all tuples of the relations in the FROM- clause are selected This is equivalent to WHERE TRUE Query 9: Retrieve the SSN values for all employees Q9:SELECT SSN FROMEMPLOYEE; 3. Retrieval Queries in SQL
42
If more than one relation is specified in the FROM-clause and there is no join condition, then the CARTESIAN PRODUCT of tuples is selected Query 10: Retrieve all combinations of EMPLOYEE SSN and DEPARTMENT DNAME Q10:SELECTSSN, DNAME FROMEMPLOYEE, DEPARTMENT; It is extremely important not to overlook specifying any selection and join conditions in the WHERE- clause 3. Retrieval Queries in SQL
43
Use of * To retrieve all the attribute values of the selected tuples, a * is used, which stands for all the attributes Query 1C: Retrieves all the attribute values of EMPLOYEE at DEPARTMENT number 5 Q1C:SELECT * FROMEMPLOYEE WHEREDNO=5; 3. Retrieval Queries in SQL
44
Query Q1D: Retrieves all the attributes of an EMPLOYEE and the attributes of the DEPARTMENT he or she works in, for every employee of the ‘Research’ department Q1D:SELECT* FROMEMPLOYEE, DEPARTMENT WHEREDNAME='Research' AND DNO=DNUMBER; 3. Retrieval Queries in SQL
45
Use of DISTINCT SQL does not treat a relation as a set; duplicate tuples can appear To eliminate duplicate tuples in a query result, the keyword DISTINCT is used Q11:SELECT SALARY FROMEMPLOYEE; Q11A: SELECT DISTINCT SALARY FROMEMPLOYEE; 3. Retrieval Queries in SQL
46
The result of Q11 may have duplicate SALARY values whereas Q11A does not have any duplicate values 3. Retrieval Queries in SQL
47
Set Operations 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 The resulting relations of these set operations are sets of tuples; duplicates are eliminated 3. Retrieval Queries in SQL
48
The set operations apply only to union compatible relations Query 4: 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 3. Retrieval Queries in SQL
49
Q4: (SELECT PNAME FROMPROJECT, DEPARTMENT, EMPLOYEE WHEREDNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith'); UNION (SELECT PNAME FROMPROJECT, WORKS_ON, EMPLOYEE WHEREPNUMBER=PNO AND ESSN=SSN AND LNAME='Smith'); 3. Retrieval Queries in SQL
50
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 '_' replaces a single arbitrary character Query 12: Retrieve all employees whose address is in Houston, Texas 3. Retrieval Queries in SQL
51
Q12: SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%’; Query 12A: Retrieve all employees who were born during the 1950s Q12A: SELECT FNAME, LNAME FROMEMPLOYEE WHEREBDATE LIKE '__5_______’; Here, '5' must be the 3th character of the string 3. Retrieval Queries in SQL
52
Arithmetic Operations The standard arithmetic operators '+', '-'. '*', and '/' can be applied to numeric values in an SQL query result Query 13: Show the effect of giving all employees who work on the 'ProductX' project a 10% raise Q13: SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECT WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX’; 3. Retrieval Queries in SQL
53
ORDER BY The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s) The default order is in ascending order Query 15: Retrieve a list of employees and the projects each works in, ordered by the employee's department, and within each department ordered alphabetically by employee last name 3. Retrieval Queries in SQL
54
Q15:SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHEREDNUMBER=DNO AND SSN=ESSN ANDPNO=PNUMBER ORDER BYDNAME, LNAME, FNAME; We can specify the keyword DESC if we want a descending order ORDER BY DNAME DESC, LNAME ASC, FNAME ASC 3. Retrieval Queries in SQL
55
Nesting of Queries A complete SELECT query, called a nested query, can be specified within the WHERE-clause of another query, called the outer query Many of the previous queries can be specified in an alternative form using nesting Query 1: Retrieve the name and address of all employees who work for the 'Research' department 4. More Complex Queries
56
Q1:SELECTFNAME, LNAME, ADDRESS FROM EMPLOYEE WHEREDNO IN (SELECT DNUMBER FROMDEPARTMENT WHEREDNAME='Research'); The nested query selects the number of the 'Research' department The outer query select an EMPLOYEE tuple if its DNO value is in the result of either nested query 4. More Complex Queries
57
The comparison operator IN compares a value v with a set (or multi-set) of values V, and evaluates to TRUE if v is one of the elements in V In general, we can have several levels of nested queries In this example, the nested query is not correlated with the outer query A reference to an unqualified attribute refers to the relation declared in the innermost nested query 4. More Complex Queries
58
Query 16: Retrieve the name of each employee who has a dependent with the same first name and same sex as the employee Q16: 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); 4. More Complex Queries
59
Correlated Nested Queries If a condition in the WHERE-clause of a nested query references an 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 4. More Complex Queries
60
A query written with nested SELECT... FROM... WHERE... blocks and using the = or IN comparison operators can always be expressed as a single block query For example, Q16 may be written as in Q16A Q16A: SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E, DEPENDENT AS D WHERE E.SSN = D.ESSN AND E.SEX = D.SEX AND E.FNAME=D.DEPENDENT_NAME; 4. More Complex Queries
61
The EXISTS Function EXISTS is used to check whether the result of a correlated nested query is empty or not We can formulate Query 16 in an alternative form that uses EXISTS as Q16B below 4. More Complex Queries
62
Q16: SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE EXISTS (SELECT * FROM DEPENDENT WHERE E.SSN = ESSN AND E.SEX = SEX AND E.FNAME = DEPENDENT_NAME); 4. More Complex Queries
63
Query 6: Retrieve the names of employees who have no dependents Q6:SELECT FNAME, LNAME FROMEMPLOYEE WHERENOT EXISTS (SELECT * FROM DEPENDENT WHERESSN=ESSN); In Q6, the correlated nested query retrieves all DEPENDENT tuples related to an EMPLOYEE If none exist, EMPLOYEE tuple is selected 4. More Complex Queries
64
Explicit Sets It is also possible to use an explicit (enumerated) set of values in the WHERE- clause rather than a nested query Query 17: Retrieve the social security numbers of all employees who work on project number 1, 2, or 3 Q13:SELECT DISTINCT ESSN FROMWORKS_ON WHEREPNO IN (1, 2, 3); 4. More Complex Queries
65
NULLS in SQL Queries SQL allows queries that check if a value is NULL (missing or undefined or not applicable) Any comparison with null returns unknown E.g. 5 null or null = null 4. More Complex Queries
66
Three-valued logic using the truth value unknown: OR: (unknown or true) = true, (unknown or false) = unknown, (unknown or unknown) = unknown AND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknown NOT: (not unknown) = unknown “P is unknown” evaluates to true if predicate P evaluates to unknown 4. More Complex Queries
67
SQL uses IS or IS NOT to compare NULLs because it considers each NULL value distinct from other NULL values Query 18: Retrieve the names of all employees who do not have supervisors Q18:SELECT FNAME, LNAME FROMEMPLOYEE WHERESUPERSSN IS NULL; Result of Q18 4. More Complex Queries
68
Aggregate Functions Include COUNT, SUM, MAX, MIN, and AVG Query 19: Find the sum of salaries, the maximum salary, the minimum salary, and the average salary among all employees Q19: SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE; 4. More Complex Queries
69
Queries 21 and 22: Retrieve the total number of employees in the company (Q21), and the number of employees in the 'Research' department (Q22) Q21:SELECT COUNT (*) FROMEMPLOYEE; Q22:SELECT COUNT (*) FROMEMPLOYEE, DEPARTMENT WHEREDNO=DNUMBER AND DNAME='Research’; 4. More Complex Queries
70
Grouping In many cases, we want to apply the aggregate functions to subgroups of tuples in a relation Each subgroup consists of the tuples having the same value for the grouping attribute(s) The function is applied to each subgroup independently SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause 4. More Complex Queries
71
Query 24: For each department, retrieve the department number, the number of employees in the department, and their average salary Q24:SELECT DNO, COUNT (*), AVG (SALARY) FROMEMPLOYEE GROUP BYDNO; In Q24, the EMPLOYEE are divided into groups having the same value for attribute DNO The COUNT and AVG functions are applied to each subgroup of tuples separately 4. More Complex Queries
72
Illustration of Q24 4. More Complex Queries
73
Query 25: For each project, retrieve the project number, project name, and the number of employees working on that project Q25: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 4. More Complex Queries
74
The HAVING-CLAUSE Sometimes we want to retrieve the values of 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) 4. More Complex Queries
75
Query 26: For each project on which more than two employees work, retrieve the project number, project name, and the number of employees Q26:SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT (*) > 2; 4. More Complex Queries
76
Illustration of Query 26 4. More Complex Queries
77
Illustration of Query 26 4. More Complex Queries
78
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, ordered as follows SELECT FROM [WHERE ] [GROUP BY ] [HAVING ] [ORDER BY ] 4. More Complex Queries
79
A query is evaluated by first applying the FROM-clause, followed by the WHERE-clause, then GROUP BY and HAVING, and finally the SELECT-clause 4. More Complex Queries
80
SQL commands to modify the database INSERT, DELETE, and UPDATE INSERT Command 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 5. Specifying Updates in SQL
81
Example: Add a new tuple to the EMPLOYEE relation U1:INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', '653298653', '30-DEC-52', '98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4); 5. Specifying Updates in SQL
82
An alternate form of INSERT specifies explicitly the attribute names that correspond to the values in the new tuple Attributes with NULL values can be left out Example: Insert a tuple for a new EMPLOYEE for whom we only know the FNAME, LNAME, and SSN attributes U1A:INSERT INTO EMPLOYEE (FNAME, LNAME, SSN) VALUES ('Richard', 'Marini', '653298653') 5. Specifying Updates in SQL
83
Note: Only the constraints specified in the DDL commands are automatically enforced by the DBMS when updates are applied to the database If a system does not support some constraint, the users must enforce the constraint U2: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN, DNO) VALUES (‘Robert’, ‘Hatcher’, ‘980760540’, 2); (* U2 is rejected if referential integrity checking is provided by DBMS *) 5. Specifying Updates in SQL
84
A DBMS enforcing NOT NULL will reject an INSERT command in which an attribute declared to be NOT NULL does not have a value U2A: INSERT INTO EMPLOYEE (FNAME, LNAME, DNO) VALUES (‘Robert’, ‘Hatcher’, 5); (* U2A is rejected if NOT NULL checking is provided by DBMS *) 5. Specifying Updates in SQL
85
Another variation of INSERT allows insertion of multiple tuples resulting from a query into a relation Example: Suppose we want to create a temporary table that has the name, number of employees, and total salaries for each department. A table DEPTS_INFO is created by U3A, and is loaded with the summary information retrieved from the database by the query in U3B 5. Specifying Updates in SQL
86
U3A:CREATE TABLE DEPTS_INFO (DEPT_NAMEVARCHAR(10), NO_OF_EMPSINTEGER, TOTAL_SALINTEGER); U3B: INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) SELECTDNAME, COUNT (*), SUM (SALARY) FROMDEPARTMENT, EMPLOYEE WHEREDNUMBER=DNO GROUP BYDNAME ; 5. Specifying Updates in SQL
87
DELETE Command Removes tuples from a relation Includes a WHERE-clause to select the tuples to be deleted 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 5. Specifying Updates in SQL
88
Examples: U4A:DELETE FROM EMPLOYEE WHERELNAME='Brown’ U4B:DELETE FROM EMPLOYEE WHERESSN='123456789’ U4C:DELETE FROM EMPLOYEE WHEREDNO IN(SELECT DNUMBER FROMDEPARTMENT WHEREDNAME='Research') U4D:DELETE FROM EMPLOYEE 5. Specifying Updates in SQL
89
UPDATE Command 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 5. Specifying Updates in SQL
90
Example: Change the location and controlling department number of project number 10 to 'Bellaire' and 5, respectively. U5: UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5 WHERE PNUMBER=10 Example: Give all employees in the 'Research' department a 10% raise in salary. 5. Specifying Updates in SQL
91
U6: UPDATE EMPLOYEE SETSALARY = SALARY *1.1 WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') In this request, the modified SALARY value depends on the original SALARY value in each tuple 5. Specifying Updates in SQL
92
Basic concepts A view is a single virtual table that is derived from other tables, which could be base tables or previously defined views A view does not necessarily exist in physical form; that means the view does not store any tuples There are limitations on possible update operations that can be applied to views There is no limitation on querying a view 6. Relational Views in SQL
93
Specify Views Using CREATE VIEW command The view attribute names can be inherited from the attribute names of the tables in the defining query Examples: V1:CREATE VIEW WORKS_ON1 AS SELECT FNAME, LNAME, PNAME, HOURS FROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBER ; 6. Relational Views in SQL
94
V2:CREATE VIEWDEPT_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) AS SELECTDNAME, COUNT (*), SUM (SALARY) FROMDEPARTMENT, EMPLOYEE WHEREDNUMBER=DNO GROUP BY DNAME; 6. Relational Views in SQL
95
Queries on Views A view can be defined to simplify frequently occurring queries Example: Retrieve the last name and first name of all employees who work on 'ProjectX'. QV1:SELECTPNAME, FNAME, LNAME FROMWORKS_ON1 WHEREPNAME='ProjectX'; Without the view WORKS_ON1, this query specification would require two join conditions 6. Relational Views in SQL
96
A view is always up-to-date If the base tables on which the view is defined are modified, the DBMS is responsible for keeping it up to date Hence, the view is not realized at the time of view definition, but rather at the time we specify a query on the view A view is removed using the DROP VIEW command Example: V1A: DROP VIEW WORKS_ON1; 6. Relational Views in SQL
97
Updating of Views A view update operation may be mapped in multiple ways to update operations on the defining base relations The topic of updating views is still an active research area Example: Suppose we issue the command in UV1 to update the WORKS_ON1 view by modifying the PNAME attribute of 'John Smith' from 'ProductX' to 'ProductY'. 6. Relational Views in SQL
98
UV1: UPDATE WORKS_ON1 SET PNAME = 'ProductY' WHERE LNAME='Smith' AND FNAME='John' AND PNAME='ProductX’ This can be mapped into several updates on the base relations to give the desired update on the view Two possibilities 1. Change the name of the 'ProductX' tuple in the PROJECT relation to 'ProductY’ 2. Relate 'John Smith' to the 'ProductY' PROJECT tuple in place of the 'ProductX' PROJECT tuple 6. Relational Views in SQL
99
Method 1 UPDATE PROJECT SETPNAME = 'ProductY' WHEREPNAME = 'ProductX’ This has the effect of changing all the view tuples with PNAME = ‘ProductX’ It is quite unlikely that the user who specified view update UV1 wants the update to be interpreted this way 6. Relational Views in SQL
100
» Method 2 UPDATE WORKS_ON SET PNO = (SELECT PNUMBER FROM PROJECT WHERE PNAME='ProductY') WHERE ESSN IN (SELECT SSN FROM EMPLOYEE WHERE LNAME='Smith' AND FNAME='John') AND PNO IN (SELECT PNUMBER FROM PROJECT WHERE PNAME='ProductX') 6. Relational Views in SQL
101
Some view updates may not make much sense Example: Modify the TOTAL_SAL attribute of DEPT_INFO as in UV2 UV2:UPDATEDEPT_INFO SETTOTAL_SAL=100000 WHEREDNAME='Research'; In general, we cannot guarantee that any view can be updated A view update is feasible only if one update on the base relations can accomplish the desired update effect on the view 6. Relational Views in SQL
102
If a view update can be mapped to more than one update on the underlying base relations, we have to choose the desired update General guideline A view with a single defining table is updatable if the view attributes contain the primary key Views defined on multiple tables using joins are generally not updatable Views defined aggregate functions are not updatable 6. Relational Views in SQL
103
7. Summary CREATE VIEW SELECT INSERT, DELETE, and UPDATE CREATE, DROP, and ALTER
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.