Download presentation
Presentation is loading. Please wait.
Published byKristina Bell Modified over 9 years ago
1
Chapter 5 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Peter Rob & Carlos Coronel
2
In this chapter, you will learn: 4The basic commands and functions of SQL 4How SQL is used for data manipulation (to add, modify, delete, and retrieve data) 4How to use SQL to query a database to extract useful information 4How SQL is used for data administration (to create tables, indexes, and views) 4About more advanced SQL features such as updatable views, stored procedures, and triggers
3
Introduction to SQL 4Ideal database language u Create database and table structures u Perform basic data management chores (add, delete, and modify) u Perform complex queries to transform data into useful information
4
Introduction to SQL 4SQL (Structured Query Language) meets ideal database language requirements: u SQL coverage fits into two categories: l Data definition l Data manipulation u SQL is relatively easy to learn. u ANSI prescribes a standard SQL. l SQL2 : SQL-92 l SQL3 : SQL-98/99 support object-oriented data management
5
Data Definition Commands 4The Database Model u Simple Database -- PRODUCT and VENDOR tables l Each product is supplied by only a single vendor. l A vendor may supply many products.
6
Data Definition Commands 4The Tables and Their Components u The VENDOR table contains vendors who are not referenced in the PRODUCT table. PRODUCT is optional to VENDOR. u Some vendors have never supplied a product ( 0,N )
7
Data Definition Commands 4The Tables and Their Components u Existing V_CODE values in the PRODUCT table must have a match in the VENDOR table. u A few products are supplied factory-direct, a few are made in-house, and a few may have been bought in a special warehouse sale. That is, a product is not necessarily supplied by a vendor. VENDOR is optional to PRODUCT. ( 0,1 )
8
PRODUCT VENDER CH5_TEXT
9
Data Definition Commands 4Create database structure u Holds all tables and is a collection of physical files stored on disk u DBMS automatically creates tables to store metadata u Database administrator creates structure or schema l Logical group of tables or logical database l Groups tables by owner l Enforces security
10
Data Definition Commands 4Creating the Database Structure CREATE SCHEMA AUTHORIZATION ; Example: CREATE SCHEMA AUTHORIZATION JONES; u Schema : logical database structure a group of database objects- such as tables and indexes – that are related to each other. CREATE DATABASE ; Example: CREATE DATABASE CH5;
11
A Data Dictionary for the CH5 Database Table 5.1
12
Some Common SQL Data Types NumericNUMBER(L,D) INTEGER SMALLINT DECIMAL(L,D) CharacterCHAR(L) VARCHAR(L) DateDATE Data TypeFormat
13
Data Definition Commands 4Creating Table Structures CREATE TABLE ( );
14
Data Definition Commands CREATE TABLE VENDOR (V_CODE INTEGER NOT NULL UNIQUE, V_NAME VARCHAR(35)NOT NULL, V_CONTACT VARCHAR(15)NOT NULL, V_AREACODE CHAR(3) NOT NULL, V_PHONE CHAR(3) NOT NULL, V_STATE CHAR(2) NOT NULL, V_ORDER CHAR(1) NOT NULL, PRIMARY KEY (V_CODE));
15
FOREIGN KEYREFERENCES VENDOR CREATE TABLE PRODUCT( P_CODEVARCHAR(10) NOT NULLUNIQUE, P_DESCRIPTVARCHAR(35)NOT NULL, P_INDATEDATENOT NULL, P_ONHANDSMALLINTNOT NULL, P_MINSMALLINTNOT NULL, P_PRICEDECIMAL(8,2)NOT NULL, P_DISCOUNTDECIMAL(4,1)NOT NULL, V_CODESMALLINT, PRIMARY KEY (P_CODE), FOREIGN KEY (V_CODE) REFERENCES VENDOR ON DELETE RESTRICT ON UPDATE CASCADE); 4ON DELETE RESTRICT cannot delete a vender as long as there is a product that references that vender 4ON UPDATE CASCADE update V_CODE in VENDER → update V_CODE in PRODUCT
16
Data Definition Commands 4Adherence to entity integrity and referential integrity rules is crucial 4SQL Integrity Constraints u Entity Integrity l PRIMARY KEY NOT NULL and UNIQUE u Referential Integrity l FOREIGN KEY ON DELETE ON UPDATE
17
SQL Command Coverage Table 5.3
18
Data Entry and Saving 4Enters data into a table 4Saves changes to disk INSERT INTO VALUES (attribute 1 value, attribute 2 value, … etc.); COMMIT ;
19
Basic Data Management 4Data Entry INSERT INTO VALUES (attribute 1 value, attribute 2 value, … etc.); INSERT INTO VENDOR VALUES(‘21225, ’Bryson, Inc.’, ’Smithson’, ’615’,’223-3234’, ’TN’, ’Y’); INSERT INTO PRODUCT VALUES(‘11 QER/31’, ’Power painter, 15 psi., 3-nozzle’, ’07/02/1999’, 8.5, 109.99, 0.00, 25595);
20
Figure 5.3 A form-based Data View and Entry Screen
21
Basic Data Management 4Saving the Table Contents COMMIT ; COMMIT PRODUCT; u Any changes made to the table contents are not physically saved on disk until l COMMIT l close the database l log out of SQL
22
Listing Table Contents and Other Commands 4Allows table contents to be listed 4UPDATE command makes data entry corrections 4ROLLBACK command restores database back to previous condition if COMMIT hasn’t been used 4DELETE command removes table row SELECT FROM ;
23
Basic Data Management 4Listing the Table Contents SELECT * FROM PRODUCT; SELECT P_CODE, P_DESCRIPT, P_INDATE, P_ONHAND, P_MIN, P-PRICE, P_DISCOUNT, V_CODE FROM PRODUCT;
24
Figure 5.4 The Contents of the PRODUCT Table
25
Basic Data Management 4Making a Correction UPDATE PRODUCT SET P_INDATE = ‘12/11/96’ WHERE P_CODE = ‘13-Q2/P2’; UPDATE PRODUCT SET P_INDATE = ‘12/11/96’, P_PRICE = 15.99, P_MIN = 10 WHERE P_CODE = ‘13-Q2/P2’;
26
Basic Data Management 4Restoring the Table Contents ROLLBACK u If COMMIT not yet u Does not require to specify the table name. SQL assumes that the database currently in memory is the one to be restored. 4Update integrity in transaction management (Ch.9) u COMMIT u ROLLBACK
27
Basic Data Management 4Deleting Table Rows DELETE FROM PRODUCT WHERE P_CODE = ‘2238/QPD’; DELETE FROM PRODUCT WHERE P_MIN = 5;
28
Queries 4Creating partial listings of table contents SELECT FROM WHERE ; Table 5.4 Mathematical Operators
29
Queries 4Partial Listing of Table Contents SELECT FROM WHERE ; SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE = 21344; Figure 5.5
30
Figure 5.6 The Microsoft Access QBE and Its SQL QBE (Query By Example) query generator
31
Examples 4Mathematical operators 4Mathematical operators on character attributes 4Mathematical operators on dates SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344; SELECT P_CODE,P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE FROM PRODUCT WHERE P_CODE < ‘1558-QWI’; SELECT P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE,PINDATE FROM PRODUCT WHERE P_INDATE >= ‘01/20/2002’;
32
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344; Figure 5.7 Queries
33
SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE FROM PRODUCT WHERE P_PRICE <= 10; Figure 5.8 Queries
34
4Using Mathematical Operators on Character Attributes SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE FROM PRODUCT WHERE P_CODE < ‘1558-QWI’; Figure 5.9 Queries
35
4Using Mathematical Operators on Dates SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE, P_INDATE FROM PRODUCT WHERE P_INDATE >= ‘08/15/1999’; Figure 5.10 Queries
36
Computed Columns 4New columns can be created through valid computations or formulas u Formulas may contain mathematical operators u May contain attributes of any tables specified in FROM clause 4Alias is alternate name given to table or column in SQL statement SELECT P_DESCRIPT,P_ONHAND,P_PRICE, P_ONHAND*P_PRICE AS TOTVALUE FROM PRODUCT; P_DESCRIPTP_ONHANDP_PRICETOTVALUE
37
Operators 4Logical: AND, OR, NOT 4Rules of precedence u Conditions within parenthesis executed first u Boolean algebra 4Special u BETWEEN - defines limits u IS NULL - checks for nulls u LIKE - checks for similar string u IN - checks for value in a set u EXISTS - opposite of IS NULL SELECT * FROM PRODUCT WHERE V_CODE = 21344 OR V_CODE = 24288;
38
4Logical Operators: AND, OR, and NOT SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE=21344 OR V_CODE=24288; Figure 5.13 Queries
39
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE ‘07/15/1999’ ; Figure 5.14 Queries
40
SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE (P_PRICE 07/15/1999’) OR V_CODE=24288; Figure 5.15 Queries
41
4Special Operators u BETWEEN - used to define range limits. u IS NULL - used to check whether an attribute value is null u LIKE - used to check for similar character strings. u IN - used to check whether an attribute value matches a value contained within a (sub)set of listed values. u EXISTS - used to check whether an attribute has a value. - the opposite of IS NULL.
42
4Special Operators BETWEEN is used to define range limits. SELECT * FROM PRODUCT WHERE P_PRICE BETWEEN 50.00 AND 100.00 ; SELECT * FROM PRODUCT WHERE P_PRICE>50.00 AND P_PRICE<100.00 ; Queries
43
4Special Operators IS NULL is used to check whether an attribute value is null. SELECT P_CODE, P_DESCRIPT FROM PRODUCT WHERE P_MIN IS NULL; SELECT P_CODE, P_DESCRIPT FROM PRODUCT WHERE P_INDATE IS NULL; Queries
44
4Special Operators LIKE is used to check for similar character strings. SELECT * FROM VENDOR WHERE V_CONTACT LIKE ‘Smith%’; SELECT * FROM VENDOR WHERE V_CONTACT LIKE ‘SMITH%’; u % : c n, c=any character, n ≧ 0 u _ : c 1 Queries
45
4Special Operators IN is used to check whether an attribute value matches a value contained within a (sub)set of listed values. SELECT * FROM PRODUCT WHERE V_CODE IN (21344, 24288); Queries
46
4EXISTS is used to check whether an attribute has value. DELETE FROM PRODUCT WHERE P_CODE EXISTS; SELECT * FROM PRODUCT WHERE V_CODE EXISTS;
47
Advanced Data Management Commands 4Changing Table Structures ALTER TABLE MODIFY ( ); ALTER TABLE ADD ( );
48
4Changing a Column’s Data Type ALTER TABLE PRODUCT MODIFY (V_CODE CHAR(5)); 4Changing Attribute Characteristics ALTER TABLE PRODUCT MODIFY (P_PRICE DECIMAL(9,2)); 4Adding a New Column to the Table ALTER TABLE PRODUCT ADD (P_SALECODE CHAR(1)); Advanced Data Management Commands
49
UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_CODE = ‘1546-QQ2’; Advanced Data Management Commands
50
UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_CODE IN (‘2232/QWE’, ‘2232/QTY’); Advanced Data Management Commands
51
UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_INDATE < ‘07/10/1999’; UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_INDATE >= ‘08/15/1999’ AND P_INDATE < ‘08/20/1999’; Advanced Data Management Commands
52
Selected PRODUCT Table Attributes: Multiple Update Effect Advanced Data Management Commands
53
The Arithmetic Operators Λ
54
4Copying Parts of Tables u Need not be identical: l Column names l Number of columns u Column characteristics must match CREATE TABLE PART PART_CODECHAR(8) NOT NULL UNIQUE, PART_DESCRIPTCHAR(35), PART_PRICEDECIMAL(8,2), PRIMARY KEY(PART_CODE)); INSERT INTO PART (PART_CODE,PART_DESCRIPT,PART_PRICE) SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT; Advanced Data Management Commands
55
The Part Attributes Copied from the PRODUCT Table
56
4Deleting a Table from the Database u DROP TABLE ; DROP TABLE PART; Advanced Data Management Commands
57
4Primary and Foreign Key Designation u For reestablish the integrity rules l Forgot to define l Imported tables from a different database ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE); ALTER TABLE PRODUCT ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR; ALTER TABLE PRODUCT ADD PRIMARY KEY (P_CODE) ADD FOREIGN KEY (V_CODE) REFERENCES VENDOR; Advanced Data Management Commands
58
More Complex Queries and SQL Functions 4Ordering a Listing ORDER BY SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE FROM PRODUCT ORDER BY P_PRICE;
59
Selected PRODUCT Table Attributes Ordered by (Ascending) P_PRICE
60
The Partial Listing of the EMPLOYEE Table
61
4Cascading order sequence SELECT EMP_LNAME,EMP_FNAME,EMP_INITIAL,EMP_AREACODE,EMP_PHONE FROM EMPLOYEE ORDER BY EMP_LNAME, EMP_FNAME, EMP_INITIAL;
62
4Descending order DESC SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE FROM PRODUCT WHERE P_INDATE<‘08/20/1999’ AND P_PRICE<=50.00 ORDER BY V_CODE, P_PRICE DESC;
63
4Listing Unique Values DISTINCT SELECT DISTINCT V_CODE FROM PRODUCT; More Complex Queries and SQL Functions
64
Some Basic SQL Aggregate Functions
65
Querying a Query: Nested Process 4COUNT DISTINCT SELECT COUNT(DISTINCT V_CODE) FROM PRODUCT; 6
66
COUNT Function Output Examples
67
MAX and MIN Function Output Examples
68
4MAX SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT WHERE P_PRICE = (SELECT MAX(P_PRICE) FROM PRODUCT);
69
SUM SELECT SUM(P_ONHAND*P_PRICE) FROM PRODUCT; AVG SELECT P_DESCRIPT, P_ONHAND, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE > (SELECT AVG(P_PRICE) FROM PRODUCT) ORDER BY P_PRICE DESC; More Complex Queries and SQL Functions
70
AVG Function Output Examples
71
Determine whether goods that have been in inventory for a certain length of time should be placed on special sale.
72
4Grouping Data GROUP BY SELECT P_SALECODE, MIN(P_PRICE) FROM PRODUCT_2 GROUP BY P_SALECODE;
73
GROUP BY clause 4 The GROUP BY clause is valid only when used in conjunction with one of the SQL arithmetic functions: COUNT, MIN, MAX, AVG, SUM SELECT V_CODE, COUNT(DISTINCT(P_CODE)) FROM PRODUCT_2 GROUP BY V_CODE; 4Otherwise, you will generate a “not a GROUP BY expression” error. SELECT V_CODE, P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT_2 GROUP BY V_CODE;
74
Improper Use of the GROUP BY Clause ERROR
75
GROUP BY’s HAVING clause 4WHERE ( SELECT ) u Applies to columns and expressions for individual rows 4HAVING ( GROUP BY ) u Applies to the output of a GROUP BY command 4SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE) FROM PRODUCT_2 GROUP BY V_CODE; 4SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE) FROM PRODUCT_2 GROUP BY V_CODE HAVING AVG(P_PRICE)<10;
76
An Application of the HAVING Clause
77
4Virtual Tables: Creating a View u Logical table exists only in memory u Can be treated as though it were a real table 4CREATE VIEW PRODUCT_3 AS SELECT P_DESCROPT, P_ONHAND, P_PRICE FROM PRODUCT WHERE P_PRICE > 50.0 ; More Complex Queries and SQL Functions
78
Creating a View
79
4SQL Indexes u Improve the efficiency of data search u Created to meet particular search criteria CREATE INDEX P_CODEX ON PRODUCT(P_CODE); u When the index field is a primary key whose values must not be duplicated CREATE UNIQUE INDEX P_CODEX ON PRODUCT(P_CODE); More Complex Queries and SQL Functions
80
4Joining Database Tables SELECT PRODUCT.P_DESCRIPT,PRODUCT.P_PRICE, VENDOR.V_NAME, VENDOR.V_CONTACT, VENDOR.V_AREACODE, VENDOR.V_PHONE FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE=VENDOR.V_CODE; More Complex Queries and SQL Functions
81
The Results of a JOIN
82
SELECT P_DESCRIPT, P_PRICE, V_NAME, V_CONTACT, V_AREACODE, V_PHONE FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE=VENDOR.V_CODE AND P_INDATE > ‘08/15/1999’; More Complex Queries and SQL Functions
83
Procedural language 4A term used in contrast to declarative language to describe a language where the programmer specifies an explicit sequences of steps to follow to produce a result. 4Common procedural languages include Basic, Pascal, C. 4Declarative languages describe relationships between variables in terms of functions or inference rules and the language executor (interpreter or compiler) applies some fixed algorithm to these relations to produce a result. 4The most common examples of declarative languages are logic programming languages such as Prolog and functional languages like Haskell.
84
Procedural SQL 4Shortcomings of SQL u SQL doesn’t support execution of a stored set of procedures based on some logical condition. IF-THEN-ELSE u SQL fails to support the looping operations. DO-WHILE 4Solutions u Embedded SQL l SQL statements can be inserted within the procedural programming language u Shared Code l Critical code is isolated and shared by all application programs. l This approach allows better maintenance. u Procedural SQL(PL/SQL)
85
Procedural SQL 4Procedural SQL u Procedural SQL allows the use of procedural code and SQL statements that are stored within the database. u The procedural code is executed by the DBMS when it is invoked by the end user. u End users can use PL/SQL to create: l Triggers l Stored procedures l PL/SQL functions
86
Procedural SQL 4Triggers u A trigger is procedural SQL code that is automatically invoked by the RDBMS upon the occurrence of a data manipulation event. l A trigger is always invoked before or after a data row is selected, inserted, or updated. l A trigger is always associated with a database table. l Each database table may have one or more triggers. l A trigger is executed as part of the transaction that triggered it.
87
Procedural SQL u Role of triggers l Triggers can be used to enforce constraints that cannot be enforced at the design and implementation levels. l Triggers add functionality by automating critical actions and providing appropriate warnings and suggestions for remedial action. l Triggers can be used to update table values, insert records in tables, and call other stored procedures.
88
The Revised PRODUCT Table u If P_ONHAND( 庫存 ) <= P_MIN( 安全存量 ) set P_REORDER = “Yes”
89
The PRODUCT List Output in the Oracle RDBMS u in Oracle : P_REORDER = 1/0 for Yes/No
90
Procedural SQL 4Syntax to create a trigger in ORACLE CREATE OR REPLACE TRIGGER [BEFORE/AFTER] [DELETE/INSERT/UPDATE OF ] ON [FOR EACH ROW] BEGIN PL/SQL instructions; …………… END;
91
Procedural SQL Creation of the Oracle Trigger for the PRODUCT Table CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDER AFTER INSERT OR UPDATE OF P_ONHAND ON PRODUCT BEGIN UPDATE PRODUCT SET P_REORDER = 1 WHERE P_ONHAND <= P_MIN; END;
92
Creation of the Oracle Trigger for the PRODUCT Table
93
The PRODUCT Table’s P_REORDER Field is Updated by the Trigger UPDATE PRODUCT SET P_ONHAND = 4 WHERE P_CODE = ’11QER/31’;
94
The P_REORDER Value Mismatch UPDATE PRODUCT SET P_MIN = 7 WHERE P_CODE = ’2232/QWE’;
95
The Second Version of the PRODUCT_REORDER Trigger CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDER AFTER INSERT OR UPDATE OF P_ONHAND, P_MIN ON PRODUCT BEGIN UPDATE PRODUCT SET P_REORDER = 1 WHILE P_ONHAND <= P_MIN; END;
96
The Second Version of the PRODUCT_REORDER Trigger
97
UPDATE PRODUCT SET P_MIN = 10 WHERE P_CODE = ’23114-AA’;
98
The P_REORDER Flag Has Not Been Properly Set After Increasing the P_ONHAND Value UPDATE PRODUCT SET P_ONHAND = P_ONHAND + P_MIN WHERE P_CODE = ’11QER/31’; 4 25 Never reset it to 0!
99
The Third Version of the PRODUCT_REORDER Trigger CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDER BEFORE INSERT OR UPDATE OF P_ONHAND, P_MIN ON PRODUCT BEGIN IF :NEW.P_ONHAND <= NEW.P_MIN THEN :NEW.P_REORDER = 1; ELSE :NEW.P_REORDER = 0; END IF; END;
100
The Third Version of the Product Reorder Trigger
101
After creating the new trigger, we can execute an UPDATE statement to fire it. UPDATE PRODUCT SET P_ONHAND = P_ONHAND
102
Execution of the Third Trigger Version
103
Procedural SQL 4Stored Procedures u A stored procedure is a named collection of procedural and SQL statements. u Stored procedures are stored in the database and invoked by name. u Stored procedures are executed as a unit.
104
Procedural SQL 4Syntax to create a stored procedure CREATE OR REPLACE PROCEDURE procedure_name (argument IN/OUT data-type, etc) IS/AS BEGIN DECLARE variable name and data type PL/SQL or SQL statements; END; 4Syntax to invoke a stored procedure EXEC store_procedure_name(parameter, parameter, …)
105
Procedural SQL 4Stored Procedures u DECLARE is used to specify the variables used within the procedure. u Argument specifies the parameters that are passed to the stored procedure. u IN / OUT indicates whether the parameter is for INPUT or OUTPUT or both. u Data-type is one of the procedural SQL data types used in the RDBMS.
106
Creating and Invoking A Simple Stored Procedure
107
The PROD_SALE Stored Procedure CREATE OR REPLACE PROCEDURE PROD-SALE (CODE IN VARCHAR2, QTYSOLD IN NUMBER) AS BEGIN UPDATE PRODUCT SET P_ONHAND = P_ONHAND - QTYSOLD WHERE P_CODE = CODE; END;
108
Creation of the PROD_SALE Stored Procedure
109
Executing the PROD_SALE Stored Procedure
110
Procedural SQL 4PL/SQL Stored Functions u A stored function is a named group of procedural and SQL statements that returns a value. u Syntax to create a function: CREATE FUNCTION function_name (argument IN data-type, etc) RETURN data-type AS BEGIN PL/SQL statements; RETURN (value); …… END;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.