Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 143

DBMS-Unit II

Database Languages and


Programming

S C H OOL O F C O M P U TER EN G I N EER IN G A N D TEC H N OLOGY


Syllabus
Introduction to SQL: Characteristics and advantages of SQL, SQL Data Types
DDL Commands, DCL Commands.
SQL Queries: DML Queries with Select Query Clauses, Creating, Modifying,
Deleting.
Views: Creating, Dropping, Updating, Indexes,
SQL DML Queries: Set Operations, Predicates and Joins, Set membership,
Grouping and Aggregation, Aggregate Functions, Nested Queries,
PL/SQL Concepts: PL/SQL Functions and Procedures, Cursors, Database Triggers.
Query Processing and Optimization.

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…

 Easy to learn and understand


 Portable: SQL can be run on any platform, Databases using SQL can be moved from a
device to another without any problems.
Supports Object based programming: SQL supports various object oriented
programming concepts which makes it powerful.
 Multiple data views: Different views of contents of a database to different users.

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

 The most widely used commercial language.

 To be able to compute complex functions SQL is usually embedded in some higher-


level language.

 Application programs generally access databases through one of


 Language extensions to allow embedded SQL

 Application program interface (e.g., ODBC/JDBC) which allow SQL queries to be


sent to a database.

12/4/2019 9
SQL language statements

 Data Definition Language (DDL)


 Data Manipulation Language (DML)
 Data Control Language (DCL)
 Transaction Control Language (TCL)

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

 An SQL relation is defined using the create table command:


create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
Example:
create table instructor (
ID char(5),
name varchar(20),
dept_name varchar(20),
salary decimal(8,2))

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 :

1. NOT NULL : Roll_No Name


• Ensures that a column cannot have NULL value.
1 ABC
NULL value is 2 XYZ
not allowed
3

12/4/2019 14
Domain Integrity Constraints (Cont..)
2. Unique Constraint :
• Ensures that all values in a column are different.

Emp_ ID Name Salary


Not allowed
as Emp_ID E101 ABC 20000
has unique E102 XYZ 20000
constraint
E102 PQR 18000

Roll_No Name Marks


3. Default Constraint: 1 ABC NULL
• Provides a default value for a column when none is specified. 2 XYZ NULL

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)

mysql> insert into emp(empid,dno,salary) values (1,100,0);


ERROR 3819 (HY000): Check constraint 'emp_chk_1' is violated.

mysql> insert into emp(empid,dno,salary) values (1,10,10.0);


ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`db5`.`emp`, CONSTRAINT
`emp_ibfk_1` FOREIGN KEY (`dno`) REFERENCES `dept` (`dno`))

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'

mysql> insert into emp(empid,dno,salary) values (3,100,10.0);


Query OK, 1 row affected (0.18 sec)

mysql> select * from emp;


+-------+------+--------+--------+
| empid | dno | desg | salary |
+-------+------+--------+--------+
| 3 | 100 | Cleark | 10.00 |
+-------+------+--------+--------+
1 row in set (0.00 sec)

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

ALTER TABLE table_name ADD(column-name1 datatype1


DEFAULT some_value);

E.g. ALTER TABLE student ADD(


dob DATE DEFAULT '01-Jan-99‘ );

2. To modify a column

ALTER TABLE table_name modify Column(column_name datatype);

12/4/2019 27
Alter Command (Cont..)
E.g. ALTER TABLE student MODIFY Column(
address varchar(300));

3. To Rename a Column

ALTER TABLE table_name RENAME


old_column_name TO new_column_name;

E.g. ALTER TABLE student RENAME


address TO location;

12/4/2019 28
Alter Command (Cont..)
4. To drop a column
◦ Dropping of attributes not supported by many databases.

ALTER TABLE table_name DROP Column(


column_name);

◦ E.g. ALTER TABLE Customers


DROP COLUMN Email;

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.

 In DCL we have two commands,


1. GRANT: Used to provide any user access privileges or other privileges for the
database.
2. REVOKE: Used to take back permissions from any user.

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];

 Allow User to create table:


To allow a user to create tables in the database, we can use the below command,
GRANT CREATE TABLE TO username;
 Grant Select privileges to user on customer table:
GRANT SELECT ON customer TO username;
 Grant permission to drop any table:
GRANT DROP ANY TABLE TO username;
 To GRANT ALL privileges to a user
GRANT ALL PRIVILEGES ON database_name TO username
12/4/2019 37
REVOKE Command
 Syntax for the REVOKE command:
REVOKE privilege_name ON object_name
FROM {User_name | PUBLIC | Role_name}

 To take back Permissions from user


REVOKE CREATE TABLE FROM username;
 Revoke SELECT privilege on employee table from user1.
REVOKE SELECT ON employee FROM user1;

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,

 Deletion of tuples from a given relation.


 Insertion of new tuples into a given relation
 Updation of values in some tuples in a given relation

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);

 Add a new tuple to student with tot_creds set to null


insert into student
values (’3003’, ’Green’, ’Finance’, null);
12/4/2019 43
DELETE Query
 Delete all instructors
delete from instructor;

 Delete all instructors from the Finance department


delete from instructor
where dept_name= ’Finance’;

 Delete all tuples in the student relation.


delete from student;

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;

• Can be done better using the case statement (next slide)

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:

SELECT column1, column2, ...


FROM table_name;

E.g. SELECT * FROM Student;

◦ The result of an SQL query is a relation.

12/4/2019 47
SELECT Query (Cont..)
 An asterisk in the select clause denotes “all attributes”

select * from instructor

 An attribute can be a literal with no from clause

select ‘437’
◦ Results is a table with one column and a single row with value “437”

◦ Can give the column a name using:

select ‘437’ as FOO


12/4/2019 48
SELECT Query (Cont..)

 An attribute can be a literal with from clause

select ‘A’ from instructor


◦ Result is a table with one column and N rows (number of tuples in the instructors
table), each row with value “A”.

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.’

 Keyword as is optional and may be omitted


instructor as T ≡ instructor T

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

 Can sort on multiple attributes


Example: order by dept_name, name

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

select ID, name, dept_name


from instructor

 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

create view v as < query expression >

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

avg: average value


min: minimum value
max: maximum value
sum: sum of values
count: number of values

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;

Discuss why query is erroneous, [Hint :refer last table]

12/4/2019 71
Aggregate Functions – Having Clause

Find the names and average salaries of all departments whose average salary is
greater than 42000

select dept_name, avg (salary) as avg_salary


from instructor
group by dept_name
having avg (salary) > 42000;

Note: predicates in the having clause are applied


after the formation of groups whereas predicates in the
where clause are applied before forming groups

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

select distinct course_id


from section
where semester = 'Fall' and year= 2017 and
course_id in (select course_id section (course id , sec id , semester ,
from section year , building , room number , time
where semester = 'Spring' and year= 2018); slot id varchar (4), primary key (course
Find courses offered in Fall 2017 but not in Spring 2018 id, sec id, semester,year), foreign key
select distinct course_id
(course id) references course);
from section
where semester = 'Fall' and year= 2017 and
course_id not in (select course_id
from section
where semester = 'Spring' and year=
2018);
12/4/2019 74
Set Membership (Cont.)
 Name all instructors whose name is neither “Mozart” nor Einstein”

select distinct name


from instructor
where name not in ('Mozart', 'Einstein')

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';

Same query using > some clause


select name
from instructor
where salary > some (select salary
from instructor
where 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

with max_budget (value) as


(select max(budget)
from department)
select department.name
from department, max_budget
where department.budget = max_budget.value;

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

with dept _total (dept_name, value) as


(select dept_name, sum(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value > dept_total_avg.value;

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

with dept _total (dept_name, value) as


(select dept_name, sum(salary)
from instructor
group by dept_name),
dept_total_avg(value) as
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value > dept_total_avg.value;

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;

where param is:


[in | out | in out] <param_name> <param_type>
 You need ADMIN privilege to create functions on mysql-user server
12/4/2019 89
SQL Functions – Example 1

 Define a function that, given the name of a department, returns the count of the
number of instructors in that department.

create function dept_count (dept_name varchar(20))


returns integer
begin
declare d_count integer;
select count (* ) into d_count
from instructor
where instructor.dept_name = dept_name
return d_count;
end

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.

select dept_name, budget


from department
where dept_count (dept_name ) > 12

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

We need to write a procedure


to update the salaries in
the deptsal table
12/4/2019 100
Example 2 (Cont..)

1. Define a procedure called updateSalary which takes as input a department number.


2. The body of the procedure is an SQL command to update the totalsalary column of
the deptsal table.

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..)

Step 4: Show the updated total salary in the deptsal table

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.

mysql> CREATE PROCEDURE my_proc_OUT (OUT highest_salary INT)


-> BEGIN
-> SELECT MAX(MAX_SALARY) INTO highest_salary FROM JOBS;
-> END$$
Query OK, 0 rows affected (0.00 sec)

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

 Use drop procedure to remove a stored procedure

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;

 While and repeat statements: repeat


while boolean expression do sequence of statements ;
sequence of statements ; until boolean expression
end while end repeat
12/4/2019 110
Language Constructs (Cont.)
 Loop, Leave and Iterate statements…
◦ Permits iteration over all results of a query.
loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
12/4/2019 111
Exception Handling
 Conditional statements (if-then-else)
 Example procedure: registers student after ensuring classroom capacity is not exceeded
◦ Returns 0 on success and -1 if capacity is exceeded
 Signaling of exception conditions, and declaring handlers for exceptions
declare out_of_classroom_seats condition
declare exit handler for out_of_classroom_seats
begin

.. signal out_of_classroom_seats
end
◦ The handler here is exit -- causes enclosing begin..end to be exited
◦ Other actions possible on exception

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.

1. We can declare a cursor by using the DECLARE statement:

• The cursor declaration must be after any variable declaration.


• A cursor must always be associated with a SELECT statement.

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

Drop the old procedure

Use cursor to iterate the rows

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.

 we used the OLD


keyword to access
employeeNumber and
lastname column of the
row affected by the
trigger.
12/4/2019 127
Continued…

 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.

 Finally, to check if the trigger was invoked by the UPDATE statement, we


can query the employees_audit table using the following query:

12/4/2019 129
MySQL Trigger Syntax
 The following is the output of the query:

12/4/2019 130
Example 2

We want to create a trigger to update the total salary of a department when a


new employee is hired

12/4/2019 131
Example 2 (Cont..)
Create a trigger to update the total salary of a department when a new employee is hired:

The keyword “new” refers to the new row inserted

12/4/2019 132
Example 2 (Cont..)

totalsalary increases by 90K

totalsalary did not change

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., salary75000(salary(instructor)) is equivalent to
salary(salary75000(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.)

 Several algorithms can reduce disk IO by using extra buffer space


◦ Amount of real memory available to buffer depends on other concurrent
queries and OS processes, known only during execution
◦ We often use worst case estimates, assuming only the minimum amount of
memory needed for the operation is available
 Required data may be buffer resident already, avoiding disk I/O
◦ But hard to take into account for cost estimation

12/4/2019 142
References

1. Silberschatz−Korth−Sudarshan's Database System Concepts, Seventh Edition.


2. MySQL Tutorial
http://www.mysqltutorial.org/

12/4/2019 143

You might also like