SQL & Query Optimization: Unit - Iii
SQL & Query Optimization: Unit - Iii
Operators Description
'+' Performs addition.
'!=' Checks if a is not equal to b. If yes, condition becomes true, else false. (a!= b) is true.
'<>' Checks if a is equal to b or not. If yes, condition becomes true, else (a<>b) is false.
false.
'>' Checks if a is greater than b. If yes, condition becomes true, else false. (a>b) is false.
'<' Checks if a is less than b. If yes, condition becomes true, else false. (a<b) is true.
'>=' Checks if value of a is greater than or equal to b. If yes, condition (a>=b) is false.
becomes true, else false.
'<=' Checks if value of a is less than or equal to b. If yes, condition (a<= b) is true.
becomes true, else false.
'!<' Checks if value of a is not less than value of b. If yes, condition (a!<b) is false.
becomes true, else false.
'!>' Checks if value of a is not greater than b. If yes, condition becomes (a!>b) is true.
true.
SQL OPERATORS
3. SQL Logical Operator
Operator Description
CREATE TABLE
Syntax Example
CREATE TABLE table_name ( CREATE TABLE Persons (
column1 datatype, PersonID int,
column2 datatype, LastName varchar(255),
column3 datatype, FirstName varchar(255),
.... Address varchar(255),
); City varchar(255)
);
CREATE VIEW
Syntax Example
CREATE VIEW view_name AS CREATE VIEW Brazil_Customers AS
SELECT column1, column2, ... SELECT CustomerName, ContactName
FROM table_name FROM Customers
WHERE Country = 'Brazil';
WHERE condition;
2. ALTER
Alter command is used for altering the table in many forms like:
1.Add a column
2.Rename existing column
3.Drop a column
4.Modify the size of the column or change datatype of the column
ADD using ALTER
Syntax: ALTER TABLE table_name ADD( column_name datatype);
Example: ALTER TABLE Student ADD (Address VARCHAR(200));
RENAME using ALTER
Syntax: ALTER TABLE table_name RENAME old_column_name TO
new_column_name;
Example: ALTER TABLE Employee RENAME Marks TO Age;
DROP using ALTER
Syntax: ALTER TABLE table_name DROp (column_name);
Example: ALTER TABLE Employee DROP (Age);
DROP using ALTER
Syntax: ALTER TABLE table_name DROp (column_name);
Example: ALTER TABLE Employee DROP (Age);
3. DROP
DROP DATABASE
Syntax: Example:
DROP DATABASE Database Name; DROP DATABASE Employee;
DROP TABLE
Syntax : Example:
DROP TABLE table_name DROP TABLE Student;
This will delete all the records from the table. For example the below command will
remove all the records from table student.
Example:
TRUNCATE TABLE Student;
5. RENAME
The rename command is used to change the name of an
existing database object(like Table, Column) to a new name.
Example:
SELECT DISTINCT Marks FROM student;
Marks
60
78
WHERE
The WHERE Clause is used to retrieve only those records which fulfill the given
criteria.
Syntax:
SELECT column_name FROM table_name WHERE conditions;
AND
The SQL AND operator is used to combine multiple conditions along with WHERE clause.
Syntax:
SELECT Column_name FROM table_name WHERE condition AND condition;
SELECT C_ID FROM Clients WHERE City= 'Pune‘ AND Country= 'India';
OR
The SQL OR operator is used to combine multiple conditions along with WHERE and OR
clause.
Syntax:
SELECT * FROM table_name WHERE condition OR condition;
SELECT FirstName FROM Clients WHERE City='Pune‘ OR City='Berlin';
2. INSERT
SQL INSERT statement is used to insert a data into a table .
Table 2:
Client_ID Last_Name First_Name Contact Country
1 Thomas Alex 2400000 USA
2 Cruise Martin 5600000 USA
Syntax:
DELETE FROM table_name WHERE [Condition];
Syntax:
UPDATE table_name SET Column1= value1, Cloumn2 = value2, column3 = value3.....
WHERE [Condition];
Example : Query using UPDATE statement.
Consider the following table titled as 'Clients'
Client_ID Last_Name First_Name Contact Country
1 Thomas Alex 2400000 USA
2 Cruise Martin 5600000 USA
3 Pandit Prajakta null India
1. Write a query to update contact information of a particular row where condition
is given as, client id = 3.
Syntax:
GRANT privileges ON Object TO user;
Parameters Used:
• privileges: These are the access rights or privileges granted to the user.
• object: It is the name of the database object to which permissions are being granted. In
the case of granting privileges on a table, this would be the table name.
• user: It is the name of the user to whom the privileges would be granted.
PRIVILEGES
EXAMPLE FOR GRANT
GRANT SELECT ON Users TO'Amit'@'localhost;
Syntax:
REVOKE privilege_list ON object_name
FROM user_name;
REVOKE SELECT ON users TO 'Amit'@localhost';
Table2 : 'Examination'
4 Mira 23 Delhi
5 Hema 27 Noida
6 Neha 25 Delhi
7 Khushi 26 Noida
TRIGGERS
� Triggers are Stored in database and executed by Oracle engine
whenever some event occurs.
� When a trigger is fired, SQL statement inside the trigger's
PL/SQL code block can also fire the same or some other
trigger.
� This is called cascading triggers.
� Triggers are written to execute in response events like DML
Statements (DELETE, INSERT, or UPDATE),
� DDL statements (CREATE, ALTER, DELETE), and database
operation (SERVERERROR, LOGON, LOGOFF, STARTUP
or SHUTDOWN)
DIFFERENCE BETWEEN TRIGGER AND
STORED PROCEDURE
Trigger Stored Procedure
DECLARE
total_rows number(2);
BEGIN
UPDATE EMPLOYEE
SET salary = salary+( salary *0.05);
IF sql%notfound THEN
dbms_output.put_line('no employee updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' employee updated ');
END IF;
END;
INPUT TABLE: EMPLOYEE
ID NAME DESIGNATION SALARY
101 AJAY MANAGER 40000
102 RAM ASST.MANAGER 35000
103 KARAN ASST.MANAGER 35000
104 RAM PROGRAMMER 23000
105 RAM ANALYST 23000
Attributes Description
DECLARE
total_rows number(2);
BEGIN
UPDATE Employee
SET salary = salary + 1000;
IF sql%notfound THEN
dbms_output.put_line('no Employee updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows | | ' Employee updated ');
END IF;
END;
2. EXPLICIT CURSOR
� If a cursor is opened for processing data through a PL/SQL
block as per requirement like user defined cursor, is known as
an Explicit cursor.
� Explicit cursor is created while executing a SELECT statement
that returns more than one row.
� These cursor should be defined in the declaration section of the
PL/SQL block and created on a SELECT statement which
returns more than one row.
� Syntax:
⚫ Cursor cursor_name IS select_statement;
FOLLOWING ARE THE STEPS TO WORK
WITH AN EXPLICIT CURSOR:
1. Declare
� Syntax:
CURSOR Name IS SELECT statement;
2.Open
� Syntax:
OPEN Cursor_name;
3. Fetch
� This statement is used to access one row at a time.
Syntax:
FETCH cursor_name INTO variable_list;
4. Close
Syntax:
Close Cursor_name;
EXAMPLE:
WRITE A PL/SQL CODE TO RETRIEVE THE
EMPLOYEE NAME AND DESIGNATION USING
EXPLICIT CURSOR.
ID NAME DESIGNATION SALARY
101 AJAY MANAGER 40000
102 RAM ASST.MANAGER 35000
103 KARAN ASST.MANAGER 35000
104 RAM PROGRAMMER 23000
105 RAM ANALYST 23000
WRITE A PL/SQL CODE TO RETRIEVE THE
EMPLOYEE NAME AND DESIGNATION USING
EXPLICIT CURSOR.
DECLARE
c_id employee.id%type;
c_name employee.name%type;
c_des employee.designation%type;
CURSOR c_employee is
SELECT id, name, designation FROM employee;
BEGIN
OPEN c_employee;
LOOP
FETCH c_employee into c_id, c_name, c_des;
EXIT WHEN c_employee%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_des);
END LOOP;
CLOSE c_employee;
END;
OUTPUT
Statement processed.
EMBEDDED SQL
AND
DYNAMIC SQL
WHAT IS EMBEDDED SQL?
� This is a method for combining data manipulation capabilities
of SQL and computing power of any programming language.
� A language in which SQL queries are embedded is referred to
as a host language, and the SQL structures permitted in the
host language constitute embedded SQL.
� Programs written in the host language can use the embedded
SQL syntax to access and update data stored in a database.
� An embedded SQL program must be processed by a special
preprocessor prior to compilation.
� The preprocessor replaces embedded SQL requests with host-
language declarations and procedure calls that allow runtime
execution of the database accesses.
EMBEDDED SQL
� Then the resulting program is compiled by the host language
compiler.
� To identify embedded SQL requests to the preprocessor, we
use the EXEC SQL statement; it has the form:
� To identify embedded SQL requests to the preprocessor, we
use the EXEC SQL statement; it has the form:
To disconnect
END;
It is generally used for situations where data It is generally used for situations where data
is distributed uniformly. is distributed non uniformly.
We may build an index on the relation, and then use the index to
read the relation in sorted order. May lead to one disk block
access for each tuple.
For relations that fit in memory, techniques like quicksort can be
used. For relations that don’t fit in memory, external
sort-merge is a good choice.
EXAMPLE: EXTERNAL SORTING USING SORT-MERGE
a 19 a 19
g 24 d 31 a 14
b 14
a 19 g 24 a 19
c 33
d 31 b 14
b 14 d 31
c 33 c 33
c 33 e 16
b 14 d 7
e 16 g 24
e 16 d 21
r 16 d 21 d 31
a 14
d 21 m 3 e 16
d 7
m 3 r 16 g 24
d 21
p 2 m 3
m 3
d 7 a 14 p 2
p 2
a 14 d 7 r 16
r 16
p 2
initial sorted
relation runs runs output
create merge merge
runs pass–1 pass–2
EXTERNAL SORT-MERGE
Let M denote memory size (in pages).
1. Create sorted runs. Let i be 0 initially.
Repeatedly do the following till the end of the relation:
(a) Read M blocks of relation into memory
(b) Sort the in-memory blocks
(c) Write sorted data to run Ri; increment i.
Let the final value of i be N
2. Merge the runs (next slide)…..
EXTERNAL SORT-MERGE (CONT.)
2. Merge the runs (N-way merge). We assume (for now) that
N < M.
1. Use N blocks of memory to buffer input runs, and 1 block to
buffer output. Read the first block of each run into its buffer
page
2. repeat
1. Select the first record (in sort order) among all buffer pages
2. Write the record to the output buffer. If the output buffer is
full write it to disk.
3. Delete the record from its input buffer page.
If the buffer page becomes empty then
read the next block (if any) of the run into the buffer.
3. until all input buffer pages are empty:
EXTERNAL SORT-MERGE (CONT.)
If N M, several merge passes are required.
⚫ In each pass, contiguous groups of M - 1 runs are merged.
⚫ A pass reduces the number of runs by a factor of M -1, and
creates runs longer by the same factor.
E.g. If M=11, and there are 90 runs, one pass reduces the
number of runs to 9, each 10 times the size of the initial runs
⚫ Repeated passes are performed till all runs have been merged
into one.
EXTERNAL MERGE SORT (CONT.)
� Cost analysis:
⚫ 1 block per run leads to too many seeks during merge
� Instead use bb buffer blocks per run
read/write bb blocks at a time
� Can merge M/bb–1 runs in one pass
⚫ Total number of merge passes required: log M/bb–1(br/M).
⚫ Block transfers for initial run creation as well as in each pass
is 2br
� for final pass, we don’t count write cost
� we ignore final write cost for all operations since the output of
an operation may be sent to the parent operation without being
written to disk
� Thus total number of block transfers for external sorting:
br ( 2 log M/bb–1 (br / M) + 1)
Cost of seeks
⚫ During run generation: one seek to read each run and one
seek to write each run
2 br / M
⚫ During the merge phase
Need 2 br / bb seeks for each merge pass
except the final one which does not require a write
Total number of seeks:
2 br / M + br / bb (2 logM/bb–1(br / M) -1)
JOIN OPERATION
Several different algorithms to implement joins
⚫ Nested-loop join
⚫ Block nested-loop join
⚫ Indexed nested-loop join
⚫ Merge-join
⚫ Hash-join
Choice based on cost estimate
Examples use the following information
⚫ Number of records of student: 5,000 takes: 10,000
⚫ Number of blocks of student: 100 takes: 400
NESTED-LOOP JOIN
� In the worst case, if there is enough memory only to hold one block of
each relation, the estimated cost is
nr bs + br block transfers, plus
nr + br seeks
� If the smaller relation fits entirely in memory, use that as the inner
relation.
⚫ Reduces cost to br + bs block transfers and 2 seeks
� Assuming worst case memory availability cost estimate is
⚫ with student as outer relation:
� 5000 400 + 100 = 2,000,100 block transfers,
� 5000 + 100 = 5100 seeks
⚫ with takes as the outer relation
� 10000 100 + 400 = 1,000,400 block transfers and 10,400 seeks
� If smaller relation (student) fits entirely in memory, the cost estimate will
be 500 block transfers.
� Block nested-loops algorithm (next slide) is preferable.
BLOCK NESTED-LOOP JOIN
Find out how to view query execution plans on your favorite database
INTRODUCTION (CONT.)
Õ L È L ( E1
1 2 q E2 ) = Õ L È L (( Õ L È L ( E1 ))
1 2 1 3 q (Õ L
2 È L4 ( E2 )))
EQUIVALENCE RULES (CONT.)
9. The set operations union and intersection are commutative
E1 E2 = E2 E1
E1 E2 = E2 E1
(set difference is not commutative).
10. Set union and intersection are associative.
(E1 E2) E3 = E1 (E2 E3)
(E1 E2) E3 = E1 (E2 E3)
11. The selection operation distributes over , and –.
(E1 – E2) = (E1) – (E2)
and similarly for and in place of –
Also: (E 1 – E2) = (E1) – E2
and similarly for in place of –, but not for
12. The projection operation distributes over union
L(E1 E2) = (L(E1)) (L(E2))
HEURISTIC OPTIMIZATION
� A query tree is a tree data structure that corresponds to a
relational algebra expression.
� It represents the input relations of the query as leaf nodes
of the tree, and represents the relational algebra operations
as internal nodes.
� An execution of the query tree consists of executing an
internal node operation whenever its operands are
available and then replacing that internal node by the
relation that results from executing the operation.
� The order of execution of operations starts at the leaf
nodes, which represents the input database relations for
the query, and ends at the root node, which represents the
final operation of the query
� SELECT LNAME FROM EMPLOYEE, WORKS_ON,
PROJECT WHERE PNAME='AQUARIUS' AND
PNUMBER=PNO AND ESSN=SSN AND BDATE >
'1957-12-31';