0% found this document useful (0 votes)
11 views

376422_LEC08_AdvancedSQL

Uploaded by

Abc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

376422_LEC08_AdvancedSQL

Uploaded by

Abc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

Advanced Structured Query

Language (SQL)
Lecture 8

1
Learning Outcomes
 In this chapter, you will learn:
 How to use SQL for data administration (to drop
tables and create views)
 How to use SQL for data manipulation (to delete
and retrieve data)
 How to use SQL to query a database for useful
information
 How to use SQL functions to manipulate dates,
strings, and other data
 How to create and use updatable views
 How to create and use triggers and stored
procedure

2
3
Deleting a Table from the Database
 DROP
 Deletes table from database
 Syntax:
DROP TABLE tablename;
 Example:
DROP TABLE LINE;
 Can drop a table only if it is not the “one” side
of any relationship
 Otherwise, RDBMS generates an error message
 Foreign key integrity violation

4
Ordering a Listing
 ORDER BY clause is useful when listing order is
important
 Syntax:
SELECT columnlist
FROM tablelist
[WHERE conditionlist]
[ORDER BY columnlist [ASC | DESC]];
 Ascending order by default
 Example:
 SELECT P_CODE, P_DESCRIPT, P_INDATE, P_PRICE
FROM PRODUCT
ORDER BY P_PRICE;

5
Order Results in Ascending Order

6
Telephone List Query Results
SELECT EMP_LNAME, EMP_FNAME,
EMP_INITIAL, EMP_AREACODE, EMP_PHONE
FROM EMPLOYEE
ORDER BY EMP_LNAME, EMP_FNAME,
EMP_INITIAL;

7
A Query based on Multiple Restrictions
SELECT P_DESCRIPT, V_CODE, P_INDATE,
P_PRICE
FROM PRODUCT WHERE P_INDATE > ‘1999-08-
20’
AND P_PRICE <= 50.00 ORDER BY V_CODE,
P_INDATE, ASC;

8
Listing Unique Values
 DISTINCT clause produces list of only values
that are different from one another
 Example:
SELECT DISTINCT V_CODE
FROM PRODUCT;

9
Aggregate Functions
 COUNT – retrieve number of items
 Takes one parameter: usually a column name
 MAX and MIN find highest (lowest) value in a
table
 Compute MAX value in inner query
 Compare to each value returned by the query
 SUM computes total sum for any specified
attribute
 AVG function format is similar to MIN and MAX

10
Example Output of COUNT Function
SELECT COUNT (DISTINCT V_CODE) DISTINCT V_CODE
FROM PRODUCT; 6

SELECT COUNT (DISTINCT V_CODE)


DISTINCT V_CODE
FROM PRODUCT
WHERE P_PRICE <=10.00; 5

SELECT COUNT (*)


COUNT(*)
FROM PRODUCT
WHERE P_PRICE <=10.00; 3

11
Example Output of MAX and MIN
Functions
SELECT MAX(P_PRICE) MAX P_PRICE
FROM PRODUCT; 256.99

SELECT MIN(P_PRICE) MIN P_PRICE


FROM PRODUCT; 4.99

SELECT P_CODE, P_DESCRIPT, P_PRICE


FROM PRODUCT
WHERE P_PRICE = (SELECT
MAX(P_PRICE) FROM PRODUCT);

P_CODE P_DESCRIPT P_PRICE


Hi-cut chain saw,
09-WRE-Q 256.99
16 in.
12
Example of SUM and AVG Functions
 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;

13
Example Output of AVG Function

14
Grouping Data
 Frequency distributions created by GROUP BY
clause within SELECT statement
 Syntax:
SELECT columnlist
FROM tablelist
[WHERE conditionlist]
[GROUP BY columnlist]
[HAVING conditionlist]
[ORDER BY columnlist [ASC | DESC] ] ;

15
Incorrect and Correct Use of the GROUP BY
clause

16
Example output of GROUP BY clause
 GROUP BY
SELECT P_SALECODE, MIN(P_PRICE)
FROM PRODUCT
GROUP BY P_SALECODE;

17
An Application of the HAVING Clause

18
Nested Query
 Nested query: sub query or inner query in
another SQL query
 Must enclose with parentheses
 During comparison, you can only SELECT one
column
 No ORDER BY in subquery, but GROUP BY can
be used in sub query and it performs the
function like ORDER BY
 For e.g.:
 SELECT V_CODE, V_NAME, P_CODE,
P_DESCRIPT, P_PRICE FROM PRODUCT WHERE
 P_PRICE = (SELECT MAX(P_PRICE) FROM
19
PRODUCT);
Joining Database Tables
 Joining tables is the most important distinction
between relational database and other DBs
 Join is performed when data are retrieved
from more than one table at a time
 Equality comparison between foreign key and
primary key of related tables
 Join tables by listing tables in FROM clause of
SELECT statement
 DBMS creates Cartesian product of every table

20
Joining 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;

21
The Results of a JOIN

22
Joining Database Tables
 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 > ‘1999-08-15’;

23
Joining Tables with an Alias
 Alias identifies the source table from which
data are taken
 Alias can be used to identify source table
 Any legal table name can be used as alias
 Add alias after table name in FROM clause
 FROM tablename alias
 Example:
SELECT P_DESCRIPT, P_PRICE, V_NAME,
V_CONTACT, V_AREACODE, V_PHONE
FROM PRODUCT P, VENDOR V
WHERE P.V_CODE = V.V_CODE
ORDER BY P_PRICE;
24
Joining Tables with an Alias
 Alias is especially useful when a table must be
joined to itself
 Recursive query
 Use aliases to differentiate the table from itself
 Two types of outer join
 Left outer join
 Right outer join

25
When Writing SQL
 Know the purpose/output (and you will know
what SQL to use here)
 If relate to database and table structure: DDL
 If relate to manipulate and change the content of
tables: DML
 To add: INSERT
 To modify: UPDATE
 To display or list: SELECT
 To delete or remove: DELETE
 Identify the involve tables (ERD is extremely
useful)
 Identify the PK and FK that link the involve
tables
26
 Identify the condition
SQL – Serve the Purpose
 Purpose 1: List the number of invoice for each
customer in year 2018
 Output (something like this):
Customer Invoice
Jimmy Choo 5
Janet Clark 15
 Involve which tables? Invoice & Customer
 These tables are linked
 CUSTOMER.CUS_CODE = INVOICE.CUS_CODE
 What and how to retrieve?
 What to select: first name, last name and customer
code
 Number of invoice: COUNT(INV_NUMBER)
 Invoice for each customer: use GROUP BY, group the
27 invoice number according to customer.
SQL – Serve the Purpose (cont)
 The condition is year 2018, I can retrieve from
INV_DATE
 INV_DATE BETWEEN ‘2018-01-01’ and ‘2018-12-31’ or
 YEAR(INV_DATE) = 2018
 A complete SQL:
 SELECT c.CUS_CODE, CUS_LNAME, CUS_FNAME,
COUNT(INV_NUMBER) AS ‘Total_Invoice’ FROM
CUSTOMER as C, INVOICE as inv WHERE
 c.CUS_CODE = inv.CUS_CODE AND
 INV_DATE BETWEEN ‘2018-01-01’ and ‘2018-12-
31’
 GROUP BY c.CUS_CODE, CUS_LNAME, CUS_FNAME;

28
SQL – Serve the Purpose (cont)
 To make the display result better, sorting is
one of the good option:
 SELECT c.CUS_CODE, CUS_LNAME, CUS_FNAME,
COUNT(INV_NUMBER) FROM CUSTOMER as C,
INVOICE as inv WHERE
 c.CUS_CODE = inv.CUS_CODE AND
 INV_DATE BETWEEN ‘2018-01-01’ and ‘2018-12-
31’
 GROUP BY c.CUS_CODE, CUS_LNAME, CUS_FNAME
 ORDER BY CUS_FNAME;

29
SQL – Serve the Purpose (cont)
 In case someone just want to see result with
invoice number more than 2:
 SELECT c.CUS_CODE, CUS_LNAME, CUS_FNAME,
COUNT(INV_NUMBER) FROM CUSTOMER as C,
INVOICE as inv WHERE
 c.CUS_CODE = inv.CUS_CODE AND
 INV_DATE BETWEEN ‘2018-01-01’ and ‘2018-12-
31’
 GROUP BY c.CUS_CODE, CUS_LNAME, CUS_FNAME
 HAVING COUNT(INV_NUMBER) > 2
 ORDER BY CUS_FNAME;

30
SQL – Serve the Purpose (cont)
 Purpose 2: List the total sold out quantity of
each product in June 2019.
 Sample output
Product Quantity
B&D jigsaw, 12- 3
in, blade
Claw hammer 35

 Involve tables: LINE, PRODUCT (as P), INVOICE (as


INV)
 LINE.P_CODE = P.P_CODE
 INV.INV_NUMBER=LINE.INV_NUMBER

31
SQL – Serve the Purpose (cont)
 What and how to retrieve
 List: SELECT P_CODE, P_DESCRIPT, SUM(LINE_UNITS)
 Total sold out quantity: SUM(LINE_UNITS)
 By product: GROUP BY P_DESCRIPT
 June 2019: (INV_DATE BETWEEN ‘2019-06-01’ AND
‘2019-06-30’) or (MONTH(INV_DATE)= 6 AND
YEAR(INV_DATE)=2019)
 A complete SQL
 SELECT P_CODE, P_DESCRIPT, SUM(LINE_UNITS)
 FROM LINE, PRODUCT as P, INVOICE as INV
 WHERE LINE.P_CODE = P.P_CODE AND
 INV.INV_NUMBER=LINE.INV_NUMBER AND
 MONTH(INV_DATE)= 6 AND YEAR(INV_DATE) =
32 2019
SQL – Serve the Purpose (cont)
 Modify purpose 2: List the total sold out
quantity of each product by month from
January to June 2019.
Month Product Quantity
 Sample output
January B&D jigsaw, 12- 3
in, blade
February Claw hammer 35

 Complete SQL
 SELECT MONTHNAME(INV_DATE), P_CODE, P_DESCRIPT,
SUM(LINE_UNITS)
 FROM LINE, PRODUCT as P, INVOICE as INV
 WHERE LINE.P_CODE = P.P_CODE AND
 INV.INV_NUMBER=LINE.INV_NUMBER AND
 INV_DATE BETWEEN ‘2019-01-01’ AND ‘2019-06-30’
33
 GROUP BY P_DESCRIPT, MONTHNAME(INV_DATE);
Virtual Tables: Creating a View
 View is virtual table based on SELECT query
 Create view by using CREATE VIEW command
 Special characteristics of relational view:
 Name of view can be used anywhere a table name
is expected
 View dynamically updated
 Restricts users to only specified columns and rows
 Views may be used as basis for reports

34
Creating a View

35
Procedural SQL
 SQL shortcomings
 Doesn’t support execution of stored procedures based
on logical condition
 Fails to support looping operations
 Solutions
 Procedural SQL (PL/SQL) stored within the database,
executed by DBMS, and invoked by the end user

36
Procedural SQL (con’t.)
 Procedural SQL allows the use of procedural
code and SQL statements that are stored
within the database.
 The procedural code is executed by the
DBMS when it is invoked by the end user.
 End users can use procedural SQL (PL/SQL)
to create:
 Triggers
 Stored procedures
 PL/SQL functions
37
Triggers
 Procedural SQL code invoked before or
after data row is deleted, inserted, or
updated
 Associated within the table
 Table may have multiple triggers
 Can update values, insert records, and call
procedures
 Add processing power

38
Triggers (con’t.)
 DB2 example

CREATE TRIGGER <trigger_name>


[NO CASCADE BEFORE/AFTER]
[DELETE/INSERT/UPDATE OF <column_name>]
ON <table_name>
[FOR EACH ROW MODE DB2SQL]
BEGIN
PL/SQL instructions;

……………
END;

39
Example of Trigger

Figure: Product table


40
Example of Trigger (con’t)
CREATE TRIGGER TRG_PRODUCT_REORDER
AFTER UPDATE OF p_onhand, p_min ON product
FOR EACH ROW MODE DB2SQL
UPDATE product SET p_reorder =1
WHERE (p_onhand <= p_min);

41
Another trigger example (con’t)

42
Another trigger example (con’t)
 One small database has three tables which are PRODUCT, ORDER
and ORDERCONTENT
 The following trigger will sum up and update the TotalAmount for
that particular order when a new product is added to the order in the
ORDERCONTENT table

CREATE TRIGGER SumTotal


AFTER INSERT ON ORDERCONTENT
REFERENCING NEW AS N
FOR EACH ROW MODE DB2SQL
BEGIN ATOMIC
UPDATE ORDER SET TotalAmount =
(SELECT SUM(UnitPrice * Quantity)
FROM ORDERCONTENT, PRODUCT
WHERE PRODUCT.ProdNum = ORDERCONTEN.ProdNum AND
ORDERCONTENT.OrderNum = N.OrderNum)
WHERE OrderNum = N.OrderNum;
END
• Use BEGIN ATOMIC … END when trigger contains multiple SQL
43
statements
Example of MySQL Trigger
CREATE TRIGGER InventoryUpdate
AFTER INSERT ON invoice
FOR EACH ROW
AFTER/BEFORE INSERT/UPDATE/DELETE : this
BEGIN command is to tell the system when trigger
UPDATE inventory should run

SET qty = qty – new.prod_qty


WHERE p_id = (SELECT prod_id FROM invoice
WHERE inv_no = new.inv_no AND prod_id =
Actions that
new.prod_id);
trigger must
END perform when it
is called.

44
Restriction of Triggers (MySQL)
 BEFORE UPDATE/INSERT/DELETE
 Can update the NEW values
 Cannot update the OLD values
 AFTER UPDATE/INSERT/DELETE
 Cannot create AFTER UPDATE/INSERT/DELETE on the VIEW
 Can access the NEW and OLD values
 Cannot update the NEW and OLD values
 For INSERT trigger, only NEW.col_name can be used
 For DELETE trigger, only OLD.col_name can be used
 For UPDATE trigger, OLD.col_name refer to the
columns of a row before it is updated; NEW.col_name
refers to the columns of the row after it is update

45
Stored Procedures
 Named collection of procedural and SQL
statements stored in database
 For multiple-update transaction
 Executed as unit
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;

 Invoked with EXEC


EXEC store_procedure_name (parameter1, parameter2, …)
46
Stored Procedures
 Advantages
 Substantially reduce network traffic and increase
performance
 No transmission of individual SQL statements over
network
 Improve system performance as all transactions are
executed locally on the RDBMS
 Help reduce code duplication by means of code
isolation and code sharing
 Minimize cost of application development and
maintenance

47
Example Of DB2 Store Procedure
CREATE PROCEDURE UPDATE_SALARY_IF
(IN employee_number CHAR(6), IN rating SMALLINT)
LANGUAGE SQL
BEGIN
DECLARE not_found CONDITION FOR SQLSTATE '20000';
DECLARE EXIT HANDLER FOR not_found
SIGNAL SQLSTATE '20000' ('Employee not found‘);

IF (rating = 1)
THEN UPDATE employee
SET salary = salary * 1.10, bonus = 1000
WHERE empno = employee_number;
ELSEIF (rating = 2)
THEN UPDATE employee
SET salary = salary * 1.05, bonus = 500
WHERE empno = employee_number;
ELSE UPDATE employee
SET salary = salary * 1.03, bonus = 0
WHERE empno = employee_number;
END IF;
END
48
Example Of MySQL Store Procedure
CREATE PROCEDURE inventoryupdate(IN pno INT (4), IN Q
INT)
BEGIN
UPDATE inventory
SET qty = qty + Q;
WHERE p_id = pno;
END;

49
PL/SQL Functions
 Scalar functions operate on a single value to
return another single value.
 For example:
 ABS(-10) returns the absolute value of –10, i.e.
10
 LENGTH(‘Shirley’) returns the number of bytes in
the string, i.e., 7
 YEAR(’03/20/2008’) extracts the year portion,
i.e., 2008
 UCASE(‘shirley’) or UPPER(‘shirley’) returns a
string which have been converted to uppercase,
i.e., SHIRLEY
50
PL/SQL Functions
 User-defined function: Named group of
procedural and SQL statements that
returns a value
CREATE FUNCTION function_name (argument IN
data-type, etc)
RETURN data-type
AS BEGIN
PL/SQL statements;
RETURN (value); ……
END;

 Invoked from within stored procedures or


triggers or simply issue SELECT command
51
Example of DB2 Functions
CREATE FUNCTION job_designation (job varchar(15))
RETURN TABLE (
empID int,
empFName varchar(20),
empLName varchar(20)
)
LANGUAGE SQL
READS SQL DATA
NO EXTERNAL ACTION
DETERMINISTRIC
RETURN
SELECT emp_no, firstname, lastname
FROM employee
WHERE employee.job = job_designation.job;

To query the new table function, simply issue:


SELECT * from TABLE(job_designation(‘MANAGER’)) AS
Manager;
52
Example of MySQL Functions
Function
name
CREATE FUNCTION totalPaidByCust(custID INT)
State returns DECIMAL (5,2)
Data type
return BEGIN parameter
value DECLARE totalSales DECIMAL (5,2);
type SELECT SUM (payment.amount) INTO totalSales
FROM Payment
Body WHERE Payment.customerID = custID;
RETURN totalSales;
END;

To query the new table function, simply issue:


SELECT totalPaidByCust(3);
53
Other
 Advanced Command (MySQL)
IF/ELSE
IF condition THEN
statements
ELSEIF condition THEN
statements
ELSE
statements;
END IF;

54
Other advanced command (con’t)
DELIMITER //
 Example:
CREATE FUNCTION IncomeLevel ( monthly_value INT )
RETURNS varchar(20)

BEGIN

DECLARE income_level varchar(20);

IF monthly_value <= 4000 THEN


SET income_level = 'Low Income';

ELSEIF monthly_value > 4000 AND monthly_value <=


7000 THEN
SET income_level = 'Avg Income';

ELSE
SET income_level = 'High Income';

END IF;
RETURN income_level;

END; //

55 DELIMITER ;
Other advanced command (con’t)
Case
CASE case_expression
WHEN condition_1 THEN statements
WHEN condition_2 THEN statements
...
ELSE statements
END CASE;

56
Other advanced command (con’t)
 Example CREATE FUNCTION IncomeLevel ( monthly_value
INT )
RETURNS varchar(20)

BEGIN

DECLARE income_level varchar(20);

CASE monthly_value
WHEN 4000 THEN
SET income_level = 'Low Income';

WHEN 5000 THEN


SET income_level = 'Avg Income';

ELSE
SET income_level = 'High Income';
END CASE;

RETURN income_level;

END; //

57 DELIMITER ;
Other
 Loop advanced command (con’t)

WHILE expression DO
statements
END WHILE

58
Other advanced command (con’t)
DELIMITER //
 Example:
DELIMITER $$
DROP PROCEDURE IF EXISTS test_mysql_while_loop$$
CREATE PROCEDURE test_mysql_while_loop()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1;
SET str = '';

WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;

SELECT str;
END$$
DELIMITER ;

59
Embedded SQL
 Key differences between SQL and
procedural languages:
 Run-time mismatch
 SQL is executed one instruction at a time
 Host language typically runs at client side in its
own memory space
 Processing mismatch
 Host language processes one data element at a time
 Data type mismatch

60
Embedded SQL (cont’d.)
 Embedded SQL framework defines:
 Standard syntax to identify embedded SQL code
within host language
 Standard syntax to identify host variables
 Communication area exchanges status and error
information between SQL and host language

61
62
Embedded SQL (cont’d.)
Static SQL Dynamic SQL
• Embedded SQL in which • SQL statement is not
programmer uses known in advance, but
predefined SQL instead is generated at run
statements and time
parameters • Program can generate SQL
End users of programs statements at run time that
are limited to actions are required to respond to
that were specified in ad hoc queries
application programs • Attribute list and condition
• SQL statements will not are not known until end
change while application is user specifies them
running • Tends to be much slower
than static SQL
• Requires more computer
resources
63
Example of Dynamic SQL

Figure source: https://www.guru99.com/dynamic-sql-pl-sql.html

64

You might also like