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

Chapter8_AdvancedSQL_Part5V2

Database class

Uploaded by

chamso Abou
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter8_AdvancedSQL_Part5V2

Database class

Uploaded by

chamso Abou
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Advanced SQL

CSC3326
Learning Objectives

• Use SQL to create database views


• Use Procedural Language SQL (PL/SQL) to create
- Stored procedures
- Stored functions
- Triggers
• Use SQL Index to speed up data retrieval
Views
• The output of a relational statement such as SELECT is another relation
• A view is a virtual table based on a SELECT query.
• The select query can contain columns, computed columns, aliases, and
aggregate functions from one or more tables.
• The tables on which the view is based are called base tables.
• Syntax to create a view:

• CREATE VIEW statement: data definition command that stores the query
specification-the SELECT statement used to generate the virtual table- in
the data dictionary.
View Characteristics
• You can use the name of a view anywhere a table name is expected in a
SQL statement.
• Views are dynamically updated=>the view is re-created on demand
each time it is invoked.
• Views provide a level of security in the database because they can
restrict users to seeing only specified columns and rows in a table (row
level and column level) security.
• A view can draw data from several different tables and present it as a
single table, turning multi-table queries into single-table queries against
the view
=> Hiding the complexity of a complex SQL query.
Procedural SQL
• Unfortunately, SQL does not support the conditional execution of
procedures that are typically supported by a programming language.
• SQL also fails to support looping operations in programming languages
that permit the execution of repetitive actions typically encountered in a
programming environment.
• Traditionally, if there is a need for such procedural constructs, you would
use a programming language as Visual Basic .NET, C#, or Java
=> Usually involves the duplication of application code in many programs.
Procedural SQL
• A better approach is to isolate critical code and then have all application
programs call the shared code => better maintenance and logic control.
• This code should be stored and executed within the database.
• Most RDBMS vendors created numerous programming language extensions.
• Those extensions include:
 Flow-control procedural programming structures (IF-THEN-ELSE, DO-WHILE)
for logic representation
 Variable declaration and designation within the procedures.
 Error management.
Procedural Language SQL (PL/SQL)
• An extension of SQL language that combines the data manipulation power of SQL with the processing
power of procedural language to create super powerful SQL queries.
• PL/SQL means instructing the compiler 'what to do' through SQL and 'how to do' through its procedural
way.
• Procedural Language SQL (PL/SQL) is a language that makes it possible to use and store procedural
code and SQL statements within the database and to merge SQL and traditional programming
constructs, such as variables, conditional processing (IF-THEN-ELSE), basic loops (FOR and WHILE
loops), and error trapping.
• The procedural code is executed as a unit by the DBMS when it is invoked (directly or indirectly) by the
end user.
• PL/SQL objects:
 Stored procedures
 Stored functions
 Triggers
Procedural Language SQL (PL/SQL)
• Block of code containing standard SQL statements and procedural extensions that is
stored and executed at the DBMS server.

• It represents business logic that can be encapsulated, stored, and shared among multiple
database users.
• Most DBMS products provide some procedural language support, but there is no universal
procedural language for all RDBMS.

• MS SQL Server uses Transact-SQL (TSQL).

• Oracle uses PL/SQL.

• PostgreSQL uses (PL/PGSQL)


Variable Data Types
Table 8.4
PL/SQL BASIC
DATA TYPES
DATA TYPE DESCRIPTION
CHAR Character values of a fixed length; for
example:
W_ZIP CHAR(5)
VARCHAR2 Variable-length character values; for example:
W_FNAME VARCHAR2(15)
NUMBER Numeric values; for example:
W_PRICE NUMBER(6,2)
DATE Date values; for example:
W_EMP_DOB DATE
%TYPE Inherits the data type from a variable that you
declared previously or from an attribute of a
database table; for example:
W_PRICE PRODUCT.P_PRICE%TYPE
Assigns W_PRICE the same data type as the
P_PRICE column in the PRODUCT table
Procedural Language SQL (PL/SQL)
• PL/SQL blocks can contain only standard SQL data manipulation
language (DML) commands such as SELECT, INSERT, UPDATE, and
DELETE. The use of data definition language (DDL) commands is not
directly supported in a PL/SQL block.
• The SELECT statement uses the INTO keyword to assign the output of
the query to a PL/SQL variable or the assignment symbol (:=)
• Each statement inside the PL/SQL code must end with a semicolon ( ; ).
Stored Procedures
• Named collection of procedural and SQL statements
 Stored in the database
 Can be used to encapsulate and represent business transactions

• Advantages
 Reduce network traffic and increase performance. The use of stored procedures
improves system performance because all transactions are executed locally on
the RDBMS, so each SQL statement does not have to travel over the network.
 Decrease code duplication by means of code isolation (creating unique PL/SQL
modules that are called by application programs. Thereby minimizing the chance
of errors and the cost of application development and maintenance.)
Stored Functions
• Named group of procedural and SQL statements that returns a value
• Indicated by a RETURN statement in its program code

• It can be invoked within PL/PGSQL code such as stored procedures and


triggers.
• Cannot call a stored procedure from a stored function.
• Stored functions can be called from a select statement whereas a stored
procedure cannot.
• Stored function can include only Select DML command however Stored
Procedure can include any DML command.
Practice Problem

• Write a stored function to calculate the number of customers that have


generated invoices on a specific date.
Triggers
• Automating business procedures and automatically maintaining data integrity and
consistency are critical in a modern business environment.
• One of the most critical business procedures is proper inventory management.
• You want to make sure that current product sales can be supported with sufficient
product availability.
• Therefore, you must ensure that a product order is written to a vendor when that
product’s inventory drops below its minimum allowable quantity on hand.
Business logic requires an update of the product quantity on hand each time there
is a sale of that product.
If the product’s quantity on hand falls below its minimum allowable inventory
level, the product must be reordered.
Triggers
• A trigger is procedural SQL code that is automatically invoked by the
RDBMS upon the occurrence of a given data manipulation event.
• DML triggers run when a user tries to modify data through a data manipulation
language (DML) event.
• DML events are INSERT, UPDATE, or DELETE statements on a table.
• A trigger is invoked before or after a data row is inserted, updated, or deleted.
• A trigger is associated with a database table.
• Each database table may have one or more triggers.
Triggers
• Maintaining complex integrity constraints (referential integrity) or
implementing business rules
• Automatic generation of derived column values.
• Auditing information in a table by recording the changes.
• Automatically signaling other programs that action needs to take place when
changes are made to a table.
Triggers
• The triggering timing: BEFORE or AFTER. This timing indicates when the trigger’s PL/SQL code executes
—in this case, before or after the triggering statement is completed.
• The triggering event: The statement that causes the trigger to execute (INSERT, UPDATE, or DELETE).
• The triggering level: The two types of triggers are statement-level triggers and row-level triggers.
 A statement-level trigger is assumed if you omit the FOR EACH ROW keywords. This type of
trigger is executed once. This is the default case.
 Due to its features, a statement-level trigger is not often used for data-related activities. It’s
typically used to enforce extra security measures on the kind of transaction that may be
performed on a table.
 A row-level trigger requires use of the FOR EACH ROW keywords. This type of trigger is
executed once for each row affected by the triggering statement. (In other words, if you update
10 rows, the trigger executes 10 times.)
• The triggering action: The PL/SQL code enclosed between the BEGIN and END keywords. Each
statement inside the PL/SQL code must end with a semicolon ( ; ).
Triggers
• A row-level trigger fires once for each row that is affected by a triggering event. For example,
if deletion is defined as a triggering event for a particular table, and a single DELETE statement
deletes five rows from that table, the trigger fires five times, once for each row.

• A statement-level trigger fires only once for each statement. Using the previous example, if
deletion is defined as a triggering event for a particular table, and a single DELETE statement
deletes five rows from that table, the trigger fires once, regardless of the number of rows in the
table that the triggering statement affects.

• Row triggers are useful if the code in the trigger action depends on data provided by
rows that are affected.

• Statement triggers are useful if the code in the trigger action does not depend on
the data provided by the rows affected.
Triggers
• All changes are done first in primary memory and then transferred to
permanent memory.
• Data is first read from permanent storage to primary memory, then change
is made in primary memory, and finally the changed data is written back to
permanent memory (on disk).
• BEFORE means before the changes are permanently saved to disk,
but after the changes are made in memory.
• AFTER means After the changes are permanently saved to disk.


Triggers
• Use Before Trigger:​
-In the case of validation check OR
-Insert or update the same table on which the trigger is defined.​
​Use After Trigger:​
-Insert/Update related table, not the same table on which the trigger is
defined.​
Triggers
• The DBMS makes copies of every row being changed by a DML (INSERT, UPDATE, or
DELETE) statement.
• NEW and OLD are special variables that you can use with PL/SQL row-level
triggers
• NEW refers to the new table row for insert and update operations in row-level triggers:
• Its usage is :NEW.column where column is the name of the column in the table on
which the trigger is defined.
• For example: NEW.P_QOH refers to the new QOH after the update.
• OLD refers to the old table row for delete and update operations in row-level triggers:
• Its usage is :OLD.column where column is the name of the column in the table on
which the trigger is defined.
• For example: OLD.P_QOH refers to the value QOH before the update.
Trigger Example 1
Suppose, you want to restrict users to update credit of customers from 28th to
31st of every month so that you can close the financial month.
To enforce this rule, you can use this statement-level trigger:
Trigger Examples 2 &3
Trigger Example 4
Trigger Example 5

• You must ensure that a product order is written to a vendor when that
product’s inventory drops below its minimum allowable quantity on
hand.
• To automate product ordering, you first must make sure the product’s
quantity on hand reflects an up-to-date and consistent value.
• The trigger TRG_PRODUCT_REORDER has four problems:
• Problem1: What happens if you update the minimum quantity of
product 2232/QWE?
Second version of the trigger
• Problem2: The trigger sets the P_REORDER value only to 1; it does
not reset the value to 0, even if such an action is clearly required
when the inventory level is back to a value greater than the minimum
value.
• Problem3: The trigger fires after the triggering statement is completed. Therefore, the DBMS
always executes two statements (INSERT plus UPDATE or UPDATE plus UPDATE). That is, after you
update P_MIN or P_QOH or you insert a new row in the PRODUCT table, the trigger executes another
UPDATE statement automatically.
•Problem4: The triggering action performs an UPDATE of all the rows in the PRODUCT table, even if
the triggering statement updates just one row! This can affect the performance of the database.
Imagine what will happen if you have a PRODUCT table with 519,128 rows and you insert just one
product. The trigger will go over all 519,129 rows, including the rows that do not need an update!
The updated trigger definition that solves all the previous stated
problems
•The trigger is executed before the actual triggering statement is completed. This
clearly indicates that the triggering statement is executed before the INSERT or
UPDATE completes.
•The trigger is a row-level trigger instead of a statement-level trigger. The FOR
EACH ROW keywords make the trigger a row-level trigger. Therefore, this trigger
executes once for each row affected by the triggering statement.
•The trigger action uses the :NEW attribute reference to change the value of the
P_REORDER attribute.
Trigger Example 3

This row-level trigger updates a row in a different table (PRODUCT), using the :NEW
values of the recently added LINE row.
PostgreSQL Trigger
• For creating a new PostgreSQL Trigger, you need to follow these steps:

1. First, you need to create a trigger function using CREATE


FUNCTION statement.
2. Then you need to bind the trigger function to a table by using CREATE
TRIGGER statement.
Practice Problem
• Create a trigger to update the customer balance (CUS_Balance) in the
customer table after inserting any new Line row (selling a product with line
units and line price).

You might also like