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

Module 1 Advanced SQL

The document outlines a course module on Advanced SQL, detailing intended outcomes such as defining terms, writing queries, and establishing referential integrity. It explains the SQL environment, types of SQL commands (DDL, DML, DCL), and the creation of databases and tables, including data integrity controls and views. Additionally, it covers SQL joins, subqueries, and stored procedures, emphasizing their roles in relational database management systems.

Uploaded by

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

Module 1 Advanced SQL

The document outlines a course module on Advanced SQL, detailing intended outcomes such as defining terms, writing queries, and establishing referential integrity. It explains the SQL environment, types of SQL commands (DDL, DML, DCL), and the creation of databases and tables, including data integrity controls and views. Additionally, it covers SQL joins, subqueries, and stored procedures, emphasizing their roles in relational database management systems.

Uploaded by

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

UniversityofScienceandTechnologyofSouthernPhilippines

Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Course : Information Management

Module No. 1

Title : Advanced SQL

Intended Course Outcomes :

(1) Defineterms
(2) DefinedatabaseusingSQLdatadefinitionlanguage.
(3) WritesingletablequeriesusingSQL
(4) EstablishreferentialintegrityusingSQL
(5) Identifyadvantagesanddisadvantagesusingstoredprocedures
(6) WriteSQLprocedureswithparameters
(7) Explaintheuseofviews
(8) Explaintheuseoftriggers

THE SQL ENVIRONMENT

With today’s relational DBMSs and application generators, the importance of SQL
within the database architecture is not usually apparent to the application users.
Many users who access database applications have no knowledge of SQL at all. For
example, sites on the Web allow users to browse their catalogs (e.g., see
www.llbean.com). The information about an item that is presented, such as size,
color, description, and availability, is stored in a database. The information has
been retrieved using an SQL query, but the user has not issued an SQL command.
Rather, the user has used a prewritten program (e.g., written in Java) with
embedded SQL commands for database processing.

An SQL-based relational database application involves a user interface, a set of


tables in the database, and a relational database management system (RDBMS)
with an SQL capability. Within the RDBMS, SQL will be used to create the tables,
translate user requests, maintain the data dictionary and system catalog, update
and maintain the tables, establish security, and carry out backup and recovery
procedures. A relational DBMS (RDBMS) is a data management system that
implements a relational data model, one where data are stored in a collection of
tables, and the data relationships are represented by common values, not links.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Figure 1 is a simplified schematic of an SQL environment, consistent with


SQL:200n standard. Each database is contained in a catalog, which describes any
object that is a part of the database, regardless of which user created that object.
Figure 1 shows two catalogs: DEV_C and PROD_C. Most companies keep at least
two versions of any database they are using. The production version, PROD_C
here, is the live version, which captures real business data and thus must be very
tightly controlled and monitored. A schema is a collection of related objects,
including but not limited to base tables and views, domains, constraints, character
sets, triggers, and roles.

If more than one user has created objects in a database, combining information
about all users’ schemas will yield information for the entire database. Each
catalog must also contain an information schema, which contains descriptions of
all schemas in the catalog, tables, views, attributes, privileges, constraints, and
domains, along with other information relevant to the database. The information
contained in the catalog is maintained by the DBMS as a result of the SQL
commands issued by the users and can be rebuilt without conscious action by the
user. It is part of the power of the SQL language that the issuance of syntactically
simple SQL commands may result in complex data management activities being
carried out by the DBMS software. Users can browse the catalog contents by using
SQL SELECT statements.

Figure 1: Database Environment

SQL commands can be classified into three types. First, there are data definition
language (DDL) commands. These commands are used to create, alter, and drop
tables, views, and indexes, and they are covered first in this chapter. There may be
other objects controlled by the DDL, depending on the DBMS.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Next, there are data manipulation language (DML) commands. Many consider
the DML commands to be the core commands of SQL. These commands are used
for updating, inserting, modifying, and querying the data in the database. They
may be issued interactively, so that a result is returned immediately following the
execution of the statement, or they may be included within programs written in a
procedural programming language.

Finally, data control language (DCL) commands help a DBA control the
database; they include commands to grant or revoke privileges to access the
database or particular objects within the database and to store or remove
transactions that would affect the database.

DEFINING A DATABASE IN SQL


Because most systems allocate storage space to contain base tables, views,
constraints, indexes, and other database objects when a database is created, you
may not be allowed to create a database. Because of this, the privilege of creating
databases may be reserved for the database administrator, and you may need to
ask to have a database created.

Generating SQL Database Definitions

Several SQL DDL CREATE commands are included in SQL:200n (and each
command is followed by the name of the object being created):

You don’t have to be perfect when you create these objects, and they don’t have to
last forever. Each of these CREATE commands can be reversed by using a DROP
command. Thus, DROP TABLE tablename will destroy a table, including its
definition, contents, and any constraints, views, or indexes associated with it.
Usually only the table creator may delete the table. DROP

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

SCHEMA or DROP VIEW will also destroy the named schema or view. ALTER
TABLE may be used to change the definition of an existing base table by adding,
dropping, or changing a column or by dropping a constraint.

Creating Tables
Once the data model is designed and normalized, the columns needed for each
table can be defined, using the SQL CREATE TABLE command. The general syntax
for CREATE TABLE is

Figure 2. Create Table General Syntax

Creating Data Integrity Controls

We have seen the syntax that establishes foreign keys in Figure 2. To establish
referential integrity constraint between two tables with a 1:M relationship in the
relational data model, the primary key of the table on the one side will be
referenced by a column in the table on the many side of the relationship.
Referential integrity means that a value in the matching column on the many side
must correspond to a value in the primary key for some row in the table on the one
side or

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

be NULL. The SQL REFERENCES clause prevents a foreign key value from being
added if it is not already a valid value in the referenced primary key column, but
there are other integrity issues.

Another solution is to pass the change through to the child table(s) by using the
ON UPDATE CASCADE option. Then, if a customer ID number is changed, that
change will flow through (cascade) to the child table, Order_T, and the customer’s
ID will also be updated in the Order_T table.

A third solution is to allow the update on Customer_T but to change the involved
CustomerID value in the Order_T table to NULL by using the ON UPDATE SET
NULL option. In this case, using the SET NULL option would result in losing the
connection between the order and the customer, which is not a desired effect. The
most flexible option to use would be the CASCADE option. If a customer record
were deleted, ON DELETE RESTRICT, CASCADE, or SET NULL would also be
available. With DELETE RESTRICT, the customer record could not be deleted
unless there were no orders from that customer in the Order_T table. With
DELETE CASCADE, removing the customer would remove all associated order
records from Order_T. With DELETE SET NULL, the order records for that
customer would be set to null before the customer’s record was deleted. With
DELETE SET DEFAULT, the order records for that customer would be set to a
default value before the customer’s record was deleted. DELETE RESTRICT would
probably make the most sense. Not all SQL RDBMSs provide for primary key
referential integrity. In that case, update and delete permissions on the primary
key column may be revoked.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

A view is a virtual table based on a SELECT query. The 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.

You can create a view by using the CREATE VIEW

command: CREATE VIEW viewname AS SELECT

query

The CREATE VIEW statement is a data definition command that stores the
subquery specification—the SELECT statement used to generate the virtual table
—in the data dictionary.

A relational view has several special characteristics:

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

• You can use the name of a view anywhere a table name is expected in
a SQL statement.
• Views are dynamically updated. That is, the view is re-created on
demand each time it is invoked. Therefore, if new products are added
(or deleted) to meet the criterion P_PRICE > 50.00, those new
products will automatically appear (or disappear) in the PRICEGT50
view the next time the view is invoked.
• Views provide a level of security in the database because the view
can restrict users to only specified columns and specified rows in a
table. For example, if you have a company with hundreds of
employees in several departments, you could give the secretary of
each department a view of only certain attributes and for the
employees that belong only to that secretary’s department.
• Views may also be used as the basis for reports. For example, if you
need a report that shows a summary of total product cost and
quantity-on-hand statistics grouped by vendor, you could create a
PROD_STATS view as:

CREATE VIEW PROD_STATS AS


SELECT V_CODE, SUM(P_QOH*P_PRICE) AS
TOTCOST, MAX(P_QOH) AS MAXQTY,
MIN(P_QOH) AS MINQTY, AVG(P_QOH) AS
AVGQTY
FROM PRODUCT
GROUP BY
V_CODE;

Joining Database Tables

The ability to combine (join) tables on common attributes is perhaps the most
important distinction between a relational database and other databases. A join is
performed when data are retrieved from more than one table at a time.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Figure 4a. Inner Join Figure 4b. Left Join

Figure 4c. Right Join Figure 4d. Full Outer Join

Inner Join

The INNER JOIN keyword selects records that have matching values in both tables.

Left Join

The LEFT JOIN keyword returns all records from the left table (table1), and the
matched records from the right table (table2). The result is NULL from the right side,
if there is no match.

Right Join

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side,
when there is no match.

Full Outer Join

The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.

Self Join

A self JOIN is a regular join, but the table is joined with itself.

Union Operator

The UNION operator is used to combine the result-set of two or more SELECT
statements.
● Each SELECT statement within UNION must have the same number of columns
● The columns must also have similar data types
● The columns in each SELECT statement must also be in the same order

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate values, use
UNION ALL:

Subquery

The use of joins in a relational database allows you to get information from two or
more tables. For example, the following query allows you to get the customers’
data with their respective invoices by joining the CUSTOMER and INVOICE
tables.

SELECT INV_NUMBER, INVOICE.CUS_CODE, CUS_LNAME,


CUS_FNAME FROM CUSTOMER, INVOICE
WHERE CUSTOMER.CUS_CODE = INVOICE.CUS_CODE;

In the previous query, the data from both tables (CUSTOMER and INVOICE) are
processed at once, matching rows with shared CUS_CODE values.

However, it is often necessary to process data based on other processed data.


Suppose, for example, you want to generate a list of vendors who provide products.

SELECT V_CODE, V_NAME FROM VENDOR


WHERE V_CODE NOT IN (SELECT V_CODE FROM PRODUCT);

Similarly, to generate a list of all products with a price greater than or equal to the
average product price, you can write the following query:

SELECT P_CODE, P_PRICE FROM PRODUCT


WHERE P_PRICE >= (SELECT AVG(P_PRICE) FROM PRODUCT);

In both of those cases, you needed to get information that was not previously known:
• What vendors provide products?

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

• What is the average price of all products?


In both cases, you used a subquery to generate the required information that could
then be used as input for the originating query.
Subquery characteristics:
• A subquery is a query (SELECT statement) inside a query.
• A subquery is normally expressed inside parentheses.
• The first query in the SQL statement is known as the outer query.
• The query inside the SQL statement is known as the
inner query. The inner query is executed first.
• The output of an inner query is used as the input for the outer query.
• The entire SQL statement is sometimes referred to as a nested query.

Subqueries can be:

● Noncorrelated–executed once for the entire outer query


● Correlated–executed once for each row returned by the outer query

Noncorrelated Subquery
● Do not depend on data from the outer query

● Execute once for the entire outer query

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example:

Figure 5. Noncorrelated Query

Correlated Subquery
●Make use of data from the outer query

●Execute once for each row of the outer query


●Can use the EXISTS operator

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example:

Figure 6. Correlated Query

Stored Procedures

● A stored procedure is a segment of declarative SQL code, which is stored in the


database catalog.
● A stored procedure can be invoked by a program, a trigger or even another stored
procedure.
● A stored procedure which calls itself is recursive stored procedure. Almost
RDBMS supports recursive stored procedure but MySQL does not support it
well.
● A stored procedure or a stored function is a program that is stored within the
database and is compiled when used
● Stored procedures can receive input parameters and they can return results

Stored procedures can be called from:


o Standard languages
o Scripting languages
o SQL command prompt

Advantages of Stored Procedures

● increases performance of application


● reduces the traffic between application and database server
● reusable and transparent to any application which wants to use it
● Secure

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Disadvantages of Stored Procedures

● make the database server high load in both memory and processors
● only contains declarative SQL
● difficult to debug
● not easy to write and maintain

Stored Procedure Basic Syntax

DELIMITER//

CREATEPROCEDUREname_of_proc()

BEGIN

<SQLCommand>
Example
DELIMITER//

CREATEPROCEDUREGetAllProducts() LANGUAGE SQL

NOTDETERMINISTIC
SQLSECURITYDEFINER

COMMENT'AProcedure'

Calling the Stored Procedure


● In order to invoke a stored procedure, we use the following SQL command:
CALL STORED_PROCEDURE_NAME()

● First you use keyword CALL followed by the stored procedure name
and a pair of parenthesis. To invoke the stored procedure
GetAllProducts, we use the following command:
CALL GetAllProducts();

Using Variables in Stored Procedures

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Variables are used in stored procedure to store the immediate result. You can
declare a variable by the following syntax:
DECLARE variable_name datatype(size) DEFAULT default_value;

Example

we can define a variable name total_sale with the data type INT and default value
is 0 as follows:

DECLARE total_sale INT DEFAULT 0

To declare two or more variables with the same data type we can use only just one
DECLARE such as:

DECLAREx,yINTDEFAULT0

Assigning Variables
To assign other value to a variable you can use SET statement, for example:

DECLARE total_count INT DEFAULT 0

The total_count variable’s value now is ten (10).

Besides SET statement, we can use SELECT INTO statement to assign result of a
query to a variable.

DECLARE total_products INT DEFAULT 0; SELECT


COUNT(*) INTO total_products FROM products ;

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

In the example above, we declare a variable total_products and initialize its value
to zero. Then we use SELECT … INTO statement to assign the variable
total_products with the total products in products database table.

Variable Scope
● If you declare a variable inside a stored procedure, it will be out of scope when
the END of stored procedure reached.
● If you defined a variable inside block BEGIN/END inside a stored procedure it
will be out of scope if the END reached.
● You can declare two variables or more variables with the same name in
different scopes; the variable only is effective in its scope.
● A variable with the ‘@’ at the beginning is session variable. It exists until the
session end.

Stored Procedure Parameters


Almost stored procedures that you develop require parameters. The parameters
make the stored procedure more flexible and useful. In MySQL, a parameter has
one of three modes
■ IN - It is the default mode. It takes a parameter as input, such as an
attribute. When we define it, the calling program has to pass an argument
to the stored procedure. This parameter's value is always protected.
■ OUT - It is used to pass a parameter as output. Its value can be changed
inside the stored procedure, and the changed (new) value is passed back to
the calling program. It is noted that a procedure cannot access the OUT
parameter's initial value when it starts.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

■ INOUT - It is a combination of IN and OUT parameters. It means the calling


program can pass the argument, and the procedure can modify the INOUT
parameter, and then passes the new value back to the calling program.
General Syntax:

MODE param_name param_type(param_size)


Example of IN Parameter

DELIMITER&&
CREATEPROCEDUREget_student(INvar1INT)B
EGIN
SELECT*FROMstudent_infoLIMITvar1;
SELECTCOUNT(stud_code)ASTotal_StudentFROMstudent_info;
END&&
DELIMITER;

mysql>CALLget_student(4);

Example of OUT Parameter

DELIMITER&&
CREATEPROCEDUREdisplay_max_mark(OUThighestmarkIN
T)BEGIN
SELECTMAX(marks)INTOhighestmarkFROMstudent_info;
END&&
DELIMITER;

mysql>CALLdisplay_max_mark(@M);
InformationM anagement
mysql>SELECT@M;
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example of INOUT Parameter

DELIMITER&&
CREATEPROCEDUREdisplay_marks(INOUTvar1INT)
BEGIN
SELECTmarksINTOvar1FROMstudent_infoWHEREstud_id=var1;
END&&
DELIMITER;

mysql>SET@M='3';
mysql>CALLdisplay_marks(@M);
mysql>SELECT@M;

Dropping a Procedure
Syntax:
DROPPROCEDURE<nameofproc>

Stored Functions
● A function can be called from inside a statement just like any other function
(that is, by invoking the function's name), and can return a scalar value.
● A stored function is a special kind stored program that returns a single value.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

● Typically, you use stored functions to encapsulate common formulas or


business rules that are reusable among SQL statements or stored programs.
● You can use a stored function in SQL statements wherever an expression is used

Syntax:

DELIMITER $$
CREATE FUNCTION function_name( param1, param2,… )
RETURNS datatype [NOT] DETERMINISTIC

In this syntax:
● First, specify the name of the stored function that you want to create after
CREATE FUNCTION keywords. o Second, list all parameters of the stored
function inside the parentheses followed by the function name. By default, all
parameters are the IN parameters. You cannot specify IN , OUT or INOUT
modifiers to parameters
● Third, specify the data type of the return value in the RETURNS statement,
which can be any valid MySQL data types.
● Fourth, specify if a function is deterministic or not using the DETERMINISTIC
keyword
● A deterministic function always returns the same result for the same input
parameters whereas a non-deterministic function returns different results for
the same input parameters.
● If you don’t use DETERMINISTIC or NOT DETERMINISTIC, MySQL uses the NOT
DETERMINISTIC option by default.
● Fifth, write the code in the body of the stored function in the BEGIN END
block. Inside the body section, you need to specify at least one RETURN
statement. The RETURN statement returns a value to the calling programs.
Whenever the RETURN statement is reached, the execution of the stored
function is terminated immediately.
Example
Let us use the table for stored functions demonstration:

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Problem: Create a function that returns a customer level based on credit.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Calling a Stored Function

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Output

Stored Function Parameter

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Calling Stored Function in a Stored Procedure

Deterministic Functions
Deterministic functions always return the same result any time they are called with
a specific set of input values and given the same state of the database.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example of Deterministic Functions

Nondeterministic Functions
Nondeterministic functions may return different results each time they are called
with a specific set of input values even if the database state that they access
remains the same.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example of Nondeterministic Functions

SQL Triggers
● an SQL statements or a set of SQL statements which is stored to be activated
or fired when an event associating with a database table occurs. The event can
be any event including INSERT, UPDATE and DELETE.
● Sometimes a trigger is referred as a special kind of stored procedure in term of
procedural code inside its body

Advantages of Triggers
● SQL Trigger provides an alternative way to check integrity.
● SQL trigger can catch the errors in business logic in the database level.
● SQL trigger provides an alternative way to run scheduled tasks. With SQL
trigger, you don’t have to wait to run the scheduled tasks. You can handle
those tasks before or after changes being made to database tables.
● SQL trigger is very useful when you use it to audit the changes of data in a
database table.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Disadvantages of Triggers

● SQL trigger only can provide extended validation and cannot replace all the
validations.
● SQL Triggers executes invisibly from client-application which connects to the
database server so it is difficult to figure out what happen underlying database
layer.
● SQL Triggers run every updates made to the table therefore it adds workload
to the database and cause system runs slower

Before Update Trigger


● As the name implies, it is a trigger which enacts before an update is invoked. If
we write an update statement, then the actions of the trigger will be performed
before the update is implemented.
Example

create table customer (acc_no integer primary key,

cust_name varchar(20), avail_balance decimal);

create table mini_statement (acc_no integer, avail_balance decimal,

Sample values

insert into customer values (1000, "Fanny", 7000);

insert into customer values (1001, "Peter", 12000);

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Before Update Trigger

delimiter //

create trigger update_cus


before update on customer
for each row

begin

Invoke Before Update Trigger

update customer set avail_balance = avail_balance + 3000


where acc_no = 1001;

Output

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

After Update Trigger


● this trigger is invoked after an update occurs. (i.e., it gets implemented after
an update statement is executed.)

Example
Create another table.

Sample values:
create table micro_statement (acc_no integer, avail_balance decimal,
foreign key(acc_no) references customer(acc_no) on delete cascade);

A fterupdatetrigg
insert into customer values (1002, "Janitor", 4500);
er

Invokeafterupdatetrigg
erdelimiter //
update customer set avail_balance = avail_balance + 1500
createtriggerupdate_after
where acc_no = 1002;
after update on customer
for each row

begin

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Output

Before Insert Trigger


● this trigger is invoked before an insert, or before an insert statement
is executed. Example
Consider the table

create table contacts (contact_id INT (11) NOT NULL AUTO_INCREMENT,


last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25),

birthday DATE, created_date DATE, created_by VARCHAR(30),

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Create before insert trigger

delimiter //
create trigger contacts_before_insert
before insert

on contacts for each row


begin
DECLARE vUser varchar(50);

-- Find username of person performing INSERT into table


select USER() into vUser;

-- Update create_date field to current system date


SET NEW.created_date = SYSDATE();
-- Update created_by field to the username of the person
performing the INSERT

-> SET NEW.created_by = vUser; -> end; //

Invoking the before insert trigger

insert into contacts values (1, "Newton", "Enigma",


str_to_date ("19-08-1999", "%d-%m-%Y"),

Output

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

After Insert Trigger

● this trigger gets invoked after an insert is


implemented. Example
Consider these tables

create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT,


last_name VARCHAR(30) NOT NULL, first_name VARCHAR(25),
birthday DATE,

CONSTRAINT contacts_pk PRIMARY KEY (contact_id));

Create after insert trigger

Invokeafterinserttrigg
erdelimiter//
insertintocontacts
createtriggercontacts_after_insert
values(1,"Kumar","Rupesh",str_to_date("20-06-1999","%d-%m-%Y"));
afterinsert
oncontactsforeachrow

begin
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Output

Before Delete Trigger

● this trigger is invoked before a delete occurs, or before deletion statement is


implemented. Example
Consider the following tables

create table contacts (contact_id int (11) NOT NULL


AUTO_INCREMENT,
last_name VARCHAR (30) NOT NULL, first_name VARCHAR (25),
birthday DATE, created_date DATE, created_by VARCHAR(30),
CONSTRAINT contacts_pk PRIMARY KEY (contact_id));

Create before delete trigger

delimiter //

create trigger contacts_before_delete


before delete -> on contacts for each row
begin
DECLARE vUser varchar(50);

-- Find username of person performing the DELETE into table


SELECT USER() into vUser;

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Invoking before delete trigger

Output
insertintocontacts
values(1,"Bond","Ruskin",str_to_date("19-08-1995","%d -%m-
%Y"),
str to_date("27-04-2018","%d-%m-%Y"),"xyz");
_

After Delete Trigger


● this trigger is invoked after a delete occurs, or after a delete operation is
implemented. Example
Consider the tables

create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT,


last_name VARCHAR (30) NOT NULL,
first_name VARCHAR (25), birthday DATE,

created_date DATE, created_by VARCHAR (30),


CONSTRAINT contacts_pk PRIMARY KEY (contact_id));

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Create after delete trigger

Invokeafterdeletetrigg
ercreate trigger contacts_after_delete
after delete on contacts for each row
begin

DECLARE vUser varchar(50);

insert into contacts


--FindusernameofpersonperformingtheDELETEintotable
values (1, "Newton", "Isaac", str_to_date ("19-08-1985", "%d-%m-%Y"),
SELECTUSER()intovUser;
str_to_date ("23-07-2018", "%d-%m-%Y"), "xyz");

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

MySQL If-then-Else Statement

The IF statement has three forms:


● IF – THEN
● IF –THEN-ELSE

● IF-THEN-ELSEIF-ELSE
The IF-THEN statement allows you to execute a set of SQL statements based on a
specified condition.
Syntax:

IF condition THEN

statements;

Example

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

In case you want to execute other statements when the condition in the IF branch
does not evaluate to TRUE, you can use the IF-THEN-ELSE statement as follows:

Example

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

If you want to execute statements conditionally based on multiple conditions, you


use the following IF-THEN-ELSEIF-ELSE statement:

Example

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

The CASE statement


Besides the IF statement, MySQL provides an alternative conditional statement called
the CASE statement for constructing conditional statements in stored procedures.
● The CASE statements make the code more readable and efficient.

● The CASE statement has two forms:


■ Simple CASE and
■ searched CASE statements.

Simple Case statement syntax

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example

Searched Case syntax

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example

Loop Statement
The LOOP statement allows you to execute one or more statements
repeatedly. Syntax

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example

While Loop Statement


The WHILE loop is a loop statement that executes a block of code repeatedly as
long as a condition is true.
Syntax

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example

First, create a table

Second, create a procedure to insert date into the calendars table

Third, create a new stored procedure LoadCalendars() that loads a number of days
starting from a start date into the calendars table.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Repeat statement
The REPEAT statement executes one or more statements until a search condition
is true. Syntax

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Example

Leave statement
The LEAVE statement exits the flow control that has a given
label. Syntax

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Exercise:

Identify the term that is being described.


Schema Object 1. Describes any object that is a part of the database, regardless of
which use created that object
Schema 2. A collection of related objects, including but not limited to base tables
and views, domains, constraints, character sets, triggers, and roles.
View 3. A virtual table based on a SELECT query. The query can contain columns,
computed columns, aliases, and aggregate functions from one or more tables.
Inner Join 4. This type of join returns all records that have matching values in both
tables.
Left Join 5. This join returns all records from the left table, and the matched
records from the right table.
Self Join 6. It is a regular join, but the table is joined with itself.
Correlated Subquery 7. A subquery that is executed once for each row returned by the
outer query.
Non Correlated Subquery 8. A type of subquery that is executed once for the entire
outer query.
Stored Procedure 9. This can be invoked by a program, a trigger or even another
stored procedure.

In Out Parameter 10. It is a combination of IN and OUT parameters. It means the


calling program can pass the argument, and the procedure can modify the INOUT
parameter, and then passes the new value back to the calling program.
Function 11. It is a special kind stored program that returns a single value.
Deterministic Function 12. This predefined function always return the same result
any time they are called with a specific set of input values and given the same state
of the database.
Trigger 13. An SQL statements or a set of SQL statements which is stored to be
activated or fired when an event associating with a database table occurs. The
event can be any event including INSERT, UPDATE and DELETE.
While Loop 14. It is a loop statement that executes a block of code repeatedly as
long as a condition is true.
Until Loop 15. The statement executes one or more statements until a search
condition is true.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

Laboratory Exercise:

Problem 1 to 9, refer to the relational schema and table definitions below.

Figure 1. Research Center Relational Schema

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

1. Create the database ResearchCenter.

2. Define all tables and populate it accordingly.


3. Show the name of the employees and job title who are working in a project
named Hotel Management.
4. Find all the employees and project name who started working in a project
between the first and third month of year 2020.
5. Create a view name salary_computation. The view contains the employee ssn,
name, job title, hourly rate, number of hours worked in a project, and its total pay.
Use an alias for the computed column total pay.
6.Create a view that will show the total worked hours of an employee for all the
projects. The view contains the employee ssn, name, and total number of hours
worked for all projects (use alias total_hours for this computed column).

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

7. Insert new employee records:

8. Perform a join operation for the tables employee and workedon showing all the
data from the employee table regardless if it has matching records in workedon
table or not.
9. Perform a self-join to employee table that will display all the employee name
with job title project manager only.
For problem 10 to 14, use the BikeStores_DB uploaded in USTeP.
10. (Correlated Subquery) Select product id and product name of products that
has been ordered by a customer.
11. (Correlated Subquery) Select product id and list price of products whose list
price is greater than the average list price of all products in ordered items.
12. (Noncorrelated Subquery) Show all the staff id, first name, and last name of
staff working in the store located in the state of California (CA).
13. (Noncorrelated Subquery) Display all the customer id, first name and last
name of customers who placed an order with the order status of “Processing”.
14. (Inline subquery) Given the output, provide the SQL statement.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

For problems 15 to 17, refer to Figure 2.

Figure 2. Movie Database

15. Create a procedure to count the star rating of a movie.

16. Create a procedure that displays the specific reviewer name who gave star rating
to a movie.
17. Make a function that will give descriptive rating to movies. 5 stars --
Outstanding; 4 stars -- Very Good; 3 stars -- Good; < 3 stars -- Improve.

For problems 18 to 19, refer to Figure 3.

Figure3.CustomerDatabase

18. Create a new table named cust_balance with the following definition:
create table cust_balance (custnum int(5), newBalance decimal(10,2),
foreign key (custnum) REFERENCES customer (custnum));
Create a trigger that will fire after the customer balance has been updated.

InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon

19. For the following table definition:


create table customer_details( custnum int(5), custLname char(15), custFname
char(15), latestInsertTime time, PRIMARY KEY (custnum));
Make a trigger that will create an audit for newly inserted data in customer table.

References:
(1)Jeff Hoffer, Ramesh Venkataraman, Heikki Topi-Modern Database Management-
Pearson Education Limited (2016)
(2)https://www.mysqltutorial.org/mysql-stored-function/
(3)https://www.javatpoint.com/mysql-procedure

(4)https://www.geeksforgeeks.org/different-types-of-mysql-triggers-with-examples/

InformationManagement

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy