DBMS - Unit II - PPT - With PLSQL
DBMS - Unit II - PPT - With PLSQL
12/4/2019 2
Characteristics of SQL
SQL is an ANSI and ISO standard computer language for creating and manipulating
databases.
SQL allows the user to create, update, delete, and retrieve data from a database.
SQL is very simple and easy to learn.
SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL
Sever etc.
SQL is a declarative language, not a procedural language.
All keywords of SQL are case insensitive.
12/4/2019 3
Advantages of SQL
• Data-definition language (DDL).
The SQL DDL provides commands for defining relation schemas, deleting relations, and
modifying relation schemas.
• Interactive data-manipulation language (DML).
The SQL DML includes a query language based on both the relational algebra and the
tuple relational calculus. It includes also commands to insert tuples into, delete tuples
from, and modify tuples in the database.
• View definition.
The SQL DDL includes commands for defining views.
• Transaction control.
SQL includes commands for specifying the beginning and ending of transactions.
12/4/2019 4
Continued…
• Embedded SQL and dynamic SQL.
Embedded and dynamic SQL define how SQL statements can be embedded
within general-purpose programming languages, such as C, C++, Java, PL/I,
Cobol, Pascal, and Fortran.
• Integrity.
The SQL DDL includes commands for specifying integrity constraints that the
data stored in the database must satisfy. Updates that violate integrity
constraints are disallowed.
• Authorization.
The SQL DDL includes commands for specifying access rights to relations and
views.
12/4/2019 5
Advantages of SQL
High Speed:
SQL Queries can be used to retrieve large amounts of records from a database
quickly and efficiently.
Well Defined Standards Exist:
SQL databases use long-established standard, which is being adopted by ANSI &
ISO. Non-SQL databases do not adhere to any clear standard.
No Coding Required:
Using standard SQL it is easier to manage database systems without having to
write substantial amount of code.
12/4/2019 6
Continued…
12/4/2019 7
SQL Data Types and Literals
char(n). Fixed length character string, with user-specified length n.
varchar(n). Variable length character strings, with user-specified maximum length n.
Boolean. Accepts value true or false.
int. Integer (a finite subset of the integers that is machine-dependent).
smallint. Small integer (a machine-dependent subset of the integer domain type).
decimal(p,d). Fixed point number, with user-specified precision of p digits, with d digits to the
right of decimal point. (ex., decimal(3,1), allows 44.5 to be stored exactly, but not 444.5 or 0.32)
Double(p,d). Floating point and double-precision floating point numbers, with machine-
dependent precision. Decimal precision can go to 53 places for a DOUBLE.
float(p,d). Floating point number, with user-specified precision of at least n digits. Decimal
precision can go to 24 places for a FLOAT.
12/4/2019 8
SQL- Structured Query Language
12/4/2019 9
SQL language statements
12/4/2019 10
Data Definition Language (DDL)
The SQL data-definition language (DDL) allows
Database tables to be created or deleted
Define indexes (keys)
Specify links between tables
Impose Integrity constraints between database tables
Some of the most commonly used DDL statements in SQL are
◦ CREATE TABLE : creates a new database tables
◦ ALTER TABLE : Alters(changes) a database tables
◦ DROP TABLE : Deletes a database table
◦ RENAME TABLE : Renames a database table
◦ TRUNCATE TABLE : Deletes all the records in the table.
12/4/2019 11
Create Table Construct
12/4/2019 12
Integrity Constraints
Constraints are the rules enforced on the data
columns of a table. These are used to limit the
type of data that can go into a table. This
ensures the accuracy and reliability of the data
in the database.
Constraints could be either column level or
table level.
1. Column Level: Column level constraints are
applied to only one column.
2. Table Level: Table level constraints are
applied to the whole table.
There are 4 types of Integrity Constraints:
12/4/2019 13
Domain Integrity Constraints
Domain Integrity constraints can be defined as the definition of a valid set of values for an
attribute.
1. NOT NULL Constraint:
2. Unique Constraint :
3. Default Constraint :
4. Check Constraint :
12/4/2019 14
Domain Integrity Constraints (Cont..)
2. Unique Constraint :
• Ensures that all values in a column are different.
12/4/2019 15
Domain Integrity Constraints (Cont..)
4. Check Constraint:
• The CHECK constraint ensures that all the values in a column satisfies certain
conditions.
Roll_No Name Age
1 ABC 18 Domain Constraint
2 XYZ 20 (Age>=18 & Age<=30)
3 PQR 25
4 MNP 38 Not Allowed
12/4/2019 16
Entity Integrity Constraints
Primary Key constraint:
• states that primary key value can't be null.
• Because primary key value is used to identify individual rows in relation and if the
primary key has a null value, then we can't identify those rows.
• A table can contain a null value other than the primary key field.
Primary Key
Emp_ ID Name Salary
Not allowed E101 ABC 20000
as Emp_ID
is a primary E102 XYZ 20000
key. PQR 18000
12/4/2019 17
Referential Integrity Constraints
Foreign Key constraint:
• A foreign key is a key used to
link two tables together.
• A Foreign Key is a column or
a combination of columns
whose values match a
Primary Key in a different
table.
• The relationship between 2
tables matches the Primary
Key in one of the tables with
a Foreign Key in the second
table.
12/4/2019 18
Referential Integrity Constraints(Cont..)
There are two type foreign key Syntax:
integrity constraints: CREATE TABLE child_table(
1. cascade delete column1 datatype [ NULL | NOT NULL ],
2. cascade update column2 datatype [ NULL | NOT NULL ], ...
1. Cascade Delete : CONSTRAINT fk_name
FOREIGN KEY (child_col1, child_col2, ...
A foreign key with cascade delete child_col_n)
means that if a record in the parent
REFERENCES parent_table (parent_col1, parent_col2,
table is deleted, then the
corresponding records in the child ... parent_col_n)
table will automatically be deleted. ON DELETE CASCADE
[ ON UPDATE { NO ACTION | CASCADE | SET
NULL | SET DEFAULT } ] );
12/4/2019 19
Referential Integrity Constraints(Cont..)
2. Cascade Update : Syntax:
A foreign key with cascade update CREATE TABLE child_table(
means that if a record in the parent column1 datatype [ NULL | NOT NULL ],
table is updates, then the column2 datatype [ NULL | NOT NULL ], ...
corresponding records in the child CONSTRAINT fk_name
table will automatically be updates. FOREIGN KEY (child_col1, child_col2, ... child_col_n)
REFERENCES parent_table (parent_col1, parent_col2,
DROP a FOREIGN KEY
... parent_col_n)
Constraint
ON DELETE CASCADE
ALTER TABLE ORDERS [ ON UPDATE { NO ACTION | CASCADE | SET
DROP FOREIGN KEY; NULL | SET DEFAULT } ] );
12/4/2019 20
Create Table example with Integrity
Constraints
create table dept (
dno int primary key,
dname varchar(20) DEFAULT “COMP”,
create table emp ( loc varchar(20) not null );
empid int primary key,
ename varchar(20) not null,
dno int,
salary numeric(8,2) check(salary >0),
aadhar int UNIQUE,
desg varchar(20) DEFAULT “cleark”,
foreign key fk1(dno) references dept (dno));
12/4/2019 21
DEPT , EMP Table
mysql> insert into dept values (100,"COMP","PUNE");
Query OK, 1 row affected (0.26 sec)
12/4/2019 22
Integrity Constraints Checks by MySQL
mysql> create table emp(empid int primary key, dno int,desg varchar(10) DEFAULT “cleark", salary numeric(5,2)
check(salary>0.0),foreign key fk3(dno) references dept(dno));
Query OK, 0 rows affected (0.70 sec)
12/4/2019 23
Integrity Constraints Checks by MySQL
mysql> insert into emp(empid,dno,salary) values (1,100,10.0);
Query OK, 1 row affected (0.32 sec)
mysql> insert into emp(empid,dno,salary) values (1,100,10.0);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
12/4/2019 24
Integrity Constraints Checks by MySQL
12/4/2019 25
Alter Command
Alter command is used for altering the table structure, such as,
1. to add a column to existing table
2. to rename any existing column
3. to change datatype of any column or to modify its size.
4. to drop a column from the table.
1. To add a column
alter table <table name> add <column name> datatype
• All exiting tuples in the relation are assigned null as the value for the new
attribute, if default value is not specified.
• E.g. ALTER TABLE Customers
ADD Email varchar(255);
12/4/2019 26
Alter Command (Cont..)
• By setting default value for new column
2. To modify a column
12/4/2019 27
Alter Command (Cont..)
E.g. ALTER TABLE student MODIFY Column(
address varchar(300));
3. To Rename a Column
12/4/2019 28
Alter Command (Cont..)
4. To drop a column
◦ Dropping of attributes not supported by many databases.
12/4/2019 29
Alter Table Examples
12/4/2019 30
Alter Table Examples
12/4/2019 31
Alter Table Examples
12/4/2019 32
Drop and Rename Command
DROP TABLE command is used to drop an existing table in a database.
12/4/2019 33
Truncate Command
12/4/2019 34
Question: Which constraint checks are
performed here
Referential Integrity
12/4/2019 35
Data Control Language (DCL)
DCL commands control the level of access that users have on database objects.
1) GRANT – provides access privileges to the users on the database objects. The privileges
could be select, delete, update and insert on the tables and views. On the procedures,
functions and packages it gives select and execute privileges.
12/4/2019 36
GRANT Command
Syntax for the GRANT command :
GRANT privilege_name ON object_name
TO {user_name | PUBLIC | role_name} [with GRANT option];
12/4/2019 38
Transaction Control Language (TCL)
TCL commands are used to manage transactions in the database.
These are used to manage the changes made to the data in a table by DML
statements.
1) Commit
2) Rollback
3) Savepoint
12/4/2019 39
TCL (Cont..)
1) Commit Command:
used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the
changes made by these commands are not permanent, until the current session
is closed, the changes made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as
permanent.
Syntax:
COMMIT;
12/4/2019 40
TCL (Cont..)
2) ROLLBACK Command:
restores the database to last committed state.
Can be used to cancel the last update made to the database, if those changes are not
committed using the COMMIT command.
Syntax:
ROLLBACK TO savepoint_name;
3) SAVEPOINT command:
used to temporarily save a transaction so that we can rollback to that point
whenever required.
Syntax:
SAVEPOINT savepoint_name;
12/4/2019 41
Data Manipulation Language (DML)
DML commands are used to make modifications of the Database like,
12/4/2019 42
INSERT Query
Add a new tuple to course
insert into course
values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
or equivalently
insert into course (course_id, title, dept_name, credits)
values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
12/4/2019 44
UPDATE Query
Increase salaries of instructors whose salary is over $100,000 by 3%, and all others by a 5%
• Write two update statements:
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
12/4/2019 45
Case Statement for Conditional Updates
Same query as before but with case statement.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end
12/4/2019 46
SELECT Query
The SELECT statement is used to select data from a database.
Syntax:
12/4/2019 47
SELECT Query (Cont..)
An asterisk in the select clause denotes “all attributes”
select ‘437’
◦ Results is a table with one column and a single row with value “437”
12/4/2019 49
Arithmetic Operations in SELECT Query
The select clause can contain arithmetic expressions involving the operation, +, –, ,
and /, and operating on constants or attributes of tuples.
o The Query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor relation, except that the
value of the attribute salary is divided by 12.
o Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary
12/4/2019 50
The WHERE Clause
The where clause specifies conditions that the result must satisfy
◦ Corresponds to the selection predicate of the relational algebra.
To find all instructors in Comp. Sci. dept
select name
from instructor
where dept_name = ‘Comp. Sci.'
Comparison results can be combined using the logical connectives and, or, and not
◦ To find all instructors in Comp. Sci. dept with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000
Comparisons can be applied to results of arithmetic expressions.
12/4/2019 51
The FROM Clause
The from clause lists the relations involved in the query
o Corresponds to the Cartesian product operation of the relational algebra.
Find the Cartesian product instructor X teaches
select *
from instructor, teaches
ogenerates every possible instructor – teaches pair, with all attributes from both
relations.
oFor common attributes (e.g., ID), the attributes in the resulting table are renamed using
the relation name (e.g., instructor.ID)
Cartesian product not very useful directly, but useful combined with where-clause
condition (selection operation in relational algebra).
12/4/2019 52
Renaming table in Select clause
The SQL allows renaming relations and attributes using the as clause:
old-name as new-name
Find the names of all instructors who have a higher salary than some instructor in
‘Comp. Sci’.
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’
12/4/2019 53
Ordering the Display of Tuples
List in alphabetic order the names of all instructors
select distinct name
from instructor
order by name
We may specify desc for descending order or asc for ascending order, for each
attribute; ascending order is the default.
Example: order by name desc
12/4/2019 54
Where Clause Predicates
SQL includes a between comparison operator
Example: Find the names of all instructors with salary between $90,000 and
$100,000 (that is, >= $90,000 and <= $100,000)
select name
from instructor
where salary between 90000 and 100000
Tuple comparison
select name, course_id
from instructor, teaches
where (instructor.ID, dept_name) = (teaches.ID, ’Biology’);
12/4/2019 55
Null Values
It is possible for tuples to have a null value, denoted by null, for some of their attributes
null signifies an unknown value or that a value does not exist.
The result of any arithmetic expression involving null is null
Example: 5 + null returns null
The predicate is null can be used to check for null values.
◦ Example: Find all instructors whose salary is null.
select name
from instructor
where salary is null
12/4/2019 56
Views
In some cases, it is not desirable for all users to see the entire logical model (that
is, all the actual relations stored in the database.)
Consider a person who needs to know an instructors name and department, but
not the salary. This person should see a relation described, in SQL, by
A view provides a mechanism to hide certain data from the view of certain users.
Any relation that is not of the conceptual model but is made visible to a user as a
“virtual relation” is called a view.
12/4/2019 57
View Definition
A view is defined using the create view statement which has the form
where <query expression> is any legal SQL expression. The view name is
represented by v.
Once a view is defined, the view name can be used to refer to the virtual relation
that the view generates.
View definition is not the same as creating a new relation by evaluating the query
expression
Rather, a view definition causes the saving of an expression; the expression is
substituted into queries using the view.
12/4/2019 58
Example of Views
A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
Find all instructors in the Biology department
select name
from faculty
where dept_name = ‘Biology’
Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;
12/4/2019 59
Inserting a new tuple into a View
Add a new tuple to faculty view which we defined earlier
insert into faculty values (’30765’, ’Green’, ’Music’);
This insertion must be represented by the insertion of the tuple
(’30765’, ’Green’, ’Music’, null)
into the instructor relation
12/4/2019 60
Update of a View
Update query is used to Update the tuples of a view.
UPDATE faculty
set dept_name=“Biology”
where name=“ABC”
Updation in view reflects the original table also. Means the changes will be done in
the original table also.
12/4/2019 61
Updatable View
VIEWs are either Updatable or Read-only, but not both.
INSERT, UPDATE, and DELETE operations are allowed on updatable VIEWs and
base tables, subject to any other constraints.
INSERT, UPDATE, and DELETE are not allowed on read-only VIEWs, but we can
change their base tables, as we would expect.
An updatable VIEW is one that can have each of its rows associated with exactly one
row in an underlying base table.
When the VIEW is changed, the changes pass unambiguously through the VIEW to
that underlying base table.
12/4/2019 62
Updatable View (cont..)
To create an updatable view, the SELECT statement that defines the view must not
contain any of the following elements:
• Aggregate functions such as MIN, MAX, SUM, AVG, and COUNT.
• DISTINCT
• GROUP BY clause.
• HAVING clause.
• UNION or UNION ALL clause.
• Left join or outer join.
• Subquery in the SELECT clause or in the WHERE clause that refers to the
table appeared in the FROM clause.
• Reference to non-updatable view in the FROM clause.
• Reference only to literal values.
• Multiple references to any column of the base table.
12/4/2019 63
Dropping a View
DROP query is used to delete a view.
Syntax:
DROP view view_name;
Example:
DROP view faculty;
12/4/2019 64
Materialized Views
Materializing a view: create a physical table containing all the tuples in the
result of the query defining the view
If relations used in the query are updated, the materialized view result becomes
out of date
◦ Need to maintain the view, by updating the view whenever the underlying
relations are updated.
12/4/2019 65
Index Creation
create table student
(ID varchar (5),
name varchar (20) not null,
dept_name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID))
create index studentID_index on student(ID)
Indices are data structures used to speed up access to records with specified values for index
attributes.
◦ e.g. select *
from student
where ID = ‘12345’
can be executed by using the index to find the required record, without looking at all records
of student.
12/4/2019 66
Set Operations
Set operations are union, intersect, and minus
◦ Each of the above operations automatically eliminates duplicates table1
To retain all duplicates use the keyword all ID NAME
◦ union all, 1 ABHI
◦ intersect all 2 SAMEER
◦ minus table2
ID NAME
◦ Select * from table1 union select * from table2;
3 JAVED
4 SAMMER
12/4/2019 67
Aggregate Functions
Type Use Functions
Single –row Operate on a single column of a relation of String functions, Date
functions single row n the table returning single value Functions
as an output
Multiple –row Act on a multiple row in the relation Min, max, avg, count,sum
functions returning single value as an output
12/4/2019 68
Aggregate Functions Examples
Find the average salary of instructors in the Computer Science department
◦ select avg (salary),min(salary), max(salary),sum(salary)
from instructor
where dept_name= 'Comp. Sci.';
Find the number of tuples in the course relation
◦ select count (*) from instructor;
12/4/2019 69
Aggregate Functions – Group By
Find the average salary of instructors in each department
◦ select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;
12/4/2019 70
Aggregation (Cont.)
Attributes in select clause outside of aggregate functions must appear in group
by list
◦ /* erroneous query */
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
12/4/2019 71
Aggregate Functions – Having Clause
Find the names and average salaries of all departments whose average salary is
greater than 42000
12/4/2019 72
Null Values and Aggregates
Total all salaries
select sum (salary )
from instructor
◦ Above statement ignores null amounts
◦ Result is null if there is no non-null amount
All aggregate operations except count(*) ignore tuples with null values on the
aggregated attributes
◦ What if collection has only null values?
◦ count returns 0
◦ all other aggregates return null
12/4/2019 73
Set Membership
Find courses offered in Fall 2017 and in Spring 2018
12/4/2019 75
Set Comparison – “some” Clause
Find names of instructors with salary greater than that of some (at least one)
instructor in the Biology department.
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept name = 'Biology';
12/4/2019 76
Set Comparison – “all” Clause
Find the names of all instructors whose salary is greater than the salary of all
instructors in the Biology department.
select name
from instructor
where salary > all (select salary
from instructor
where dept name = 'Biology');
12/4/2019 77
Test for Empty Relations
EXISTS and NOT EXISTS are used with a subquery in WHERE clause to
examine if the result the subquery returns is TRUE or FALSE.
The true or false value is then used to restrict the rows from outer query
select. Because EXISTS and NOT EXISTS only return TRUE or FALSE in the
subquery,
The SELECT list in the subquery does not need to contain actual column
name(s).
12/4/2019 78
Test for Absence of Duplicate Tuples
The unique construct tests whether a subquery has any duplicate tuples in its result.
The unique construct evaluates to “true” if a given subquery contains no duplicates .
Find all courses that were offered at most once in 2017
select T.course_id
from course as T
where unique ( select R.course_id
from section as R
where T.course_id= R.course_id
and R.year = 2017);
section(course id, sec id, semester, year, building, room number,
time slot id)
12/4/2019 79
Subqueries in the From Clause
Find the average instructors’ salaries of those departments where the average salary is greater than
$42,000.”
select dept_name, avg_salary
from ( select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
Note that we do not need to use the having clause
Another way to write above query
select dept_name, avg_salary
from ( select dept_name, avg (salary)
from instructor
group by dept_name)
as dept_avg (dept_name, avg_salary)
where avg_salary > 42000;
12/4/2019 80
With Clause
The with clause provides a way of defining a temporary relation whose definition
is available only to the query in which the with clause occurs.
Find all departments with the maximum budget
12/4/2019 81
Complex Queries using With Clause
Find all departments where the total salary is greater than the average of the total
salary at all departments
12/4/2019 82
Complex Queries using With Clause
Find all departments where the total salary is greater than the average of the total
salary at all departments
12/4/2019 83
Extensions to SQL
(PL/SQL)
What is PL/SQL
12/4/2019 85
PL/SQL Comments
12/4/2019 86
Functions and Procedures
SQL:1999 supports functions and procedures
◦ Functions/procedures can be written in SQL itself, or in an external programming
language (e.g., C, Java).
◦ Functions written in an external languages are particularly useful with specialized data
types such as images and geometric objects.
◦ Example: functions to check if polygons overlap, or to compare images for similarity.
◦ Some database systems support table-valued functions, which can return a relation as a
result.
SQL:1999 also supports a rich set of imperative constructs, including
◦ Loops, if-then-else, assignment
Many databases have proprietary procedural extensions to SQL that differ from SQL:1999.
12/4/2019 87
Stored Function
SQL Functions
Functions are declared using the following syntax:
Create function <function-name> (param_1, …, param_k)
returns <return_type>
[not] deterministic allow optimization if same output
for the same input (use RAND not deterministic )
Begin
-- execution code
end;
Define a function that, given the name of a department, returns the count of the
number of instructors in that department.
12/4/2019 90
Example 1 (Cont)..
The function dept_count can be used to find the department names and budget of all
departments with more that 12 instructors.
12/4/2019 91
Example 2
A function that returns the level of a customer based on credit limit. We use the IF
statement to determine the credit limit.
12/4/2019 92
Example 2 (Cont..)
Calling function:
we can call the CustomerLevel() in a SELECT statement as follows:
O Output:
12/4/2019 93
Example 3
12/4/2019 94
Example 3 (cont..)
12/4/2019 95
Stored Procedures
Stored Procedures in MySQL
A stored procedure contains a sequence of SQL commands stored in the database
catalog so that it can be invoked later by a program
Stored procedures are declared using the following syntax:
Create Procedure <proc-name>
(param_spec1, param_spec2, …, param_specn )
begin
-- execution code
end;
where each param_spec is of the form:
[in | out | inout] <param_name> <param_type>
◦ in mode: allows you to pass values into the procedure,
◦ out mode: allows you to pass value back from procedure to the calling program
12/4/2019 97
Example 1 – No parameters
The GetAllProducts() stored procedure selects all products from the products
table.
12/4/2019 98
Example 1 (Cont..)
Calling Procedure:
CALL GetAllProducts();
Output:
12/4/2019 99
Example 2 ( with IN parameter)
Suppose we want to keep track of the total salaries of employees working for each department
12/4/2019 101
Example 2 (Cont..)
Step 3: Call the procedure to update the totalsalary for each department
12/4/2019 102
Example 2 (Cont..)
12/4/2019 103
Example 3 (with OUT Parameter)
The following example shows a simple stored procedure that uses an OUT
parameter.
Within the procedure MySQL MAX() function retrieves maximum salary from
MAX_SALARY of jobs table.
12/4/2019 104
(Cont..)
Procedure Call:
mysql> CALL my_proc_OUT(@M)$$
Query OK, 1 row affected (0.03 sec)
mysql< SELECT @M$$
Output:
+-------+
| @M |
+-------+
| 40000 |
+-------+
1 row in set (0.00 sec)
12/4/2019 105
Example 4 (with INOUT Parameter)
The following example shows a simple stored procedure that uses an INOUT
parameter.
‘count’ is the INOUT parameter, which can store and return values and ‘increment’
is the IN parameter, which accepts the values from user.
12/4/2019 106
Example 4 (Cont..)
Function
Call:
12/4/2019 107
Stored Procedures (Cont..)
Use show procedure status to display the list of stored procedures you have created
12/4/2019 108
Language Constructs for Procedures &
Functions
SQL supports constructs that gives it almost all the power of a general-purpose
programming language.
oWarning: most database systems implement their own variant of the standard
syntax below.
Compound statement: begin … end,
oMay contain multiple SQL statements between begin and end.
oLocal variables can be declared within a compound statements
12/4/2019 109
Language Constructs
CASE Statement
CASE case_expression
WHEN when_expression_1 THEN commands
WHEN when_expression_2 THEN commands
...
ELSE commands
END CASE;
12/4/2019 112
Cursors
Cursors
To handle a result set inside a stored procedure, we use a cursor.
A cursor allows us to iterate a set of rows returned by a query and process each
row accordingly.
The set of rows the cursor holds is referred to as the active set.
12/4/2019 114
Cursors
2. Next, open the cursor by using the OPEN statement.
3. Then, use the FETCH statement to retrieve the next row pointed by the cursor and
move the cursor to the next row in the result set.
4. Finally, call the CLOSE statement to deactivate the cursor and release the memory
associated with it as follows:
12/4/2019 115
Cursors
The following diagram illustrates how MySQL cursor works.
12/4/2019 116
Example using Cursors
Example 2 in stored procedure updates one row in deptsal table based on input
parameter.
Suppose we want to update all the rows in deptsal simultaneously.
◦ First, let’s reset the totalsalary in deptsal to zero.
12/4/2019 117
Example using Cursors
12/4/2019 118
Example using Cursors
Call procedure :
12/4/2019 119
Another Example
Create a procedure to give a raise to all employees
12/4/2019 120
Another Example (Cont..)
12/4/2019 121
Another Example (Cont..)
12/4/2019 122
Triggers
Triggers
A trigger is a statement that is executed automatically by the system as a side effect
of a modification to the database i.e. when changes are made to the table.
To monitor a database and take a corrective action when a condition occurs
Examples:
• Charge $10 overdraft fee if the balance of an account after a withdrawal
transaction is less than $500
• Limit the salary increase of an employee to no more than 5% raise
SQL triggers provide an alternative way to check the integrity of data.
12/4/2019 124
Triggering Events and Actions in SQL
A trigger can be defined to be invoked either before or after the data is changed
by INSERT, UPDATE or DELETE .
MySQL allows you to define maximum six triggers for each table.
BEFORE INSERT – activated before data is inserted into the table.
AFTER INSERT- activated after data is inserted into the table.
BEFORE UPDATE – activated before data in the table is updated.
AFTER UPDATE - activated after data in the table is updated.
BEFORE DELETE – activated before data is removed from the table.
AFTER DELETE – activated after data is removed from the table.
12/4/2019 125
MySQL Trigger Syntax
12/4/2019 126
MySQL Trigger Example 1
Create a BEFORE
UPDATE trigger that is
invoked before a
change is made to the
employees table.
In a trigger defined for INSERT, you can use NEW keyword only. You
cannot use the OLD keyword.
However, in the trigger defined for DELETE, there is no new row so you
can use the OLD keyword only.
In the UPDATE trigger, OLD refers to the row before it is updated and
NEW refers to the row after it is updated.
12/4/2019 128
MySQL Trigger Syntax
Update the employees table to check whether the trigger is invoked.
12/4/2019 129
MySQL Trigger Syntax
The following is the output of the query:
12/4/2019 130
Example 2
12/4/2019 131
Example 2 (Cont..)
Create a trigger to update the total salary of a department when a new employee is hired:
12/4/2019 132
Example 2 (Cont..)
12/4/2019 133
MySQL Trigger
To list all the triggers we have created:
mysql> show triggers;
To drop a trigger
mysql> drop trigger <trigger name>
12/4/2019 134
Query Processing and
Optimization
12/4/2019 135
Basic Steps in Query Processing
1. Parsing and translation
2. Optimization
3. Evaluation
12/4/2019 136
Basic Steps in Query Processing(Contd..)
Parsing and translation
◦ translate the query into its internal form. This is then translated into
relational algebra.
◦ Parser checks syntax, verifies relations
Evaluation
◦ The query-execution engine takes a query-evaluation plan, executes that
plan, and returns the answers to the query.
12/4/2019 137
Basic Steps in Query Processing : Optimization
A relational algebra expression may have many equivalent expressions
◦ E.g., salary75000(salary(instructor)) is equivalent to
salary(salary75000(instructor))
Each relational algebra operation can be evaluated using one of several different
algorithms
◦ Correspondingly, a relational-algebra expression can be evaluated in many
ways.
Annotated expression specifying detailed evaluation strategy is called an
evaluation-plan.
◦ E.g., can use an index on salary to find instructors with salary < 75000,
◦ or can perform complete relation scan and discard instructors with salary
75000
12/4/2019 138
Basic Steps: Optimization (Cont.)
Query Optimization:
Amongst all equivalent evaluation plans choose the one with lowest cost.
◦ Cost is estimated using statistical information from the
database catalog
◦ e.g. number of tuples in each relation, size of tuples, etc.
Thus we will study
◦ How to measure query cost
12/4/2019 139
Measures of Query Cost (Cont.)
For simplicity we just use the number of block transfers from disk and
the number of seeks as the cost measures
◦ tT – time to transfer one block
◦ tS – time for one seek
◦ Cost for b block transfers plus S seeks
b * tT + S * tS
Here ignore CPU costs for simplicity
◦ Real systems do take CPU cost into account
here do not include cost to writing output to disk in our cost formulae
12/4/2019 140
Measures of Query Cost
Cost is generally measured as total elapsed time for answering query
◦ Many factors contribute to time cost
◦ disk accesses, CPU, or even network communication
Typically disk access is the predominant cost, and is also relatively easy to
estimate. Measured by taking into account
◦ Number of seeks * average-seek-cost
◦ Number of blocks read * average-block-read-cost
◦ Number of blocks written * average-block-write-cost
◦ Cost to write a block is greater than cost to read a block
◦ data is read back after being written to ensure that the write was
successful.
12/4/2019 141
Measures of Query Cost (Cont.)
12/4/2019 142
References
12/4/2019 143