Module 1 Advanced SQL
Module 1 Advanced SQL
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Module No. 1
(1) Defineterms
(2) DefinedatabaseusingSQLdatadefinitionlanguage.
(3) WritesingletablequeriesusingSQL
(4) EstablishreferentialintegrityusingSQL
(5) Identifyadvantagesanddisadvantagesusingstoredprocedures
(6) WriteSQLprocedureswithparameters
(7) Explaintheuseofviews
(8) Explaintheuseoftriggers
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.
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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.
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.
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
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.
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.
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:
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.
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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.
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
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.
In the previous query, the data from both tables (CUSTOMER and INVOICE) are
processed at once, matching rows with shared CUS_CODE values.
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:
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
Noncorrelated Subquery
● Do not depend on data from the outer query
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Example:
Correlated Subquery
●Make use of data from the outer query
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Example:
Stored Procedures
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
● make the database server high load in both memory and processors
● only contains declarative SQL
● difficult to debug
● not easy to write and maintain
DELIMITER//
CREATEPROCEDUREname_of_proc()
BEGIN
<SQLCommand>
Example
DELIMITER//
NOTDETERMINISTIC
SQLSECURITYDEFINER
COMMENT'AProcedure'
● 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();
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:
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:
Besides SET statement, we can use SELECT INTO statement to assign result of a
query to a variable.
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.
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
DELIMITER&&
CREATEPROCEDUREget_student(INvar1INT)B
EGIN
SELECT*FROMstudent_infoLIMITvar1;
SELECTCOUNT(stud_code)ASTotal_StudentFROMstudent_info;
END&&
DELIMITER;
mysql>CALLget_student(4);
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
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
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
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Output
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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
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
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
Sample values
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
delimiter //
begin
Output
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
delimiter //
create trigger contacts_before_insert
before insert
Output
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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
delimiter //
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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");
_
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Invokeafterdeletetrigg
ercreate trigger contacts_after_delete
after delete on contacts for each row
begin
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
● 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
Example
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Example
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
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Example
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:
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
Laboratory Exercise:
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
InformationManagement
UniversityofScienceandTechnologyofSouthernPhilippines
Alubijid|CagayandeOro|Claveria|Jasaan|Oroquieta|Panaon
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
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.
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
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