18csc303j Dbms Unit III
18csc303j Dbms Unit III
Management Systems
13/12/2024 1
Outline of the Presentation
S-1 SLO-1 : Basics of SQL-DDL,DML,DCL,TCL
SLO-2 : Structure Creation, alternation
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key, Foreign Key, Unique,
not null, check, IN operator
S-3 SLO-1 : Functions-aggregation functions
SLO-2 : Built-in Functions- Numeric, Date, String functions, Set operations
S 4-5 SLO-1 & SLO-2 : Lab 7 : Join Queries on sample exercise.
S-6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
S-8 SLO-1 : Transaction Control Commands
SLO-2 : Commit, Rollback, Savepoint
S-9-10 SLO-1 & SLO-2 : Lab 8: Set Operators & Views.
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions Triggers and Exceptional Handling
S-13 SLO-1 & SLO-2 : Query Processing
S-14-15SLO-1 & SLO-2 : Lab9: PL/SQL Conditional and Iterative Statements
13/12/2024 2
S-1 SLO-1 : Basics of SQL-DDL,DML,DCL,TCL
13/12/2024 3
S-1 SLO-2 : Structure Creation, alternation
DDL relates only with base tables structure and it is no where relates with the
information stored in the table.
Note : All the DDL command statements are AUTO COMMIT Statements
– CREATE
– ALTER
– DROP
– TRUNCATE
13/12/2024 4
S-1 SLO-2 : Structure Creation, alternation
Data Definition Language (DDL)
CREATE COMMAND
Used to create a new object / schema with a defined structure
Syntax :
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Example :
13/12/2024 5
S-1 SLO-2 : Structure Creation, alternation
13/12/2024 6
S-1 SLO-2 : Structure Creation, alternation
Data Definition Language (DDL)
ALTER COMMAND
SYNTAX
13/12/2024 7
S-1 SLO-2 : Structure Creation, alternation
Example :
13/12/2024 8
S-1 SLO-2 : Structure Creation, alternation
DROP COMMAND
It is used to remove the base table with records (information) from database
permanently.
Syntax:
Example:
13/12/2024 9
S-1 SLO-2 : Structure Creation, alternation
TRUNCATE COMMAND
Truncate command used to delete the records (information) from the
base table permanently and keeps the structure of the base table
alone
Syntax:
Example:
13/12/2024 10
S-1 SLO-2 : Structure Creation, alternation
DML Commands are relates only with base table information ( value in an attribute)
There are four commands in DML:
1. INSERT
2. UPDATE
3. DELETE
4. SELECT
INSERT COMMAND
It relates only with new records.
Only one row can be inserted at a time
Multiple rows can be inserted using “&” symbol one by one
Can insert to entire table
Can insert in selected columns with some restrictions
Must follow the order of the column specified in the query statement
13/12/2024 12
S-1 SLO-2 : Structure Creation, alternation
INSERT COMMAND
Syntax:
13/12/2024 13
S-1 SLO-2 : Structure Creation, alternation
INSERT COMMAND
INSERT INTO EMP VALUES (7369, 'SMITH', 'CLERK', 7902, '17-12-1980‘, 800, NULL,
20);
(OR)
INSERT INTO EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
VALUES (7369, 'SMITH', 'CLERK', 7902, '17-12-1980', 800, NULL, 20);
The input value will be store in the appropriate field using bind
variable ( :OLD and :NEW)
13/12/2024 15
S-1 SLO-2 : Structure Creation, alternation
Update command
It works with only existing records
It works only column wise
It is used to modify the column values ( increase / decrease / change)
Syntax
UPDATE <table_name> set <field_name> = value [ where <condition>];
Note : Update command without where condition will update all the records.
Update command with where condition will update the records which are satisfy
the condition
Example 1:
UPDATE emp set comm = 2000 ; ( Update all the records in EMP table )
Example 2 :
Update emp set comm = 1000 where empno = 7369;
(Update the records having the empno as 7369)
13/12/2024 16
S-1 SLO-2 : Structure Creation, alternation
Delete command
It works only with existing records
It works only with row wise
It not possible to delete a single column in a row
Syntax
DELETE from <table_name> [ where <condition>];
Note : Delete command with out where condition will delete all the records in the table.
Delete command with where condition will delete the selected records which
are
satisfy the condition.
Example 1: DELETE from emp; ( All records will be deleted from emp )
Example 2: DELETE from emp where empno = 7369;
( Those records holding the value in the field empno as 7369 will be
deleted )
13/12/2024 17
S-1 SLO-2 : Structure Creation, alternation
SELECT COMMAND
13/12/2024 18
S-1 SLO-2 : Structure Creation, alternation
SELECT COMMAND
Syntax
SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
NOTE : To retrieve all the column from the table ‘ * ’ symbol can be
used instead of specifying the column_list.
13/12/2024 19
S-1 SLO-2 : Structure Creation, alternation
SELECT COMMAND
Example 1: To retrieve all the columns and rows from emp table
SELECT * from emp; ( ‘*’ stands from all columns and rows )
Example 3: To retrieve the records from emp table which record holds the salary value
greater than 1000;
SELECT * from emp WHERE sal> 1000;
Example 4: To retrieve the columns empno and ename from emp table which records
holds the value as CLERK in job column.
SELECT empno, ename from emp WHERE job = ‘CLERK’
13/12/2024 20
S-1 SLO-2 : Structure Creation, alternation
SELECT COMMAND
Select command with order by clause
Example 5 : To retrieve the records from emp table in
ascending order using empno
SELECT * from emp order by empno asc;
(OR)
SELECT * from emp order by empno;
Example 6: To retrieve the records from emp table in
ascending order using job and empno
SELECT * from emp order by job,empno asc;
(OR)
SELECT * from emp order by job,empno;
NOTE : Ascending order is default condition, no need to specify
13/12/2024 21
S-1 SLO-2 : Structure Creation, alternation
SELECT COMMAND
Select command with order by clause
Example 7 : To retrieve the records from emp table in descending order using
empno.
SELECT * from emp order by empno desc;
Example 8: To retrieve the records from emp table in descending order using job
and empno
SELECT * from emp order by job desc,empno desc;
Example 8: To retrieve the records from emp table in ascending order using job
and descending order empno
SELECT * from emp order by job asc,empno desc;
13/12/2024 22
S-1 SLO-2 : Structure Creation, alternation
SELECT COMMAND
Select command with group by clause
Example 9: To retrieve the different jobs from emp table
SELECT job from emp group by job;
Example 10: To retrieve the different jobs and its average salary from emp
table
SELECT job, avg(sal) from emp group by job;
13/12/2024 23
S-1 SLO-2 : Structure Creation, alternation
on <OBJECT_NAME> to <USER_NAME>;
REVOKE : To get back all the privileges from the user who has been granted
13/12/2024 24
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Constraint
Purpose
Use a constraint to define an integrity constraint--a rule that
restricts the values in a database.
Oracle Database lets you create five types of constraints and lets
you declare them in two ways.
There five types of integrity constraint
• NOT NULL constraint
• Unique constraint
• Primary key constraint
• Foreign key constraint
• Check constraint
13/12/2024 25
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
13/12/2024 26
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Not Null Constraint
NOT NULL constraint prohibits a database value from being null.
To satisfy a NOT NULL constraint, every row in the table must contain a value for the
column.
For example: Every user should have a username. So we would define the "Username"
column as NOT NULL
You cannot specify NULL or NOT NULL for an attribute of an object. Instead, use
a CHECK constraint with the IS [NOT] NULL condition.
13/12/2024 27
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Syntax for Not Null constraint
Create table <table_name> ( column_1 datatype Constraint <constraint_name>
<constraint_type>,
column_2 datatype,
………..
……….
column_n datatype);
Example
Create table emp ( empno number constraint my_cons_NN not null,
ename varchar2(10), sal number(10), dept varchar2(10));
Note : Constraints may specified without name also, in that case system
automatically assign some random name.
Create table emp ( empno number(10) not null, ename varchar2(10),
sal number(10), dept varchar2(10));
13/12/2024 28
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Unique Constraint
A unique constraint designates a column as a unique key.
A composite unique key designates a combination of columns as the
unique key.
To satisfy a unique constraint, no two rows in the table can have the
same value for the unique key.
Unique constraint allows null values and it allows more number of null
values (Two null values are always not equal ).
13/12/2024 29
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
13/12/2024 30
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Syntax for unique constraint
Primary Key
A primary key constraint designates a column as the primary key of
a table or view.
A composite primary key designates a combination of columns as
the primary key.
A primary key constraint combines a NOT NULL and unique
constraint in one declaration
Therefore, to satisfy a primary key constraint:
• No primary key value can appear in more than one row in the
table.
• No column that is part of the primary key can contain a null.
13/12/2024 32
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Restrictions on Primary Key Constraints
A table or view can have only one primary key.
None of the columns in the primary key can be LOB , LONG , LONG RAW , VARRAY,
NESTED TABLE , BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type.
The size of the primary key cannot exceed approximately one database block.
A composite primary key cannot have more than 32 columns.
You cannot designate the same column or combination of columns as both a
primary key and a unique key.
13/12/2024 33
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Syntax for Primary key constraint
The table or view containing the foreign key is called the child object, and the table or
view containing the referenced key is called the parent object.
The foreign key and the referenced key can be in the same table or view.
To satisfy a composite foreign key constraint, the composite foreign key must refer to a
composite unique key or a composite primary key in the parent table or view, or the
value of at least one of the columns of the foreign key must be null.
13/12/2024 36
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Syntax for Foreign Key
CREATE TABLE <child_table_name> ( column_1 datatype,
column_1 datatype ,
-------
Dept_id references <parent_table_name>
(Parent_table_Primary key));
Example
CREATE TABLE emp ( empno number (10) Primary key,
ename varchar2(25),
salary number(10,2),
dept_id references DEPT (DEPT_ID));
An entity emp created with foreign key constraint referencing dept entity
primary key attribute dept_id.
13/12/2024 37
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Check Constraint
A check constraint lets you specify a condition that each row in the table must satisfy.
To satisfy the constraint, each row in the table must make the condition either TRUE or
NULL
The condition of a check constraint can refer to any column in the table, but it cannot
13/12/2024 38
S-2 SLO-1 & SLO-2: Defining Constraints-Primary Key,
Foreign Key, Unique, Not null, Check, IN operator
Syntax for Check Constraint
Create table <table_name> ( column_1 datatype Constraint <constraint_name>
<constraint_type> (condition),
column_2 datatype,
………..
……….
column_n datatype);
Example
Create table emp ( empno number(10) , ename varchar2(10),
sal number(10) constraint my_cons_ck (sal
>10000) dept varchar2(10));
13/12/2024 39
S3 SLO-1 : Functions - aggregation functions
Aggregation Functions
MAX – To find the number of the maximum values in the SQL table.
MIN – Number of the minimum values in the table.
COUNT – Get the number of count values in the SQL table.
AVG – Find average values in the SQL table.
SUM – Return the summation of all non-null values in the SQL table.
DISTINCT – Return the distinct values of a column.
13/12/2024 40
S3 SLO-1 : Functions - aggregation functions
Max Function
Syntax: Max( Column_name)
Example : Select max(sal) from emp;
Min Function
Syntax : Min(Column_name)
Example : Select min(sal) from emp;
Avg Function
Syntax : Avg( Column_name)
Example : Select avg(sal) from emp;
13/12/2024 41
S3 SLO-1 : Functions - aggregation functions
Sum Function
Syntax : Sum(Column_name)
Example : Select sum(sal) from emp;
Count Function
Syntax : Count(Column_name)
Example : Select count(sal) from emp;
Note : (1) When Count (*) is used , it will count the number of
rows using rowid value ( Rowid is the unique id and it is
a 16bit hexa decimal number for all the rows
assigned at the time of creation)
(2) When Count (Column_name) is used, it will count the
number of values in a specified column except null values
13/12/2024 42
S3 SLO-1 : Functions - aggregation functions
Distinct Function
Syntax : Distinct ( Column_name)
Example : Select distinct (job) from emp;
STDDEV Function
Syntax : Stddev ( Column_name)
Example : Select stddev(sal) from emp;
Variance Function
Syntax : Variance (Coulmn_name)
Example : Select variance (sal) from emp;
13/12/2024 43
S3 SLO-1 : Functions - aggregation functions
Some more examples using EMP table
Select sum(sal), avg(sal), min(sal), max(sal) from emp;
13/12/2024 45
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Numeric Functions
Functions Value Returned Example
Power(m,n) m power n Select power(5,3) from dual;
13/12/2024 46
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Date Functions
Functions Value Returned Example
add_months(d,n) ‘n’ months added to date ‘d’. Select add_months(sysdate,2) from dual;
13/12/2024 47
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Date Functions
Functions Value Returned Input
Select round(sysdate,’year’) from dual;
Date will be the rounded to Select round(sysdate,’month’) from dual;
round(d,’format’) nearest day.
Select round(sysdate,’day’) from dual;
Select round(sysdate) from dual;
Select trunc(sysdate,’year’) from dual;
Date will be the truncated to Select trunc(sysdate,’month’) from dual;
trunc(d,’format’) nearest day.
Select trunc(sysdate,’day’) from dual;
Select trunc(sysdate) from dual;
greatest(d1,d2, Select greatest(sysdate, to_date(‘02-10- 06’,’dd-mm-
…) Picks latest of list of dates
yy’),to-date(’12-07- 12’,’dd-mm-yy’)) from dual;
Select sysdate+25 from dual;
Add /Subtract no. of days to a date
Select sysdate-25 from dual;
Date Arithmetic
Subtract one date from another, Select sysdate - to_date(‘02-10-06’,’dd- mm-yy’) from
producing a no. of days dual;
13/12/2024 48
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
String Functions
Functions Value Returned Input
13/12/2024 49
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Set Operators
Set operators are used to join the results of two (or more)
SELECT statement.
The following set operators are available in SQL
• Union
• Union All
• Intersect
• Minus
13/12/2024 50
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Set Operators
Union operator retrieves the records from both queries without
duplicate.
In the union operation, all the number of datatype and columns
must be same in both the tables on which UNION operation is
being applied.
Union All retrieves all the records from both queries (with
duplicate).
Intersect operator retrieve the common records from both query
statements.
Minus operator retrieve the records from first query , the records
13/12/2024 51
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Set Operators
Point to be followed while using SET operators
The number of columns must be same in all participating query
Column heading will be selected from the first query for displaying the output.
Data types of the column list must be match with all the query.
Positional ordering must be used to sort the result set.
UNION and INTERSECT operators are commutative, i.e. the order of queries is not
important; it doesn't change the final result.
Set operators can be the part of sub queries.
Set operators can't be used in SELECT statements containing TABLE collection
expressions.
The LONG, BLOB, CLOB, BFILE, VARRAY,or nested table are not permitted for use
in Set operators.
For update clause is not allowed with the set operators.
13/12/2024 52
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Create two tables named a and b with the columns f1,f2 and
id,name respectively
13/12/2024 53
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Insert three rows as given below in tables a and b
13/12/2024 55
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Example 1 : Union Example 2 : Union
Sql> select f1 from a Sql> select id from b
union union
select id from b; select f1 from a;
13/12/2024 56
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
Example : Union All
Sql>select f1 from a union all select id from b
13/12/2024 57
S3 SLO-2 : Built-in Functions-Numeric, Date,
String functions, Set operations
Examples: Set Operators
13/12/2024 58
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
Joins
SQL Joins are used to fetch records from two are more tables using a common field.
A join is an operation that combines the rows of two or more tables based on related
columns.
This operation is used for retrieving the data from multiple tables simultaneously
using common columns of tables.
To implement join condition minimum two tables are required
Join conditions used in where clause as given below
Note : Column name used in where condition need not to same , but data type
should be same.
13/12/2024 59
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
13/12/2024 60
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
• Self Join - a self join is a regular join that is used to join a table with itself
• Outer Join - Left Outer Join retrieves all records from the
left table and retrieves matching records from the right table.
- Right Outer Join retrieves all records from the right
table and retrieves matching records from the left table.
13/12/2024 61
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
• Left Outer Join returns all the rows from the table on the left even if no
matching rows have been found in the table on the right. When no matching
record is found in the table on the right, NULL is returned.
13/12/2024 62
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
• Right outer join returns all the columns from the table on the right even if no matching rows
have been found in the table on the left. Where no matches have been found in the table on
the left, NULL is returned. RIGHT outer JOIN is the opposite of LEFT JOIN
13/12/2024 63
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
• In a Full Outer Join , all tuples from both relations are included
in the result, irrespective of the matching condition.
13/12/2024 64
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
Note : Consider EMP and Dept Tables
Simple Join
For the below query the output is cartesian prodcut
13/12/2024 65
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
Simple Join
Syntax : where <table_name1>.<column_name> =
<table_name2>.<column_name>
Example 1:
Sql> select * from emp,dept where emp.deptno=
dept.deptno;
Example 2:
Sql> select ename,dname from emp,dept where
emp.deptno= dept.deptno;
13/12/2024 66
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
Simple Join
13/12/2024 67
S 4-5 SLO-1 & SLO-2 :
Lab 7 : Join Queries on sample exercise.
Simple Join
Example :
Sql> select a.ename,b.ename,a.empno,b.empno from emp a,
emp b where b.mgr=a.empno;
Outer Join
Example: (Right Outer Join)
Sql> select * from emp ,dept where emp.deptno =
dept.deptno(+);
Example: (Left Outer Join)
Sql> select * from emp ,dept where emp.deptno (+) =
dept.deptno;
13/12/2024 68
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
A Query statement contains another query is called sub query or nested query
A subquery is used to return value(s) that will be used in the main query as a condition
Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
• Subqueries that return more than one row can only be used with multiple value
• The BETWEEN operator cannot be used with a subquery, but the BETWEEN operator can
13/12/2024 69
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
13/12/2024 70
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
Note : Consider emp table
Example : Subqueries with the SELECT Statement
SQL> SELECT * FROM emp WHERE deptno IN (SELECT deptno FROM dept WHERE
dname = ‘SALES’ or dname = ‘RESEARCH’) ;
13/12/2024 71
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
Sample Sub queries
SELECT ename FROM EMP WHERE sal > ( SELECT sal FROM emp WHERE empno=7566);
SELECT ename, sal, deptno, job FROM EMP WHERE job = SELECT job FROM emp WHERE empno=7369);
SELECT ename, sal, deptno FROM EMP WHERE sal IN ( SELECT MIN(sal) FROM emp GROUP BY deptno );
SELECT empno, ename, job FROM emp WHERE sal < ANY ( SELECT sal FROM emp WHERE job = 'CLERK' );
SELECT empno, ename, job FROM emp WHERE sal > ALL ( SELECT AVG(sal) FROM emp GROUP BY deptno)
;
SELECT ename, sal, deptno FROM EMP WHERE sal IN ( SELECT MIN(sal) FROM emp GROUP BY deptno ) ;
SELECT job, AVG(sal) FROM emp GROUP BY job HAVING AVG(sal) = ( SELECT MIN(AVG(sal)) FROM emp
GROUP BY job );
13/12/2024 72
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
13/12/2024 73
S 6 SLO-1 & SLO-2 : Sub Queries, correlated sub queries
Using EXISTS the following query display the empno, mgr, ename of those
employees who manage other employees.
select * from( select ename, sal, dense_rank() over(order by sal desc) r from
Emp)
where r=&n;
13/12/2024 74
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Eaxmple :
SQL> SELECT job,AVG(sal),Min(sal),Max(sal) FROM emp GROUP BY job HAVING
2 AVG(sal) < (SELECT MAX(AVG(sal)) FROM emp WHERE job IN
3 (SELECT job FROM emp WHERE deptno BETWEEN 10 AND 40) GROUP BY job);
13/12/2024 75
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Difference between Nested Subquery and Correlated subquery :
Nested Query
In Nested Query, Inner query runs first, and only once. Outer query is executed with result from Inner query. Hence,
Inner query is used in execution of Outer query.
SQL> select deptno from dept where deptno not in ( select deptno from emp );
DEPTNO
----------
40
Correlated Query
In Correlated Query, Outer query executes first and for every Outer query row Inner query is executed. Hence, Inner
query uses values from Outer query.
SQL> Select dname from dept where deptno not in ( select deptno from emp );
DNAME
--------------
OPERATIONS
13/12/2024 76
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Difference between Nested Query, Correlated Query and Join Operation
13/12/2024 77
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Difference between Nested Query, Correlated Query and Join Operation
13/12/2024 78
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Views
A view also has rows and columns like tables, but a view doesn’t store data
on the disk like a table. View is a Virtual table
Virtual table (view) based on the result of query statement.
Views can be created from single table
Views can be created from single table using selected columns
Views can be created from single table using selected rows
Views can be created from multiple tables
Views can be created from multiple tables using selected columns
Views can be created from multiple tables using selected rows
Data manipulation is possible in views with restrictions
The changes made in the base table(s) will be reflected in view(s)
The changes made in the views will reflected in base table with restrictions
13/12/2024 79
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
VIEWS
General Syntax
CREATE VIEW view_name AS SELECT column1, column2, ...
FROM table_name(s) WHERE condition;
13/12/2024 80
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Views
Output of Example 1:
SQL> select * from emp_view;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- - --------- --------- ---------- ----------
----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
13/12/2024 81
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Views
Example 2: Creating a view from emp table using ename, job and sal columns
SQL> create view emp_view1 as select ename, job, sal from emp;
View created.
14 rows selected.
13/12/2024 82
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Views
Example 3: Creating a view from emp table using selected rows
SQL> create view emp_view2 as select * from emp where
deptno=10;
View created.
13/12/2024 83
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Views
SQL> create view emp_view3 as select ename,job from emp where sal>2000;
View created.
ENAME JOB
---------- ---------
JONES MANAGER
BLAKE MANAGER
CLARK MANAGER
SCOTT ANALYST
KING PRESIDENT
FORD ANALYST
6 rows selected.
13/12/2024 84
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Views
Example 4: Creating a view from emp and dept table
SQL> create view emp_dept as select ename,dname from emp, dept where emp.deptno=dept.deptno;
View created.
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows
13/12/2024 selected. 85
S-7 SLO-1 & SLO-2 : Nested Queries, Views and its Types
Data manipulation in Views
If view has been created from single table using all the fields the data
manipulation is possible in view and table.
• Whatever the changes made in table , that will reflected in view and
vice versa.
If view has been created from single table using selected fields including
NOT NULL and PRIMARY KEY columns , data manipulation is possible.
• Whatever the changes made in table , that will reflected in view and
vice versa.
If view has been created from single table using selected fields excluding
NOT NULL and PRIMARY key fields, data manipulation is having some
restrictions
• Insertion is not possible
• Updation and Deletion is possible
If view has been created from multiple tables , data manipulation is not
possible.
13/12/2024 86
S-8 SLO-1 : Transaction Control Commands
DCL Commands
Used to give / get back / control the privileges of an object by the owner
GRANT : To give access privileges of an object to other user by the owner
Syntax : GRANT [ ALL / INSERT /UPDATE /DELETE /SELECT ]
on <OBJECT_NAME> to <USER_NAME>;
Example: GRANT all on emp to scott;
REVOKE : To get back all the privileges from the user who has been granted
Syntax : REVOKE [ ALL / INSERT /UPDATE /DELETE /SELECT ]
on <OBJECT_NAME> from <USER_NAME>;
Example: REVOKE all on emp from scott;
13/12/2024 87
S-8 SLO-2 : Commit, Rollback, Savepoint
TCL Commands
– SAVEPOINT: Sets a savepoint within a transaction. Rolled back from the specified
savepoint
– SET TRANSACTION: Specifies characteristics for the transaction, such as isolation level.
Ex:SET TRANSACTION [ READ WRITE | READ ONLY ];
13/12/2024 88
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
PL/SQL concepts
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database.
Anonymous Block
Named Block
Features of PL/SQL
Tightly integrated with SQL.
13/12/2024 90
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Structure of PL/SQL block
DECLARE
<declarations section>
BEGIN
<executable statements>
EXCEPTION
<exception handling>
END;
13/12/2024 91
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Structure of PL/SQL block
Declarations
This section starts with the keyword DECLARE.
It is an optional section
Defines all variables, cursors, subprograms, and other elements to be
used in the program.
Each and every variables to be declared individually.
Executable Statements
Program execution starts from BEGIN
Between BEGIN and END is called BODY of PL/SQL block.
Nested BODY is permitted
It consists of executable statements.
Exception Handling
This is an optional section , starts with Exception
It is used to handle the logical errors during run time.
13/12/2024 92
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Simple Example
DECLARE
message varchar2(100):= ‘Welcome to SRMIST';
BEGIN
dbms_output.put_line(message);
END;
Output :
Welcome to SRMIST
PL/SQL procedure successfully completed
13/12/2024 93
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Comments in PL/SQL
Double hypen (--) is Single line comment
Multiline comments enclosed by /* and */
Example
DECLARE
-- variable declaration Single line comment
message varchar2(20):= ‘Welcome to SRMIST ';
BEGIN
/* PL/SQL executable statement(s) Multi-line Comment
This Program display a Welcome note*/
dbms_output.put_line(message);
END;
13/12/2024 94
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
13/12/2024 95
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
13/12/2024 96
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Simple Example for variable declarations
DECLARE
a number := 10;
b number := 20;
c number (10,4);
f float;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 100.0/3.0;
dbms_output.put_line('Value of f: ' || round(f,4));
END;
Output
Value of c: 30
Value of f: 33.3333
13/12/2024 97
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Assigning SQL query result to PL/SQL variables using INTO clause
(Consider EMP table)
DECLARE
emp_no emp.empno%type:=&emp_no;
emp_name emp.ename%type;
emp_job emp.job%type;
emp_sal emp.sal%type;
BEGIN
SELECT ename,job,sal INTO emp_name,emp_job,emp_sal
FROM emp WHERE empno = emp_no;
dbms_output.put_line
('Employee ' ||emp_name || ' working as ' || emp_job || ' and his salary is ' || emp_sal);
END;
Output
Enter value for emp_no: 7499
old 2: emp_no emp.empno%type:=&emp_no;
new 2: emp_no emp.empno%type:=7499;
PL/SQL Operators
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
13/12/2024 99
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Continue
Goto
13/12/2024 100
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Cursors
Cursor is a private SQL workgroup area allocated temporarily
• Explicit Cursors
13/12/2024 101
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Implicit Cursors
Oracle create implicit cursor automatically whenever the DML statements
( INSERT, UPDATE and DELETE) are executed.
The implicit cursors are SQL cursors
The SQL cursors has four attributes
Attribute Description
Always returns FALSE for implicit cursors, as they are closed automatically.
SQL%ISOPEN
Returns TRUE if the SQL statement affected one or more rows, otherwise
SQL%FOUND FALSE
13/12/2024 102
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Example for Implicit Cursors ( Consider EMP table)
DECLARE
total_rows number(2);
BEGIN
UPDATE emp SET sal = sal + 500 where comm is null ;
IF sql%notfound THEN
dbms_output.put_line('No Employee selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' Employees selected ');
END IF;
END;
Output
10 Employees selected
Note : Sal updated in EMP table for 10 employees , those commission is null
13/12/2024 103
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Explicit Cursors
Syntax
13/12/2024 104
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Example for Explicit Cursors
DECLARE
emp_no emp.empno%type;
Output
emp_name emp.ename%type;
emp_sal emp.sal%type; emp_no emp_name emp_sal
7369 SMITH 800
CURSOR emp_cur is SELECT empno,ename,sal FROM emp; 7499 ALLEN 1600
BEGIN 7521 WARD 1250
7566 JONES 2975
OPEN emp_cur; 7654 MARTIN 1250
dbms_output.put_line(‘emp_no’ || ' ' || ‘emp_name’ || ' ' ||’emp_sal’); 7698 BLAKE 2850
7782 CLARK 2450
LOOP 7788 SCOTT 3000
FETCH emp_cur into emp_no,emp_name,emp_sal; 7839 KING 5000
7844 TURNER 1500
EXIT WHEN emp_cur%notfound; 7876 ADAMS 1100
dbms_output.put_line(emp_no || ' ' || emp_name || ' ' || emp_sal); 7900 JAMES 950
7902 FORD 3000
END LOOP; 7934 MILLER 1300
CLOSE emp_cur; PL/SQL procedure successfully
completed.
END;
13/12/2024 105
S-11 SLO-1 & SLO-2 : PL/SQL Concepts- Cursors
Cursor based Records
Output
Employee Number Name
DECLARE 7369 SMITH
CURSOR emp_currec is SELECT empno, ename FROM emp; 7499 ALLEN
7521 WARD
emp_rec emp_currec%rowtype;
7566 JONES
BEGIN 7654 MARTIN
OPEN emp_currec; 7698 BLAKE
DBMS_OUTPUT.put_line(‘Employee Number’ || ' ' || ‘Name’); 7782 CLARK
7788 SCOTT
LOOP 7839 KING
FETCH emp_currec into emp_rec; 7844 TURNER
EXIT WHEN emp_currec%notfound; 7876 ADAMS
7900 JAMES
DBMS_OUTPUT.put_line(emp_rec.empno || ' ' || emp_rec.ename); 7902 FORD
END LOOP; 7934 MILLER
END;
PL/SQL procedure successfully completed.
13/12/2024 106
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Sub Program
A program which can be called and executed in another program.
• Procedures
• Functions
13/12/2024 108
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Procedures
In the given syntax
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters.
• IN parameter lets you pass a value to the subprogram. It is a read-only
parameter.
• OUT parameter returns a value to the calling program. Inside the
subprogram, an OUT parameter acts like a variable.
• IN OUT parameter passes an initial value to a subprogram and returns an
updated value to the caller.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
13/12/2024 109
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example: Welcome note
CREATE OR REPLACE PROCEDURE
The procedure can be executed as given
welcome
below also
AS
BEGIN SQL> begin
dbms_output.put_line 2 welcome;
('Welcome to SRMIST'); 3 end;
END; 4 /
Welcome to SRMIST
13/12/2024 110
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Parameters
Output
DECLARE
a number:=&a; Enter value for a: 100
b number:=&b; old 2: a number:=&a;
c number;
New 2: a number:=100;
PROCEDURE findMin
Enter value for b: 200
(x IN number, y IN number, z OUT number) IS
BEGIN old 3: b number:=&b;
IF x < y THEN New 3: b number:=200;
z:= x; Minimum of 100 and 200 is :100
ELSE
z:= y;
PL/SQL procedure successfully completed.
END IF;
END;
BEGIN
findMin(a, b, c);
dbms_output.put_line
(' Minimum of '|| a ||' and ' ||b || ' is :' || c);
END;
13/12/2024 111
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Parameters
DECLARE
a number := &a;
PROCEDURE square (x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
square(a);
dbms_output.put_line (' Square is : ' || a);
END;
Output
Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Square is : 100
13/12/2024 113
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Display employee record
Output
SQL> exec get_emp_rec (7499);
7499 ALLEN SALESMAN 1600
13/12/2024 115
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Functions
13/12/2024 117
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Function to find the maximum of given two numbers
DECLARE
a number := &a;
b number := &b;
c number; Output
FUNCTION findMax(x IN number, y IN number)
RETURN number IS Enter value for a: 100
z number; old 2: a number := &a;
BEGIN
New 2: a number := 100;
IF x > y THEN
z:= x; Enter value for b: 200
ELSE old 3: b number := &b;
z:= y; New 3: b number := 200;
END IF; Maximum of 100 and 200 is: 200
RETURN z;
END;
PL/SQL procedure successfully completed.
BEGIN
c := findMax(a, b);
dbms_output.put_line(' Maximum of '||a||' and '||b|| ' is: ' || c);
END;
13/12/2024 118
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Recursive Function in PL/SQL : Find the Factorial of a number
DECLARE
num number;
factorial number;
FUNCTION fact(x number) RETURN number IS
f number; Output
BEGIN Enter value for num: 5
IF x=0 THEN old 17: num:= #
f := 1; new 17: num:= 5;
ELSE Factorial 5 is 120
f := x * fact(x-1);
END IF; PL/SQL procedure successfully
RETURN f; completed.
END;
BEGIN
num:= #
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
13/12/2024 119
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Triggers
Triggers are event driven program
Not necessary to execute manually
Triggers are automatically executed when the event ocuurs
There are 12 events are there in PL/SQL
• Before insert
• Before delete
• Before update
• After insert
• After delete
• After update
The above mentioned events can be executed for each row or each statements
Totally 12 triggers
Apart from these triggers, Instead of triggers are also available which is used to
insert into the views which is created from more than one tables 120
13/12/2024
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Syntax for Trigger
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF }
DECLARE
<Declaration-statements>
BEGIN
<Executable-statements>
EXCEPTION
<Exception-handling-statements>
END; 121
13/12/2024
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
In the given syntax
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would
13/12/2024 122
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : Display the salary difference in emp table
Output
create or replace trigger display_salary_changes SQL> update emp set sal = 1111 where empno = 7900;
Old salary: 950
before delete or insert or update on emp
New salary: 1111
for each row
Salary difference: 161
when (new.empno > 0)
declare 1 row updated.
sal_diff number; SQL> insert into emp values
begin (1234,'NANTHA','MANAGER',7839,'23-MAR-
sal_diff := :new.sal - :old.sal; 83',4000,NULL,30);
Old salary:
dbms_output.put_line('old salary: '
New salary: 4000
|| :old.sal);
Salary difference:
dbms_output.put_line('new salary: '
|| :new.sal); 1 row created.
dbms_output.put_line('salary difference: ' ||
sal_diff); SQL> delete from emp where empno=1234;
13/12/2024 123
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example for Triggers
Voters_list and polling
13/12/2024 124
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Exception Handling
While the occurrence of logical errors , exceptions are used to continue the program execution
instead stop the execution.
There are two types of exceptions are in PL/SQL
• No_data_found
• Login_denied
• Too_many_rows
• Value_error
• Zero_divide
• User defined Exception
13/12/2024 125
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Exception Handling
General Syntax
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN exception1-handling-statements
WHEN exception2 THEN exception2-handling-statements
WHEN exception3 THEN exception3-handling-statements
........
END;
13/12/2024 126
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : System defined Exception Output
declare Enter value for empno: 7499
emp_number number(10) := old 2: emp_number number(10) :=
&empno;
&empno;
New 2: emp_number number(10) := 7499;
emp_name varchar2(10);
Employee name is ALLEN
begin
select ename into emp_name from PL/SQL procedure successfully completed.
emp where empno = emp_number;
dbms_output.put_line('employee SQL> /
name is ' || emp_name); Enter value for empno: 1234
exception old 2: emp_number number(10) :=
when no_data_found then &empno;
dbms_output.put_line('no such New 2: emp_number number(10) := 1234;
employee: ' || emp_number); No such employee: 1234
end;
PL/SQL procedure successfully completed.
13/12/2024 127
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example for User defined exception With Raise command
DECLARE
emp_name VARCHAR2(10);
emp_number NUMBER;
empno_out_of_range EXCEPTION;
BEGIN
emp_number := &empno;
IF emp_number > 9999 OR emp_number < 1000 THEN
RAISE empno_out_of_range;
ELSE
SELECT ename INTO emp_name FROM emp WHERE empno = emp_number;
DBMS_OUTPUT.PUT_LINE('Employee name is ' || emp_name);
END IF;
EXCEPTION
WHEN empno_out_of_range THEN
DBMS_OUTPUT.PUT_LINE('Employee number ' || emp_number || ' is out of range.');
END;
13/12/2024 128
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Output
SQL> /
Enter value for empno: 7499
old 6: emp_number := &empno;
new 6: emp_number := 7499;
Employee name is ALLEN
SQL> /
Enter value for empno: 900
old 6: emp_number := &empno;
new 6: emp_number := 900;
Employee number 900 is out of range.
SQL> /
Enter value for empno: 10000
old 6: emp_number := &empno;
new 6: emp_number := 10000;
Employee number 10000 is out of range.
13/12/2024 129
S-12 SLO-1 & SLO-2 : Stored Procedure, Functions
Triggers and Exceptional Handling
Example : With user defined and System defined Exceptions
DECLARE Output
13/12/2024 130
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 131
S-13 SLO-1 & SLO-2 : Query Processing
Optimizer
Evaluation Execution
Query Output
Engine Plan
Statistics
Data Data about Data
13/12/2024 132
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 133
S-13 SLO-1 & SLO-2 : Query Processing
Basic steps in Query 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
13/12/2024 134
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 135
S-13 SLO-1 & SLO-2 : Query Processing
Measures of Query Cost
Cost is generally measured as total elapsed time for answering query
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
13/12/2024 136
S-13 SLO-1 & SLO-2 : Query Processing
Measures of Query Cost
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 * t T + S * tS
We ignore CPU costs for simplicity
• Real systems do take CPU cost into account
We do not include cost to writing output to disk in our cost formulae
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
13/12/2024 137
S-13 SLO-1 & SLO-2 : Query Processing
Selection Operation
File scan
Algorithm A1 (linear search). Scan each file block and test all records to see whether
they satisfy the selection condition.
• Cost estimate = br block transfers + 1 seek
br denotes number of blocks containing records from relation r
• If selection is on a key attribute, can stop on finding record
cost = (br /2) block transfers + 1 seek
• Linear search can be applied regardless of
selection condition or
ordering of records in the file, or
availability of indices
Note: binary search generally does not make sense since data is not stored consecutively
• except when there is an index available,
• and binary search requires more seeks than index search
13/12/2024 138
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 139
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 140
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 141
S-13 SLO-1 & SLO-2 : Query Processing
13/12/2024 143