You are on page 1of 22

Structured Query Language (SQL) fall 2006

Structured Query Language (SQL)


Advanced SQL
Learning objectives:
1. Understand the basic SQL definitions and Concepts
2. Use basic commands and functions of SQL
3. About relational set operators UNION, UNION ALL, INTERSECT, and
MINUS
4. How to use the advanced SQL JOIN operator syntax
5. Write multiple table SQL queries
6. About the different types of subqueries and correlated queries
7. How to use SQL functions to manipulate dates, strings, and other data
8. How to create and use updatable views
9. Understand triggers and stored procedures
10. How to create embedded SQL

1. Basic SQL Concepts and Definitions:


1.1 SQL Environment
 Catalog: A set of schemas that constitute the description of a
database
 Schema: The structure that contains descriptions of objects created
by a user (database tables, views, constraints)
 Data Definition Language (DDL): Commands that define a database,
including creating, altering, and dropping tables and establishing
constraints
 Data Manipulation Language (DML): Commands that maintain and
query a database
 Data Control Language (DCL): Commands that control a database,
including administering privileges and committing data.

Purpose Development
process
Data Definition  Define the Database Database
Language (DDL)  CREATE Tables, indexes, Views Physical Design
 Establish Foreign Keys Database
 DROP or Truncate tables Maintenance
Data Manipulation  Maintain the data: Database
Language (DML)  INSERT Data Implementation

1
Structured Query Language (SQL) fall 2006

 UPDATE the database


 Manipulate the database
(SELECT)
Data Control  Controls the database: Database
Language (DCL)  GRANT Implementation
 ADD Database
 REVOKE Maintenance

1.2 ISO SQL Data types:

Data Type Declaration Format


Boolean BOOLEAN
Character CHAR(L) VARCHAR(L)
Numeric NUMBER(L,D) DECIMAL(L.D)
INTEGER SMALLINT
Date/Time DATE
TIME TIMESTAMP
Interval INTERVAL
Large Objects CHARACTER LARGE BINARY LARGE
OBJECT OBJECT

1.3 Data Definition Language (DDL)


1.3.1 CREATE statements:
 CREATE SCHEMA – defines a portion of the database owned by a
particular user
 CREATE TABLE – defines a table and its columns
 CREATE VIEW – defines a logical table from one or more views
 Other CREATE statements: COLLATION, ASSERTION, DOMAIN
a) Creating indexes:
CREATE INDEX NAME_IDX ON CUSTOMER (CUSTOMER_NAME)
This makes an index for the CUSTOMER_NAME field of the CUSTOMER
table
b) Creating Table Structures:
 Use one line per column (attribute) definition
 Use spaces to line up the attribute characteristics and constraints
 Table and attribute names are capitalized
 Table Creation format:

2
Structured Query Language (SQL) fall 2006

CREATE TABLE tableName


{( columnName dataType [NOT NULL] [UNIQUE]

[DEFAULT defaultOption] [CHECK (searchContition)] [, . . .]}


[Primary Key (listOfColumns),]
{[UNIQUE (listOfColumns) [, . . .]}
{[FOREIGN KEY (listOfForeignKeyColumns)]
REFERENCES parentTableName [(listOfCandidateKeyColumns)]
[MATCH {PARTIAL | FULL }
[ON UPDATE referencialAction]
[ON DELETE referencialAction]] [, . . .]}
{[CHECK (searchContition)] [, . . .]})

Examples:
create table customer
(customer-ID number(6.0) NOT NULL,
customer-name char(20) NOT NULL ,
customer-street char(30),
customer-city char(30),
constraint primary key (customer-ID))
create table branch
(branch-name char(15) NOT NULL,
branch-city char(30),
assets integer,
constraint primary key (branch-name))
create table account
(account-number integer (10) NOT NULL,
branch-name char(15) check (branch-name IN (‘A’, ‘B’, ‘C’)),
date-opened date default sysdate,
balance decimal(8.2),
constraint primary key (account-number),
constraint foreign key (branch-name) references branch)
create table depositor
(customer-name char(20) NOT NULL,
account-number char(10),
constraint primary key (customer-name, account-number),
constraint foreign key (account-number) references account,

3
Structured Query Language (SQL) fall 2006

constraint foreign key (customer-name) references customer)

1.3.2 SQL Integrity Constraints:


a) Data Integrity Constraints:
 NOT NULL constraint: Ensures that a column does not accept nulls
 UNIQUE constraint : Ensures that all values in a column are unique
 DEFAULT constraint : Assigns a value to an attribute when a new row is
added to a table
 CHECK constraint: Validates data when an attribute value is entered
 SQL Indexes : When a primary key is declared, DBMS automatically
creates a unique index
 Using the CREATE INDEX command, SQL indexes can be created on the
basis of any selected attribute
 Composite index: Index based on two or more attributes. Often used to
prevent data duplication
b) Referential integrity:
 constraint that ensures that foreign key values of a table must match
primary key values of a related table in 1:M relationships
 Primary and foreign keys can be specified as parts of the SQL create
table statement:
 The primary key clause lists attributes that comprise the primary
key.
 The unique key clause lists attributes that comprise a candidate key.
 The foreign key clause lists the attributes that comprise the foreign
key and the name of the relation referenced by the foreign key.
 By default, a foreign key references the primary key attributes of the
referenced table
foreign key (account-number) references account
 Short form for specifying a single column as foreign key
account-number char (10) references account
 Restricting:
 Deletes of primary records
 Updates of primary records
 Inserts of dependent records
ON UPDATE RESTRICT A customer can only be deleted if it is not
found in ORDER table.
ON UPDATE CASCADE Changing a customerID in CUSTOMER table will
result in that value changing in the ORDER table

4
Structured Query Language (SQL) fall 2006

to match.
ON UPDATE SET NULL When a customerID is changed in the
CUSTOMER table, any customerID in the
ORDER table that matches the old customerID
is set to NULL
ON UPDATE SET When a customerID is changed in the
DEFAULT CUSTOMER table, any customerID in the
ORDER table that matches the old customerID
is set to predefined default value

c) ASSERTIONS:
 An assertion is a general condition that we wish the database always to
satisfy.
 The syntax for creating assertion is:
CREATE ASSERTION assertionName
CHECK (searchCondition)
 Domain constraints and referential integrity constraints are special cases
of assertions.
 Example of assertions: the sum of all customer invoices must be less than
or equal to the credit limits assigned to that customer.
 When an assertion is made, the system tests it for validity, and tests it
again on every update that may violate the assertion.
Assertion example 1: The sum of all loan amounts for each branch must be
less than the sum of all account balances at the branch.
create assertion sum-constraint check
(not exists (select * from branch
where (select sum(amount) from loan
where loan.branch-name = branch.branch-name)
>= (select sum(amount) from account
where loan.branch-name = branch.branch-name)))
Assertion example 2:
Every loan has at least one borrower who maintains an account with a
minimum balance or $1000.00
create assertion balance-constraint check
(not exists (select * from loan
where not exists ( select *
from borrower, depositor, account
where loan.loan-number = borrower.loan-number

5
Structured Query Language (SQL) fall 2006

and borrower.customer-name = depositor.customer-name


and depositor.account-number = account.account-number
and account.balance >= 1000)))

1.3.3 Changing and Removing Tables


 ALTER TABLE statement allows you to change column specifications:
ALTER TABLE CUSTOMER_T ADD (TYPE VARCHAR(2))
 DROP TABLE statement allows you to remove tables from your
schema:
DROP TABLE CUSTOMER_T

1.4 Data Manipulation Commands:


Command Description
INSERT Adding table rows, one row at a time
INSERT with Inserting table rows with a select subquery
Subquery
SELECT Listing table content
UPDATE Changing the columns values in one or more table rows
DELETE Deleting table rows
COMMITT Permanently save any changes made to any table in the
database
ROLLBACK Restore the database to its previous condition

1.4.1 Insert Statement


Adds data to a table
a) Inserting into a table:
INSERT INTO CUSTOMER VALUES (001, ‘Contemporary Casuals’,
‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);

b)Inserting a record that has some null attributes requires identifying the
fields that actually get data:
INSERT INTO PRODUCT (PRODUCT_ID, PRODUCT_DESCRIPTION,
PRODUCT_FINISH, STANDARD_PRICE, PRODUCT_ON_HAND)
VALUES (1, ‘End Table’, ‘Cherry’, 175, 8);

c) Inserting from another table (with SELECT subquery):

6
Structured Query Language (SQL) fall 2006

 Inserts multiple rows from another table (source)


 The embedded (or nested) query is executed first
 The command format:
INSERT INTO tablename SELECT columnlist FROM tablename
Example:
INSERT INTO CA_CUSTOMER SELECT * FROM CUSTOMER WHERE
STATE = ‘CA’;

1.4.2 Delete Statement:


 Deletes row or rows from a table
 Syntax:
DELETE FROM tablename
[WHERE conditionlist ];
 WHERE condition is optional
 If WHERE condition is not specified, all rows from the specified
table will be deleted
 Example:
DELETE FROM CUSTOMER
WHERE STATE = ‘HI’;
DELETE FROM CUSTOMER;

1.4.3 Update Statement


 Modifies data in existing rows
 Syntax:
UPDATE tablename
SET columnname = expression [, columname = expression]
[WHERE conditionlist];
 If more than one attribute is to be updated in the row, separate
corrections with commas
 Example:
UPDATE PRODUCT
SET UNIT_PRICE = 775
WHERE PRODUCT_ID = 7;

1.4.4 SELECT Statement:


 Used for retrieving information from single or multiple tables
 Selecting Rows by Adding conditional restrictions to the SELECT
statement, using WHERE clause

7
Structured Query Language (SQL) fall 2006

 Syntax:
SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;
 Clauses of the SELECT statement:
Clause Descriptions
SELECT List the columns (and expressions) that should be returned
from the query

FROM Indicate the table(s) or view(s) from which data will be


obtained
WHERE Indicate the conditions under which a row will be included in
the result
GROUP BY Indicate categorization of results
HAVING Indicate the conditions under which a category (group) will be
included
ORDER BY Sorts the result according to specified criteria

Rows Selection in WHERE clause is based on the following conditions:


 Comparison: using operators such as <, >, >=, <=, <>
 Range - WHERE salary BETWEEN 1000 AND 2000
 Set membership - WHERE department IN (‘MIS’, ‘BA’) AND 2000IN
 Pattern Search - WHERE address LIKE ‘%Amman%’
 Null – WHERE phone IS NULL
 Also we can define complex conditions using logical operators like
AND, OR, and NOT
SELECT Examples:
 Find products with standard price less than $275:
SELECT PRODUCT_NAME, STANDARD_PRICE
FROM PRODUCT
WHERE STANDARD_PRICE < 275;

 SELECT Example Using Alias


SELECT CUSTOMER_NAME AS NAME, CUSTOMER_ADDRESS
FROM CUSTOMER CUST
WHERE NAME = ‘Home Furnishings’;

8
Structured Query Language (SQL) fall 2006

1.4.5. SQL Queries with Aggregate Functions


 SQL provides useful functions like COUNT(), MAX(), MIN(), and
AVG()
 SQL allows the user to limit queries to only those entries having no
duplicates or entries whose duplicates may be grouped.
 SELECT Example Using the COUNT aggregate function :
SELECT COUNT(*) FROM ORDER_LINE
WHERE ORDER_ID = 1004;
 SELECT Example using Boolean Operators (AND, OR, and NOT
Operators) for customizing conditions in WHERE clause:
SELECT PRODUCT_DESCRIPTION, PRODUCT_FINISH, STANDARD_PRICE
FROM PRODUCT
WHERE (PRODUCT_DESCRIPTION LIKE ‘%Desk’
OR
PRODUCT_DESCRIPTION LIKE ‘%Table’)
AND
UNIT_PRICE > 300;
 SELECT Example – Sort the results first by STATE, and within a state by
CUSTOMER_NAME
SELECT CUSTOMER_NAME, CITY, STATE
FROM CUSTOMER
WHERE STATE IN (‘FL’, ‘TX’, ‘CA’, ‘HI’)
ORDER BY STATE, CUSTOMER_NAME;

 SELECT Example – Categorizing Results Using the GROUP BY Clause:


 For use with aggregate functions:
 Scalar aggregate: single value returned from SQL query with
aggregate function
 Vector aggregate: multiple values returned from SQL query with aggregate
function (via GROUP BY)
SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE)
FROM CUSTOMER
GROUP BY CUSTOMER_STATE;

 SELECT Example – Qualifying Results by Categories Using the HAVING


Clause
 For use with GROUP BY
SELECT CUSTOMER_STATE, COUNT(CUSTOMER_STATE)

9
Structured Query Language (SQL) fall 2006

FROM CUSTOMER
GROUP BY CUSTOMER_STATE
HAVING COUNT(CUSTOMER_STATE) > 1;

1.5 Security Specification in SQL


 The grant statement is used to confer authorization. This statement
defined as follows:
grant <privilege list>
on <relation name or view name>
to <user / role list>
[with grant option]
where <user list> is:
 a user-id
 public, which allows all valid users the privilege granted
 A role ( see 7.2)
 [with grant option] allows a specified user to grant this privilege to
others users
 Granting a privilege on a view does not imply granting any privileges on the
underlying relations.
 The grantor of the privilege must already hold the privilege on the
specified item (or be the database administrator).

1.5.1 Privileges in SQL


 select: allows read access to relation, or the ability to query using the
view. Example: to grant users U1, U2, and U3 select authorization on the
branch relation, we can write:
grant select on branch to U1, U2, U3
 insert: the ability to insert tuples
 update: the ability to update using the SQL update statement
 delete: the ability to delete tuples.
 references: ability to declare foreign keys when creating relations.
 usage: authorizes a user to use a specified domain ( SQL-92;)
 all privileges: used as a short form for all the allowable privileges
1.5.2 Roles
 Roles permit specifying common privileges for a class of users.
 Privileges can be granted to or revoked from roles, just like user.
 Roles can be assigned to users, and even to other roles.
 SQL:1999 supports roles. For example:

10
Structured Query Language (SQL) fall 2006

create role teller


create role manager

grant select on branch to teller


grant update (balance) on account to teller
grant all privileges on account to manager
grant manager to ahmad
grant teller to sawsan, layla

1.5.3 Revoking Authorization in SQL


 The revoke statement is used to revoke authorization. The statement format is:
revoke<privilege list> on <relation name or view name>
from <user list> [restrict | cascade]
Example, the following statement:
Revoke select on branch from U1, U2, U3 cascade
 Causes revocation of a select privilege from the U1, U2 and U3 and may
cause other users also to lose that privilege.
 We can prevent cascading by specifying restrict:
revoke select on branch from U1, U2, U3 restrict
With restrict, the revoke command fails if cascading revokes are
required.
 All privileges that depend on the privilege being revoked are also revoked.

2. Complex Queries:
We can use the sets operations to combine the results of two or
more queries into a single result query (complex Query).
2.1 Relational sets operations:
2.1.1 UNION operation:
 The UNION of two query results, A and B, is a table containing all rows
that are in the first query result A or the second query result B or
both
 Combines rows from two or more queries without including duplicate
rows.
 The output (union of multiple queries) together into a single result
table

11
Structured Query Language (SQL) fall 2006

 Query result A and Query result B should be union compatible, this


means the names of the attributes must be the same and their data
types must be identical.

Example:
Combined Query Result
(SELECT city (SELECT city
FROM branch FROM branch
WHERE city IS NOT NULL) WHERE city IS NOT NULL)
UNION UNION CORRESPONDING BY city
(SELECT city (SELECT city
FROM propertyForRent FROM propertyForRent
WHERE city IS NOT NULL) WHERE city IS NOT NULL)
 If ALL is specified, the result can include duplicate rows.

2.1.2 INTERSECT Operation


The intersection of two tables, A and B, is a table containing all rows
that are common to both A and B tables.
Example:
Combined Query Result
(SELECT city (SELECT city
FROM branch FROM branch
WHERE city IS NOT NULL) WHERE city IS NOT NULL)
INTERSECT INTERSECT CORRESPONDING BY
(SELECT city city
FROM propertyForRent (SELECT city
WHERE city IS NOT NULL) FROM propertyForRent
WHERE city IS NOT NULL)

2.1.3 The DIFFERENCE operation:


 Combines two queries and returns only the rows that appear in the first
query but not appear in the second.
 The queries must be UNION compatible
 Example:
Combined Query Result
(SELECT city (SELECT city
FROM propertyForRent FROM branch
WHERE city IS NOT NULL) WHERE city IS NOT NULL)
MINUS INTERSECT CORRESPONDING BY
(SELECT city city

12
Structured Query Language (SQL) fall 2006

FROM branch (SELECT city


WHERE city IS NOT NULL) FROM propertyForRent
WHERE city IS NOT NULL)

Branch
BranchNo Street City ZipCode
01 Deer Red 22 Amman 14270
02 Main 12 Alssalt 11310
03 Shardy 8 Aqaba 09146
04 Palace 31 Amman 22183
05 Gardens 27 irbid 21054

PropertyForRent
PropertyNO street city type rent ownerID EmpNo BranchNO
P110 A 12 Amman House 1000 O11 E06 O1
P114 A 26 Amman Flat 400 O12 E08 03
P115 B 05 Alssalt Flat 350 O15 E011 05
P210 C 08 Irbid Flat 700 O28 E06 02
P211 D 36 Aqaba House 1200 048 E06 03
P215 D 12 Alzarka Flat 540 044 E01 01
P217 F 12 Jarash House 860 011 E02 04
P218 G 05 Irbid Flat 320 032 E03 01

Employee
EmpNo Ename position sex DOB Salary BranchNo
E01 Samir Manager M 22-06-78 650 01
E03 Sawsan Assistant F 02-09-68 430 02
E05 Ali Supervisor M 03-06-88 490 05
E06 Hany Assistant M 07-03-81 310 03
E08 Layla Assistant F 28-12-84 330 04
E011 Rauf Manager M 30-11-76 570 02
E012 Amy supervisor f 20-10-75 425 01

2.1.4 NATURAL JOIN operations:


 Causes two or more tables or queries with a common domain to be
combined into a single table or view
 The common columns in joined tables are usually the primary key of the
dominant table and the foreign key of the dependent table in 1:M
relationships

13
Structured Query Language (SQL) fall 2006

 Equi-join – a join in which the joining condition is based on equality


between values in the common columns; common columns appear
redundantly in the result table
 Natural join – an equi-join in which one of the duplicate columns is
eliminated in the result table
 Outer join – a join in which rows that do not have matching values in
common columns are included in the result table. Outer Join has three
types:
 Left outer join
 Right outer join
 Full outer join
 Union join – includes all columns from each table in the join, and an
instance for each row of each table

Natural JOIN Example:


 For each customer who placed an order, what is the customer’s name and order
number?
SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID
FROM CUSTOMER NATURAL JOIN ORDER
ON CUSTOMER.CUSTOMER_ID = ORDER.CUSTOMER_ID;

 ON clause performs the equality check for common columns of the two
tables
Multiple Table Join Example:
 Assemble all information necessary to create an invoice for order number
1006:
SELECT CUSTOMER.CUSTOMER_ID, CUSTOMER_NAME,
CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER.ORDER_ID,
ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION,
STANDARD_PRICE, (QUANTITY * UNIT_PRICE)
FROM CUSTOMER, ORDER, ORDER_LINE, PRODUCT

WHERE CUSTOMER.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID


AND ORDER.ORDER_ID = ORDER_LINE.ORDER_ID
AND ORDER_LINE.PRODUCT_ID = PRODUCT.PRODUCT_ID
AND ORDER.ORDER_ID = 1006;

2.2 SubQueries:

14
Structured Query Language (SQL) fall 2006

 Subquery – a complex structure containing a query (inner SELECT


statement) inside another query (outer SELECT query).
 Options to build a subquery:
 In a condition of the WHERE clause
 As a “table” of the FROM clause
 Within the HAVING clause
2.2.1 Noncorrelated subqueries:
 Do not depend on data from the outer query
 Execute once for the entire outer query
 Noncorrelated query example: Show all customers who have placed an order
SELECT CUSTOMER_NAME FROM CUSTOMER
WHERE CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM ORDER);
 The IN operator will test to see if the CUSTOMER_ID value of a row
is included in the list returned from the inner subquery.
 Subquery is embedded in parentheses. In this case it returns a list
that will be used in the WHERE clause of the outer query
Processing a noncorrelated subquery
1. The subquery executes and returns the customer IDs from the
ORDER_T table
2. The outer query on the results of the subquery.
SELECT A.Name
FROM ARTIST A
WHERE A.Artist IN
( SELECT W.ArtistID
FROM WORK W
WHERE W.Title = ‘Mystic Fabric‘);

2.2.2 Correlated subqueries:


 A correlated subquery looks similar to a regular subquery
 A regular subquery can be processed from the bottom up
 For a correlated subquery, the processing is nested, i.e., a row from an
upper query statement is used in comparison with rows in a lower-level
query
 Can use the EXISTS operator
 Correlated Subquery Example: Show all orders that include furniture
finished in natural ash:
SELECT DISTINCT ORDER_ID FROM ORDER_LINE

15
Structured Query Language (SQL) fall 2006

WHERE EXISTS
(SELECT * FROM PRODUCT
WHERE PRODUCT_ID = ORDER_LINE.PRODUCT_ID
AND PRODUCT_FINISH = ‘Natural ash’);
 The EXISTS operator will return a TRUE value if the subquery
resulted in a non-empty set, otherwise it returns a FALSE
 The subquery is testing for a value that comes from the outer query
 Another example of Correlated Subquery: The following is a
correlated subquery. It contains the same tables in both levels of the
query
SELECT W1.Title, W1.Copy
FROM WORK W1
WHERE W1.Title IN
( SELECT W2.Title
FROM WORK W2
WHERE W1.Title = W2.Title
AND
W1.WorkID <> W2.WorkID);

Subquery Examples:

INSERT INTO PRODUCT


SELECT * FROM P;
UPDATE PRODUCT
SET P_PRICE = (SELECT AVG(P_PRICE) FROM PRODUCT)
WHERE V_CODE IN (SELECT V_CODE FROM VENDOR
WHERE V_AREACODE = ‘615’);
DELETE FROM PRODUCT
WHERE IN (SELECT V_CODE FROM VENDOR
WHERE V_AREACODE = ‘615’);

3. Triggers, Functions and Stored Procedures


 Are program modules that execute on demand
 Functions are routines that return values and take input parameters
 Procedures are routines that do not return values and can take input
or output parameters.
3.1 Triggers

16
Structured Query Language (SQL) fall 2006

 A trigger is a stored program that is executed by the DBMS


whenever a specified event occurs on a specified table or view
 A trigger is a stored routine that the DBMS executes automatically
whenever a specified event occurs on a specified table or view.
 Triggering event can be INSERT, UPDATE, or DELETE.
 To design a trigger mechanism, we must do the following:
1. Specifying the event and a condition that must be satisfied for
trigger execution.
2. Specifying the actions to be taken when the trigger executes.
 The above model of triggers is referenced as the event-condition-
action model for triggers.
 Firing Triggers: When a trigger is fired, the DBMS supplies:
– Old and new values for the update operation
– New values for insert operation
– Old values for deletion
 Triggers are event-driven but Procedures / Functions are called
explicitly

Simplified trigger syntax, SQL:2003


CREATE TRIGGER trigger_name
{BEFOR | AFTER | INSTEAD OF } {INSERT | DELETE | UPDATE } ON
table_name
[ FOR EACH { ROW | STATEMENT}]
[WHEN (search condition)]
< trigger SQL statement > ;
 Triggers on update can be restricted to specific attributes, E.g:
create trigger overdraft-trigger after update of balance on account

Trigger example: Suppose that the bank deals with balance overdrafts by:
 Setting the account balance to zero
 Creating a loan in the amount of the overdraft
 Giving this loan a loan number identical to the account number of the
overdrawn account
The condition for executing the trigger is an update to the account
relation that results in a negative balance value. This trigger example in
SQL will be as follows:
create trigger overdraft-trigger after update on account
referencing new row as nrow

17
Structured Query Language (SQL) fall 2006

for each row


when nrow.balance < 0
begin atomic
insert into borrower
(select customer-name, account-number
from depositor
where nrow.account-number = depositor.account-number);
insert into loan values
(n.row.account-number, nrow.branch-name, – nrow.balance);
update account set balance = 0
where account.account-number = nrow.account-number
end

Statement Level Triggers


Instead of executing a separate action for each affected row, a single
action can be executed for all rows affected by a transaction:
 Use for each statement instead of for each row
 Use referencing old table or referencing new table to refer to
temporary tables (called transition tables) containing the affected
rows
 Can be more efficient when dealing with SQL statements that update
a large number of rows
External World Actions
 We sometimes require external world actions to be triggered on a
database update. For example re-ordering an item whose quantity in a
warehouse has become below predetermined level.
 Triggers can be used to record actions-to-be-taken in a separate table.
Example: Suppose a warehouse has the following tables:
Table Explaination
inventory(item, level, minLevel, reorderQty): Inventory data
orders(item, amount) : Orders to be placed (read
by external process)

The trigger for reordering the item will be as follows:


create trigger reorder-trigger after update of amount
on inventory
referencing old row as orow, new row as nrow
for each row

18
Structured Query Language (SQL) fall 2006

when nrow.level < = mimLevel


begin
insert into orders
( nrow.item, orow.reorderQty)
end

3.2 Stored Procedures


 A stored procedure is a program that is stored within the database
and is compiled when used
– In Oracle, it can be written in PL/SQL or Java
– In SQL Server, it can be written in TRANSACT-SQL
 Stored procedures can receive input parameters and they can return
results
Create routine syntax, SQL:2003
{ CREATE PROCEDURE | CREATE FUNCTION} routine_name
([parameter [ {,parameter} . . . ]])
[RETURNS data_type result_cast] /* for functions only*/

< trigger SQL statement > ;


 Stored procedures can be called from:
 Programs written in standard languages, e.g., Java, C#
 Scripting languages, e.g., JavaScript, VBScript
 SQL command prompt, e.g., SQL*Plus, Query Analyzer
 Stored Procedure Advantages
 Greater security as store procedures are always stored on the
database server
 Decreased network traffic
 SQL can be optimized by the DBMS compiler
 Code sharing resulting in less work, standardized processing and
specialization among developers
Triggers vs. Stored Procedures
Triggers Stored procedures
Module of code that are called by Module of code that are called by a
the DBMS when INSERT, UPDATE, user or database administrator
or DELETE commands are issued
Assigned to a table or view Assigned to a database but no a table
or view
Depending on the DBMS, may have Can issue INSERT, UPDATE, and

19
Structured Query Language (SQL) fall 2006

more than one trigger per table or DELETE commands


view
Trigger may issue INSERT, UPDATE, Used for repetitive administration
and DELETE commands and thereby tasks or as part of an application
may cause invocation of other
triggers
4. Embedded and Dynamic SQL
 SQL can be embedded in triggers, stored procedures, and program code
 Embedded SQL
 Including coded SQL statements in a program written in another
language such as C or Java
 Embedded SQL Framework:
 A standard syntax to identify embedded SQL code within host
language
 A standard syntax to identify host variables
 A communication area used to exchange status and error
information between SQL and the host language
 Dynamic SQL
 Ability for an application program to generate SQL code on the fly, as
the application is running
 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 the condition are not known until the end user
specifies them
 Tends to be much slower than static SQL
 Requires more computer resources
5. SQL Views
 SQL view is a “virtual table” that is created from other tables or views
 No data actually stored; instead data from base table made available to
user
 Based on SQL SELECT statement on base tables or other views
 Materialized View – a copy or replication of data that actually stored, and
must be refreshed periodically to match the corresponding base tables.
 Views can contain columns, computed columns, aliases, and aggregate
functions from one or more tables
 Create a view by using the CREATE VIEW command

20
Structured Query Language (SQL) fall 2006

 Views provide users controlled access to tables. The syntax to create a


view is:
Create VIEW viewName [(newColumnName) [, . . .])]
AS subselect [WITH [CASCADE | LOCAL] CHECK OPTION]
 To drop a view we can use the following syntax:
DROP VIEW viewName [RESTRICT | CASCADE]
 Sample CREATE VIEW command :
CREATE VIEW EXPENSIVE_STUFF_V AS
SELECT PRODUCT_ID, PRODUCT_NAME, UNIT_PRICE
FROM PRODUCT_T
WHERE UNIT_PRICE >300
WITH CHECK_OPTION;

Examples of CREATE VIEW Command:


a) create a view
CREATE VIEW CustomerNameView AS
SELECT [Name] AS CustomerName
FROM CUSTOMER;
b) To see the view use the following command:
SELECT *
FROM CustomerNameView
ORDER BY CustomerName;

c) The Results: a list of customer names alphabetically ordered

5.2 Updateable Views:


a. View based on a:
 single table with no computed columns, and
 all non-null columns present in the view.
b. View based on:
 Any number of tables with or without computed columns, and
 INSTEAD OF trigger defined for the view.

5.3 Possibly Updateable Views:


c. View based on a single table:
 with primary key in a view
 some required columns missing from a view
 update and delete may be allowed but delete is not allowed.

21
Structured Query Language (SQL) fall 2006

d. View based on multiple tables:


 update may be allowed on the most subordinate table in the
view if rows of that table can be uniquely identified.

22

You might also like