Chapter 5 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Peter Rob & Carlos Coronel.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
7 7 SQL Data Definition 4Spread throughout chapter 7.
Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
5 Chapter 5 Structured Query Language (SQL2) Revision.
Introduction to Structured Query Language (SQL)
Structured Query Language (SQL)
1 Basic SQL Prof. Sin-Min Lee Department of Computer Science.
3 3 Chapter 3 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
5 Chapter 5 Structured Query Language (SQL1) Revision.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
S511 Session 10, IU-SLIS 1 Structured Query Language.
Introduction to SQL J.-S. Chou Assistant Professor.
ITEC 3220A Using and Designing Database Systems Instructor: Gordon Turpin Course Website: Office: CSEB3020.
Chapter 7 Introduction to Structured Query Language (SQL)
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
Database Technical Session By: Prof. Adarsh Patel.
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
6 1 Chapter 6 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Concepts of Database Management Seventh Edition
Database Systems: Design, Implementation, and Management Tenth Edition
Advanced SQL Advanced SQL Complex Queries, Joining Tables.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 7 Introduction to Structured Query Language (SQL)
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
3 3 Chapter 3 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Chapter 6 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Peter Rob & Carlos Coronel.
7 7 SQL Data Modification 4Spread throughout chapter 7.
1 Chapter 6 Structured Query Language (SQL) DATABASE MANAGEMENT SYSTEM.
SQL – Structured Query Language
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
IS 380 Introduction to SQL This lectures covers material from: database textbook chapter 3 Oracle chapter: 3,14,17.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
1 Chapter 1 File Systems and Databases Database Systems: Design, Implementation, and Management, Fifth Edition, Rob and Coronel l 工程資料庫專題 –NTUST/ME-2007Q4.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
Week 4 Lecture Part 2 of 3 Structured Query Language (SQL) Samuel ConnSamuel Conn, Faculty Suggestions for using the Lecture Slides.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Chapter 8 Advanced SQL. Relational Set Operators UNIONINTERSECTMINUS Work properly if relations are union- compatible –Names of relation attributes must.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL Query Getting to the data ……..
Advanced SQL Advanced SQL Week 8 Comparison Operators
ORACLE SQL Developer & SQLPLUS Statements
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Chapter 7 Introduction to Structured Query Language (SQL)
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Chapter # 7 Introduction to Structured Query Language (SQL) Part I.
Presentation transcript:

Chapter 5 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Peter Rob & Carlos Coronel

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

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

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

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.

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 )

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 )

PRODUCT VENDER CH5_TEXT

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

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;

A Data Dictionary for the CH5 Database Table 5.1

Some Common SQL Data Types NumericNUMBER(L,D) INTEGER SMALLINT DECIMAL(L,D) CharacterCHAR(L) VARCHAR(L) DateDATE Data TypeFormat

Data Definition Commands 4Creating Table Structures CREATE TABLE ( );

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

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

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

SQL Command Coverage Table 5.3

Data Entry and Saving 4Enters data into a table 4Saves changes to disk INSERT INTO VALUES (attribute 1 value, attribute 2 value, … etc.); COMMIT ;

Basic Data Management 4Data Entry INSERT INTO VALUES (attribute 1 value, attribute 2 value, … etc.); INSERT INTO VENDOR VALUES(‘21225, ’Bryson, Inc.’, ’Smithson’, ’615’,’ ’, ’TN’, ’Y’); INSERT INTO PRODUCT VALUES(‘11 QER/31’, ’Power painter, 15 psi., 3-nozzle’, ’07/02/1999’, 8.5, , 0.00, 25595);

Figure 5.3 A form-based Data View and Entry Screen

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

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 ;

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;

Figure 5.4 The Contents of the PRODUCT Table

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

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

Basic Data Management 4Deleting Table Rows DELETE FROM PRODUCT WHERE P_CODE = ‘2238/QPD’; DELETE FROM PRODUCT WHERE P_MIN = 5;

Queries 4Creating partial listings of table contents SELECT FROM WHERE ; Table 5.4 Mathematical Operators

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

Figure 5.6 The Microsoft Access QBE and Its SQL QBE (Query By Example) query generator

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

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344; Figure 5.7 Queries

SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE FROM PRODUCT WHERE P_PRICE <= 10; Figure 5.8 Queries

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

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

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

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 = OR V_CODE = 24288;

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

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE ‘07/15/1999’ ; Figure 5.14 Queries

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

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.

4Special Operators BETWEEN is used to define range limits. SELECT * FROM PRODUCT WHERE P_PRICE BETWEEN AND ; SELECT * FROM PRODUCT WHERE P_PRICE>50.00 AND P_PRICE< ; Queries

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

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

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

4EXISTS is used to check whether an attribute has value. DELETE FROM PRODUCT WHERE P_CODE EXISTS; SELECT * FROM PRODUCT WHERE V_CODE EXISTS;

Advanced Data Management Commands 4Changing Table Structures ALTER TABLE MODIFY ( ); ALTER TABLE ADD ( );

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

UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_CODE = ‘1546-QQ2’; Advanced Data Management Commands

UPDATE PRODUCT SET P_SALECODE = ‘1’ WHERE P_CODE IN (‘2232/QWE’, ‘2232/QTY’); Advanced Data Management Commands

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

Selected PRODUCT Table Attributes: Multiple Update Effect Advanced Data Management Commands

The Arithmetic Operators Λ

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

The Part Attributes Copied from the PRODUCT Table

4Deleting a Table from the Database u DROP TABLE ; DROP TABLE PART; Advanced Data Management Commands

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

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;

Selected PRODUCT Table Attributes Ordered by (Ascending) P_PRICE

The Partial Listing of the EMPLOYEE Table

4Cascading order sequence SELECT EMP_LNAME,EMP_FNAME,EMP_INITIAL,EMP_AREACODE,EMP_PHONE FROM EMPLOYEE ORDER BY EMP_LNAME, EMP_FNAME, EMP_INITIAL;

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;

4Listing Unique Values DISTINCT SELECT DISTINCT V_CODE FROM PRODUCT; More Complex Queries and SQL Functions

Some Basic SQL Aggregate Functions

Querying a Query: Nested Process 4COUNT DISTINCT SELECT COUNT(DISTINCT V_CODE) FROM PRODUCT; 6

COUNT Function Output Examples

MAX and MIN Function Output Examples

4MAX SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT WHERE P_PRICE = (SELECT MAX(P_PRICE) FROM PRODUCT);

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

AVG Function Output Examples

Determine whether goods that have been in inventory for a certain length of time should be placed on special sale.

4Grouping Data GROUP BY SELECT P_SALECODE, MIN(P_PRICE) FROM PRODUCT_2 GROUP BY P_SALECODE;

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;

Improper Use of the GROUP BY Clause ERROR

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;

An Application of the HAVING Clause

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

Creating a View

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

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

The Results of a JOIN

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

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.

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)

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

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.

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.

The Revised PRODUCT Table u If P_ONHAND( 庫存 ) <= P_MIN( 安全存量 ) set P_REORDER = “Yes”

The PRODUCT List Output in the Oracle RDBMS u in Oracle : P_REORDER = 1/0 for Yes/No

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;

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;

Creation of the Oracle Trigger for the PRODUCT Table

The PRODUCT Table’s P_REORDER Field is Updated by the Trigger UPDATE PRODUCT SET P_ONHAND = 4 WHERE P_CODE = ’11QER/31’;

The P_REORDER Value Mismatch UPDATE PRODUCT SET P_MIN = 7 WHERE P_CODE = ’2232/QWE’;

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

The Second Version of the PRODUCT_REORDER Trigger

UPDATE PRODUCT SET P_MIN = 10 WHERE P_CODE = ’23114-AA’;

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!

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

The Third Version of the Product Reorder Trigger

 After creating the new trigger, we can execute an UPDATE statement to fire it. UPDATE PRODUCT SET P_ONHAND = P_ONHAND

Execution of the Third Trigger Version

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.

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

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.

Creating and Invoking A Simple Stored Procedure

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;

Creation of the PROD_SALE Stored Procedure

Executing the PROD_SALE Stored Procedure

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;