Sie sind auf Seite 1von 47

Advanced Structured Query

Language (SQL)
Lecture 7
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

Deleting a Table from the Database

DROP

Deletes table from database


Syntax:
DROP TABLE tablename;

Example:
DROP TABLE VENDOR;

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

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;

Order Results in Ascending Order

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;

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;

Listing Unique Values

DISTINCT clause produces list of only values


that are different from one another
Example:
SELECT DISTINCT V_CODE
FROM PRODUCT;

Aggregate Functions

COUNT function tallies number of non-null


values of an attribute

MAX and MIN find highest (lowest) value in a


table

Takes one parameter: usually a column name

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

Example Output of COUNT Function


SELECT COUNT (DISTINCT V_CODE)
FROM PRODUCT;

SELECT COUNT (DISTINCT V_CODE)


FROM PRODUCT
WHERE P_PRICE <=10.00;

SELECT COUNT (*)


FROM PRODUCT
WHERE P_PRICE <=10.00;

10

DISTINCT V_CODE

DISTINCT V_CODE

COUNT(*)
3

Example Output of MAX and MIN


Functions
MAX P_PRICE

SELECT MAX(P_PRICE)
FROM PRODUCT;

256.99

MIN P_PRICE

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

11

P_CODE

P_DESCRIPT

P_PRICE

09-WRE-Q

Hi-cut chain saw,


16 in.

256.99

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;

12

Example Output of AVG Function

13

Grouping Data

Frequency distributions created by GROUP BY


clause within SELECT statement
Syntax:
SELECT
FROM
[WHERE
[GROUP BY
[HAVING
[ORDER BY

14

columnlist
tablelist
conditionlist]
columnlist]
conditionlist]
columnlist [ASC | DESC] ] ;

Incorrect and Correct Use of the GROUP BY


clause

15

Example output of GROUP BY clause

GROUP BY
SELECT P_SALECODE, MIN(P_PRICE)
FROM PRODUCT
GROUP BY P_SALECODE;

16

An Application of the HAVING Clause

17

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:

18

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

Creating a View

19

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

20

DBMS creates Cartesian product of every table

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

25

Left outer join


Right outer join

Procedural SQL

Shortcomings of SQL

SQL doesnt support execution of a stored set of procedures


based on some logical condition.
SQL fails to support the looping operations.

Solutions

Embedded SQL

Shared Code

26

To remedy the above shortcomings, SQL statements can be


inserted within the procedural programming language
The embedded SQL approach involves the duplication of
application code in many programs.
Critical code is isolated and shared by all application programs.
This approach allows better maintenance and logic control.

Procedural SQL

Procedural SQL (contd.)

Procedural SQL (PL/SQL) enables you to:

Store procedural code and SQL statements in


database
Merge SQL and traditional programming
constructs

Procedural code executed by DBMS when


invoked by end user

27

Anonymous PL/SQL blocks and triggers


Stored procedures and PL/SQL functions

Triggers

Procedural SQL code automatically invoked by


RDBMS on data manipulation event
Trigger definition:

Triggering timing: BEFORE or AFTER


Triggering event: INSERT, UPDATE, DELETE
Triggering level:

Statement-level trigger
Row-level trigger

Triggering action

DROP TRIGGER trigger_name

28

Trigger - Insert Trigger


A
B

Table A

C+1
D+1

Table B

After data is inserted to Table A then


do something to Table B

29

Trigger

Role of triggers

30

Triggers can be used to enforce constraints that


cannot be enforced at the design and
implementation levels.
Triggers add functionality by automating critical
actions and providing appropriate warnings and
suggestions for remedial action.
Triggers can be used to update table values, insert
records in tables, and call other stored procedures.
Triggers add processing power to the RDBMS and
to the database system.

The PRODUCT List Output

31

Trigger Example

Syntax to create a trigger in IBM DB2


create trigger <TriggerName> <After
Insert/After Update> on product
for each row mode db2sql
UPDATE <TableName>
set <Conditions>

32

Creating Trigger for PRODUCT Table in


Oracle

33

P_REORDER is Updated by the Trigger

34

The P_REORDER Value Mismatch after


update of the P_MIN value

35

The Second Version of the Trigger

36

Successful trigger execution after the


P_MIN value is updated

37

The P_REORDER Mismatch after


Increasing the P_QOH Value

38

The 3rd Version of the Trigger

39

Execution of the Trigger (3rd Version)

40

Stored Procedures

Named collection of procedural and SQL


statements
Advantages

Substantially reduce network traffic and increase


performance

No transmission of individual SQL statements over


network

Reduce code duplication by means of code


isolation and code sharing

Stored
C+ 1 of application
Minimize chanceAof errors
and cost
Procedure
B
D+ 1
development and maintenance

Table A

Table B

You can manipulate the whole set of records (changing, adding, updating,
deleting) using stored procedure

41

Stored Procedure (SP)

Syntax 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;
DECLARE specifies the variables used within the procedure.
Argument specifies the parameters that are passed to the SP.
IN / OUT indicates whether the parameter is for INPUT or
OUTPUT or both.
Data-type is one of the procedural SQL data types used in the
RDBMS.

Syntax to invoke a stored procedure

42

EXEC store_procedure_name (parameter, parameter, )

PL/SQL Stored Functions

Named group of procedural and SQL


statements that returns a value
Syntax:
CREATE FUNCTION function_name
(argument
IN data-type, ) RETURN data- type [IS]
BEGIN
PL/SQL statements;

RETURN (value or expression);


END;

43

Embedded SQL

Key differences between SQL and


procedural languages:

Run-time mismatch

Processing mismatch

44

SQL is executed one instruction at a time


Host language typically runs at client side in its
own memory space
Host language processes one data element at a time

Data type mismatch

Embedded SQL (contd.)

Embedded SQL framework defines:

45

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

46

Embedded SQL (contd.)


Static SQL

Embedded SQL in which


programmer uses
predefined SQL
statements and
parameters
End users of programs
are limited to actions
that were specified in
application programs
SQL statements will not
change while application is
running

47

Dynamic SQL

SQL statement is not


known in advance, but
instead is generated at run
time
Program can generate SQL
statements at run time that
are required to respond to
ad hoc queries
Attribute list and condition
are not known until end
user specifies them
Tends to be much slower
than static SQL
Requires more computer
resources

Das könnte Ihnen auch gefallen