0% found this document useful (0 votes)
5 views82 pages

DBMS Lab Manual

This document is a laboratory manual for a Database Management System course, detailing experiments and practical exercises for students to learn DDL and DML commands using Oracle SQL. It includes objectives, procedures, queries, and quizzes related to creating and manipulating database tables. The manual emphasizes hands-on practice with SQL commands and provides safety precautions and references for further learning.

Uploaded by

Vishvas Panchal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views82 pages

DBMS Lab Manual

This document is a laboratory manual for a Database Management System course, detailing experiments and practical exercises for students to learn DDL and DML commands using Oracle SQL. It includes objectives, procedures, queries, and quizzes related to creating and manipulating database tables. The manual emphasizes hands-on practice with SQL commands and provides safety precautions and references for further learning.

Uploaded by

Vishvas Panchal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

A Laboratory Manual for

Database Management System


(3130703)

B.E. Semester 3(Computer Engineering)

Directorate of Technical Education,


Gandhinagar, Gujarat

1
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

3
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

4
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

5
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
6
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

7
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

Experiment No: 1
To study DDL-create and DML-insert commands.
Create tables and insert data as shown below.

Perform queries on created tables as given in the practical list.


Date:

Competency and Practical Skills: programming and database commands

Relevant CO: CO1,CO3


Objectives: (a) To create table using DDL command.
(b) To insert data in table using DML command.

(c) To use select command for accessing data from tables(comparison


based queries) Equipment/Instruments: Personal Computer, Oracle Xpress Edition (Open
Source)

Explanation:

To study DDL-create and DML-insert commands.


Create tables and insert data as shown below.
Perform following queries on created tables,

1. Describe deposit, branch.


2. Describe borrow, customers.
3. List all data from table DEPOSIT.
4. List all data from table BORROW.
5. List all data from table CUSTOMERS.
6. List all data from table BRANCH.
7. Give account no and amount of depositors.
8. Give name of depositors having amount greater than 4000.

9. Give name of customers who opened account after


date '1-12-96'. Create tables according to the following
definition.

CREATE TABLE DEPOSIT (ACTNO VARCHAR2(5) ,CNAME VARCHAR2(18) , BNAME


VARCHAR2(18) , AMOUNT NUMBER(8,2),ADATE DATE);

CREATE TABLE BRANCH(BNAME VARCHAR2(18),CITY


VARCHAR2(18)); CREATE TABLE CUSTOMERS(CNAME
VARCHAR2(19) ,CITY VARCHAR2(18));

CREATE TABLE BORROW(LOANNO VARCHAR2(5), CNAME VARCHAR2(18), BNAME


VARCHAR2(18), AMOUNT NUMBER(8,2));

8
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Insert the data as shown below.

9
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

Safety and necessary Precautions:


1) Make sure the database server is started
2) Login with correct user ID and password in oracle.

Procedure:
1. Get Oracle SQL prompt
2. Login with correct userID and password
3. Ensure commit after inserting records in table/ set auto commit ON

Observations:

Creating Tables as required and inserting data into tables :

10
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Performing Queries :
1. Describe deposit, branch

11
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2. Describe borrow, customers

12
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
3. List all data from table DEPOSIT.

4. List all data from table BORROW.

13
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
5. List all data from table CUSTOMERS.

6. Give account no and amount of depositors.

14
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
7. Give name of depositors having amount greater than 4000.

Quiz:
1) List all datatypes used to create a table column in oracle.
Common datatypes include VARCHAR2, NUMBER, DATE, CHAR, BLOB, CLOB,
TIMESTAMP, FLOAT, RAW.

2) What is primary key?


A column that uniquely identifies each row in a table and ensures no
duplicate values.

3) Draw architecture of DBMS.

15
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
16
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Suggested Reference:
1. “Understanding SQL”, Martin Gruber, BPB
2. “SQL- PL/SQL”, Ivan bayros

17
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

Experiment No: 2
Perform queries on created tables as given in the practical list.

To study DDL-create and DML-insert commands.


Create tables and insert data as shown.

Date:

Competency and Practical Skills: run DML and DDL commands in SQL
Relevant CO: CO1, CO3
Objectives: (a) To create table using DDL command.
(b) To insert data in table using DML command.

(c) To use select command for accessing data from tables (matching regular expression using like

predicate)..
Equipment/Instruments: Personal Computer, Oracle Xpress Edition (Open Source)

Explanation:

Create tables and insert data as shown below.


Perform following queries ,
1. Retrieve all data from employee, jobs and deposit.
2. Give details of account no. and deposited rupees of customers having account opened between dates
01-01-06 and 25-07-06.
3. Display all jobs with minimum salary is greater than 4000.

4.Display name and salary of employee whose department no is 20. Give alias
name to name of employee.

5.Display employee no, name and department details of those employee whose
department lies in(10,20)

To study various options of LIKE predicate


Display all employee whose name start with ‘A’ and third character is ‘ ‘a’.

2.Display name, number and salary of those employees whose name is 5 characters
long and first three characters are ‘Ani’.

3.Display the non-null values of employees and also employee name second
character should be ‘n’ and string should be 5 character long.
4.Display the null values of employee and also employee name’s third character should be ‘a’.
5.What will be output if you are giving LIKE predicate as ‘%\_%’ ESCAPE ‘\’

18
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Database Management System (3130703)

19
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
20
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Safety and necessary Precautions:
1) Make sure the database server is started
2) Login with correct user ID and password in oracle.

Procedure:
1. Get Oracle SQL prompt
2. Login with correct userID and password

3. Ensure commit after inserting records in table/ set auto commit ON

Observations:

Creating required tables and inserting data into tables :

21
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Performing queries :
1. Retrieve all data from employee, jobs and deposit.

22
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2. Give details of account no. and deposited rupees of customers having account opened between dates 01-01-06 and
25-07-06.

23
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
3. Display all jobs with minimum salary is greater than 4000.

4. Display name and salary of employee whose department no is 20. Give alias name to name of employee

24
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
5. Display employee no, name and department details of those employee whose department lies in(10,20)

1. Display all employee whose name start with ‘A’ and third character is ‘ ‘a’.

2. Display name, number and salary of those employees whose name is 5 characters long and first three characters are
‘Ani’.

25
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
3. Display the non-null values of employees and also employee name second character should be ‘n’ and string should be
5 character long.

4. Display the null values of employee and also employee name’s third character should be ‘a’.

Quiz:
1. Define data and information.
Data is a collection of raw, unorganized facts and details like text, observations, figures,
symbols, and descriptions of things etc. In other words, data does not carry any specific
purpose and has no significance by itself.

2. Give syntax of insert command.


INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

3. How can we create a table from existing table? Give example.


CREATE TABLE new_table_name AS
SELECT column1, column2, ...
FROM existing_table_name;

Example :- CREATE TABLE new_employee AS


SELECT emp_no, emp_name, emp_sal
FROM employee;

Suggested Reference:
1. “Understanding SQL”, Martin Gruber, BPB
2. “SQL- PL/SQL”, Ivan bayros

26
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
27
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Experiment No: 3
To Perform various data manipulation commands, aggregate functions, and sorting
concepts on all created tables. (Use tables from practical 1 and 2). Then, perform queries
on created tables as given in the practical list.

Date:
Competency and Practical Skills: run DML commands in SQL with group by, having
Relevant CO: CO3
Objectives:

(a) To use select command for accessing data from tables (group by, order by , having etc).

(b)To delete record from tables using delete command


(c) To update data stored in table using update command
.
Equipment/Instruments: Personal Computer, Oracle OR MySQL

Explanation:

To Perform various data manipulation commands, aggregate functions and


sorting concept on all created tables. (Use tables from practical 1 and 2)

1. List total deposit from deposit.


2. List total loan from karolbagh branch
3. Give maximum loan from branch vice.
4. Count total number of customers
5. Count total number of customer’s cities.
6. Create table supplier from employee with all the columns.
7. Create table sup1 from employee with first two columns.
8. Create table sup2 from employee with no data

9. Insert the data into sup2 from employee whose second character should be
‘n’ and string should be 5 characters long in employee name field.

10. Delete all the rows from sup1.


11. Delete the detail of supplier whose sup_no is 103.
12. Rename the table sup2.
13. Destroy table sup1 with all the data.
14. Update the value dept_no to 10 where second character of emp. name is ‘m’.
15. Update the value of employee name whose employee number is 103.

Safety and necessary Precautions:


1. Make sure the database server is started
2. Login with correct user ID and password in oracle.

Procedure:
1. Get Oracle SQL prompt
2. Login with correct userID and password
3. Ensure commit after inserting/deleting/updating records in table/ set auto commit ON

Observations:

28
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
1. List total deposit from deposit.

2. List total loan from kathlal branch

3. Give maximum loan from branch vice.

29
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
4. Count total number of customers

5. Count total number of customer’s cities.

6. Create table supplier from employee with all the columns.

7. Create table sup1 from employee with first two columns.

8. Create table sup2 from employee with no data

30
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
9. Insert the data into sup2 from employee whose second character should be ‘n’ and string
should be 5 characters long in employee name field.

10. Delete all the rows from sup1.

11. Delete the detail of supplier whose sup_no is 103.

12. Rename the table sup2.


RENAME TABLE sup2 TO new_sup2;

13. Destroy table sup1 with all the data.

14. Update the value dept_no to 10 where second character of emp. name is ‘m’.

15. Update the value of employee name whose employee number is 103.

31
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Quiz:
1. Give syntax of delete command
DELETE FROM table_name
WHERE condition;

2. Give syntax of update command


UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

3. How can we write group by query in Relational Algebra.


In relational algebra, there isn't a direct GROUP BY operation like in SQL, but
similar functionality can be achieved using the following operations:

Aggregation: You use aggregation functions (such as SUM, MAX, MIN, AVG,
COUNT) combined with projection and selection.

Grouping: To achieve grouping, you can use the Grouping and Aggregation
operation in extended relational algebra.

Suggested Reference:
1. “Understanding SQL”, Martin Gruber, BPB
2. “SQL- PL/SQL”, Ivan bayros
References used by the students:

32
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
33
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
34
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
35
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
36
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Quiz:
1. Draw the symbols used for ER diagram.

2. Define weak entity set.

A weak entity set is an entity set that cannot be uniquely identified by its own
attributes alone. Instead, it depends on a strong entity set (also called an owner
entity) to provide part of its primary key. A weak entity has a partial key (also called a
discriminator) which, when combined with the primary key of the related strong entity,
uniquely identifies the weak entity.

3. How can we implement tables from ER diagram? Explain with example.

Converting an ER (Entity-Relationship) diagram to a relational schema (i.e., tables)


involves creating tables for all entity sets and relationships. Each entity set becomes
a table, and the relationships between entities are implemented using foreign keys.

Steps to Convert ER Diagram to Tables:

1. For Strong Entities: Create a table for each strong entity with its attributes. The primary key
of the entity set becomes the primary key of the table.
2. For Weak Entities: Create a table for each weak entity. Include the attributes of the weak
entity and the primary key of the related strong entity (as a foreign key). The primary key of
the weak entity table is the combination of the strong entity's key and the weak entity's partial
key.

37
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
3. For Relationships: Create a table for many-to-many relationships, including foreign keys from
both participating entities. For one-to-many and one-to-one relationships, foreign keys can
be added to the respective entity tables.
4. Handle Participation and Cardinality Constraints: If an entity is participating totally in a
relationship, ensure the foreign key is NOT NULL. For cardinality constraints, adjust the
number of records and foreign key usage accordingly.

Suggested Reference:

1. “Database System Concepts”, 6th Edition by Abraham Silberschatz,


Henry F. Korth, S. Sudarshan, McGraw-Hill.
2. “An introduction to Database Systems”, C J Date, Pearson.
References used by the students:

38
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
39
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Procedure:
1. Get Oracle SQL prompt
2. Login with correct userID and password
3. Ensure commit after inserting/deleting/updating records in table/ set auto commit ON

Observations:

1. Write a query to display the current date. Label the column Date.

40
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2. For each employee, display the employee number, job, salary, and salary increased by 15% and expressed as
a whole number. Label the column New Salary.

3. Modify your query no.(2) to add a column that subtracts the old salary from the new salary. Label the
column Increase

4. Write a query that displays the employee’s names with the first letter capitalized and all other letters
lowercase, and the length of the names, for all employees whose name starts with J, A, or M. Give each column
an appropriate label. Sort the results by the employees’ last names.

41
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
5. Write a query that produces the following for each employee:
<employee name> earns <salary> monthly

6. Write a query to calculate the annual compensation of all employees


(sal+comm.).

7. Give 10% interest to all depositors.

42
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Quiz:
1. Explain the concept of nested queries
Nested Queries, also known as subqueries, are queries that are embedded within
another query. They allow you to perform complex data retrieval tasks by using the result
of one query as an input for another query.Subqueries can be used in SELECT, INSERT,
UPDATE, or DELETE statements and typically occur in the WHERE clause to filter
results.
● Types of subqueries:
○ Single-row subquery: Returns one row (e.g., used with =, <, >, etc.)
○ Multiple-row subquery: Returns multiple rows (e.g., used with IN, ANY, ALL)
○ Correlated subquery: Dependent on data from the outer query, evaluated once for
each row.

2. List various built in function related to string in oracle.


Oracle provides several built-in functions to manipulate string data. Some common ones
include:
● LOWER(string): Converts a string to lowercase.
● UPPER(string): Converts a string to uppercase.
● INITCAP(string): Capitalizes the first letter of each word.
● LENGTH(string): Returns the length of a string.
● SUBSTR(string, start_position, length): Extracts a substring from a string.
● INSTR(string, substring, [start_position]): Finds the position of a substring in
a string.
● REPLACE(string, search_string, replace_string): Replaces occurrences of a
substring within a string.
● CONCAT(string1, string2): Concatenates two strings.
● LTRIM(string, trim_chars): Trims characters from the left side of a string.
● RTRIM(string, trim_chars): Trims characters from the right side of a string.
● TRIM([trim_chars] FROM string): Trims characters from both sides of a string.
● LPAD(string, length, pad_string): Pads the left side of the string.
● RPAD(string, length, pad_string): Pads the right side of the string.

3. Explain difference between cross product and natural join.


Cross Product (Cartesian Product):
● A cross product combines every row from one table with every row from another table.
● If one table has n rows and another table has m rows, the result of a cross product will have
n * m rows.

Natural Join:

● A natural join automatically joins two tables based on all columns with the same name and
compatible data types.
● It eliminates redundant columns from the result and combines rows with matching values in
the common columns.

Suggested Reference:
1. “Understanding SQL”, Martin Gruber, BPB
2. “SQL- PL/SQL”, Ivan bayros

43
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
References used by the students:

44
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
45
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
46
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
47
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Safety and necessary Precautions:
1. Make sure the database server is started
2. Login with correct user ID and password in oracle.

Procedure:
1. Get Oracle SQL prompt
2. Login with correct userID and password
3. Ensure commit after inserting/deleting/updating records in table/ set auto commit ON

48
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Observations:

Creating tables first and then inserting data into tables :-

49
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
50
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Performing Queries on travelling_company Database :-
6.3 Solve the below queries.
(a) Show the structure of the route_header table.

(b) Alter the table to modify the length of the column distance in table
route_header to 4.

51
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(c) Display all the details of all the routes.

(d) update the table route_header to set the distance between madras and Madurai
to be 300.

(e) create a pseudo table ticket_det with the same structure as the table ticket_detail
and insert rows into the table using the select clause.

(f) Remove all the details of ticket no-5 from ticket_detail table.

52
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(g) Alter pseudo table ticket_detail to add foreign key for ticket_no.

(h) Remove table ticket_detail from database.

(i) Find system’s current date.

(j) Find sum of 5 and 10.

53
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(k) Find only those routes that originate in madras and terminate at cochin.

6.4 Solve the below queries.

(a) Find the fare and the origin for those route_no which are greater than 15.

54
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(b) Find only those rows where fare ranges between 30 and 50.

(c) Display details of all the routes according to decending order of their distance.

55
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(d) Find only those rows from route_header where origin begins with ‘m’.

(e) Find the details of those places whose name is of maximum 6 characters,and
3rd character of name includes ‘i’.

6.5 Solve the below queries.


(a) Find the date two months later the date of issue of the ticket.

56
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(b) Find the months between date of travel and date of issue.

(c) Display the first three character of the place_name where the name is
‘banglore’.

(d) Give the avg. of the total_fare.

57
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(e) Which bus runs the minimum distance?

6.6 Solve the below queries.


(a) Give the total no. of people who have traveled so far group by ticket no.

(b) Select distinct ticket numbers from both ticket_header and ticket_detail.

58
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(c) Select all ticket_numbers from ticket_header and ticket_detail.

(d) Select only common fleet_ids that are present in fleet_header and ticket_header.

59
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(e) Select distinct route_id from route_header and not in route_detail using both the
tables.

6.7 Solve the below queries.


(a) count total no of fleets running on each route.

(b) Display the details of all those routes for which no fleet is assigned.

60
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(c) Display details for those fleets for which no ticket is issued.

(d) How many passengers are traveling on each ticket?

6.8 Solve the below queries.


(a)Display details for those fleets for which the origin is ‘Madras’.

61
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(b) For each ticket display details of those passengers whose age is above 20.

(c) Display the details of ticket allocated for super deluxe category. (Using joins)

(d) Display details of those routes on which deluxe category fleet is running. (Using joins)

62
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Quiz:
1. How can we create a table level primary key? Write down syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...,
PRIMARY KEY (column1, column2)
);

2. Write a command to create a foreign key for already created table.


ALTER TABLE table_name
ADD CONSTRAINT constraint_name FOREIGN KEY (column_name)
REFERENCES parent_table (parent_column);

3. Write syntax for check constraint


CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...,
CHECK (condition)
);

4. Write a command to delete a constraint.


ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

Suggested Reference:
1. “Understanding SQL”, Martin Gruber, BPB
2. “SQL- PL/SQL”, Ivan bayross
References used by the students:

63
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Experiment No: 7
1. What is a view in SQL? Explain its different types with SQL syntax and examples.

2. Discuss stored procedure and stored function for PL/SQL.

Date:

Competency and PracticalSkills: Theory concept of view and stored procedure/function


along with syntax to create them

Relevant CO: CO2


Objectives:
(a)To understand view and its requirement
(b)to understand need of stored procedure and stored function
(c) Know the syntax for creating view, stored procedure and stored function.
.
Equipment/Instruments: Pen and paper

Write answer of the Question here:

1. View in SQL
A view is a virtual table in SQL that provides a way to look at data in one or more tables without storing
the actual data itself. It is based on a SQL query and can include data from multiple tables, allowing you
to simplify complex queries or abstract the underlying table structures.

Types of Views in SQL:

1. Simple View:
○ Based on a single table, and does not include any functions, groups, or multiple tables.
○ It allows DML operations (INSERT, UPDATE, DELETE).
2. Complex View:
○ Based on multiple tables, and may include functions, joins, and group by clauses.
○ It may not allow DML operations depending on the complexity.

Types of Views:
● Updatable View: A view that allows DML operations like INSERT, UPDATE, and DELETE on the base
tables through the view.
○ Example: A simple view that does not have aggregations or joins may allow updates.
● Non-Updatable View: A view that does not allow DML operations, often due to involving joins,
subqueries, or aggregate functions.
○ Example: Complex views involving GROUP BY or multiple joins are non-updatable.

2. Stored Procedure and Stored Function in PL/SQL


In PL/SQL, both stored procedures and stored functions are subprograms that are stored in the database and can
be executed later as required. They encapsulate reusable SQL and PL/SQL code blocks.

1. Stored Procedure

A stored procedure is a group of SQL statements that performs a specific task. It does not necessarily return a
value, but it can modify data or execute complex logic. Stored procedures can also accept input parameters.

64
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2. Stored Function

A stored function is similar to a stored procedure but must return a value. Functions are mainly used for
computations and can be called in SQL queries.

Quiz:
1. List the rules of updatable view.

For a view to be updatable, certain conditions must be met. These rules ensure
that DML operations (INSERT, UPDATE, DELETE) on the view can be
propagated to the base tables.
1. Single Base Table: The view must be based on a single table. If the view is based on multiple
tables (through JOINs), it is typically not updatable.
2. All Required Columns: The view must include all the columns from the base table that are
defined as NOT NULL. This ensures that the necessary data is provided for DML operations.
3. No Aggregate Functions: The view cannot contain aggregate functions (like SUM, COUNT,
AVG, etc.). If it does, the view is non-updatable.
4. No Grouping or Group By Clause: A view cannot be updated if it includes a GROUP BY,
HAVING, or similar clauses.
5. No Distinct: If the view contains the DISTINCT keyword, it is non-updatable because it
eliminates duplicate rows.
6. No Subqueries in the SELECT Clause: Subqueries in the SELECT list or the WHERE clause
prevent the view from being updatable.
7. No Join with Non-Updatable Views: If the view includes a JOIN and one of the tables is not
updatable, the entire view becomes non-updatable.
8. Primary Key or Unique Key: The view must include a primary key or a unique key of the
underlying base table for the view to be updatable.
9. No Derived Columns: The view cannot include derived columns (i.e., columns that are
computed or generated using expressions).

2. List the advantages of stored procedure and stored function.

1. Advantages of Stored Procedure:


● Code Reusability: Stored procedures allow you to write SQL code once and reuse it multiple
times throughout the database, reducing code duplication.
● Improved Performance: Since stored procedures are precompiled and stored in the
database, they run faster than executing separate SQL queries repeatedly.
● Reduced Network Traffic: When a stored procedure is called, only the procedure's name and
parameters are sent over the network rather than the entire SQL query, minimizing data
transfer.
● Enhanced Security: Stored procedures can be used to enforce database security by limiting
direct access to the underlying tables. Permissions can be granted for procedures rather
than tables.
● Maintainability: Any logic encapsulated in a stored procedure can be updated without
affecting the applications that use it, making the system easier to maintain.
● Transaction Control: Stored procedures support transaction control, ensuring that operations
like inserts, updates, and deletes are executed in a consistent manner.

2. Advantages of Stored Function:


● Modularity: Like stored procedures, functions allow modular programming by breaking down
complex operations into smaller, manageable functions.

65
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
● Return a Value: Stored functions must return a single value, making them highly useful in
computations or when processing data from the database.
● Call in SQL Statements: Stored functions can be used in SQL queries, making them more
flexible than stored procedures. You can use a function inside SELECT, WHERE, GROUP BY,
and ORDER BY clauses.
● Reusability: Just like stored procedures, stored functions can be reused multiple times,
improving code efficiency and reducing redundancy.
● Performance: Functions are stored in the database and precompiled, making them faster
than executing complex computations within SQL queries.

Suggested Reference:

1. “Database System Concepts”, 6th Edition by Abraham Silberschatz,


Henry F. Korth, S. Sudarshan, McGraw-Hill.
2. “An introduction to Database Systems”, C J Date, Pearson.
References used by the students:

66
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Experiment No: 8
1. Define the Trigger and explain it with syntax and examples.
2. Define cursor and explain its different types with syntax and examples.

Date:

Competency and PracticalSkills: Theory concept of cursor and triggers along with
syntax to create them in PL/SQL

Relevant CO: CO3


Objectives:
(a)To understand cursor and its types
(b)to understand need of triggers and various types of it.
(c) Know the syntax for creating cursor and triggers in DBMS
.
Equipment/Instruments: Pen and paper

Write answer of the Question here:

1. Trigger in SQL
A Trigger in SQL is a database object that automatically executes or "fires" when certain events occur in a database.
These events are typically related to Data Manipulation Language (DML) actions such as INSERT, UPDATE, or
DELETE. Triggers can be used to enforce business rules, validate data, maintain complex integrity constraints, or
automatically generate derived column values.

Syntax of a Trigger:

CREATE TRIGGER trigger_name


AFTER | BEFORE INSERT | UPDATE | DELETE
ON table_name
FOR EACH ROW
BEGIN
-- Trigger logic goes here --
END;

● AFTER | BEFORE: Defines whether the trigger will execute before or after the specified event.
● INSERT | UPDATE | DELETE: Specifies the event that activates the trigger.
● FOR EACH ROW: Indicates that the trigger is row-level, which means it executes once for each row
affected by the event.
● The code block inside BEGIN and END contains the logic to be executed.

2. Cursor in SQL
A Cursor is a database object used in SQL to retrieve, manipulate, and traverse through a set of rows returned by a
query. Cursors are commonly used in stored procedures and functions to process individual rows returned by a
SELECT statement one by one, instead of processing the entire result set at once.

67
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Types of Cursors:

1. Implicit Cursor: Automatically created by the database when a SELECT statement is executed, and
typically used for single-row queries.
2. Explicit Cursor: Defined explicitly by the programmer for handling multiple rows returned by a query.
This type of cursor requires declaration, opening, fetching, and closing.

Syntax for Explicit Cursor:


DECLARE cursor_name CURSOR FOR
SELECT column1, column2, ...
FROM table_name
WHERE condition;

-- Open the cursor —-


OPEN cursor_name;

-- Fetch rows from the cursor —-


FETCH cursor_name INTO variable1, variable2, ...;

-- Close the cursor —-


CLOSE cursor_name;

Types of Cursors:

1. Implicit Cursor: Used automatically by SQL for single-row queries.


2. Explicit Cursor: Defined by the user and useful for multi-row query handling.
3. Cursor Attributes:
○ %FOUND: Returns TRUE if a row was fetched successfully.
○ %NOTFOUND: Returns TRUE if no more rows were fetched.
○ %ROWCOUNT: Returns the number of rows fetched so far.
○ %ISOPEN: Returns TRUE if the cursor is still open.

Quiz:
1. How implicit cursor can be addressed in PL/SQL block?

DECLARE
v_emp_name employees.emp_name%TYPE;
v_salary employees.salary%TYPE;
BEGIN
-- Implicit cursor is used with SELECT INTO statement
SELECT emp_name, salary
INTO v_emp_name, v_salary
FROM employees
WHERE emp_id = 101;

-- Display the result


DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_emp_name);
DBMS_OUTPUT.PUT_LINE('Salary: ' || v_salary);
END;

68
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2. Compare implicit and explicit cursor

3. List the advantages of using Trigger?

Advantages of Using Triggers


Triggers provide several benefits in database management, helping ensure data integrity,
automating tasks, and maintaining business logic at the database level. Below are some key
advantages:

1. Automating Actions: Triggers can automate repetitive tasks like updating audit logs,
recalculating values, or synchronizing data between tables without needing external
programs.

2. Enforcing Business Rules: Triggers can be used to enforce complex business rules by
controlling what happens during specific database operations (e.g., preventing certain
updates or inserts based on custom logic).

3. Data Integrity Maintenance: Triggers ensure that data integrity constraints are enforced,
even when bypassing application-level checks (e.g., maintaining referential integrity or
ensuring that calculated columns are up to date).

4. Event-Driven Execution: Triggers respond to specific events (e.g., INSERT, UPDATE,


DELETE) without any external intervention, reducing the need for manual actions.

5. Centralized Control: Business logic embedded in triggers ensures consistency and prevents
having to duplicate logic in multiple places, like in various applications or client programs.
6. Auditing: Triggers are commonly used to maintain audit logs automatically whenever
changes are made to critical tables.

7. Security: Triggers can enforce security policies (e.g., prevent unauthorized changes to
sensitive data) by restricting certain operations.

69
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Suggested Reference:

1. “Database System Concepts”, 6th Edition by Abraham Silberschatz,


Henry F. Korth, S. Sudarshan, McGraw-Hill.
2. “An introduction to Database Systems”, C J Date, Pearson.
References used by the students:

70
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Experiment No: 9
1. Discuss serializability concepts with examples.

2. How does the Two-Phase locking protocol work? Also,


explain its different variants.

3. How does the Timestamp-based protocol execute?


4. Explain Database Recovery.

5. Define Authentication, data integrity, and data encryption.


Explain three different access control methods for data security.

Date:
Competency and PracticalSkills: Theory concept of Transaction and concurrent execution of
multiple transaction is studied along with issues and their solutions. Also solutions of database
recovery if transaction interrupted abnormally are also explained along with security of DBMS

Relevant CO: CO4


Objectives:
(a) To understand transaction and its concurrent execution with issues and possible solutions.

(b)to understand need of database recovery system


(c) to understand need of security along with solutions to secure DBMS
.
Equipment/Instruments: Pen and paper

Write answer of the Question here:

1. Serializability Concepts
Serializability in databases refers to ensuring that the outcome of executing concurrent transactions is the same as if
they were executed sequentially, one after the other. It’s a fundamental concept in maintaining the consistency of a
database in a multi-user environment. There are two types of serializability:

1. Conflict Serializability: This happens when two transactions that access the same data conflict in their
operations (one reads while the other writes). If the order of these conflicting operations can be rearranged
to achieve the same result as a serial schedule, the transactions are conflict serializable.
2. View Serializability: A schedule is view serializable if transactions produce the same result as a serial
execution, regardless of the order of their operations, as long as the operations produce the same final view
of the database.

Example of Serializability:

Let’s assume two transactions T1 and T2 operate on a shared variable A.

● T1: Read(A), A = A + 10, Write(A)


● T2: Read(A), A = A * 2, Write(A)

The schedules below are possible:

● Serial Schedule: Execute T1 completely, then T2 (T1 → T2), or vice versa (T2 → T1).
● Non-Serial Schedule: Interleave the operations of T1 and T2 (e.g., Read(A) by T1, then Read(A) by
T2, then modify and write by both).

71
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
A non-serial schedule would be considered serializable if it results in the same final value of A as the serial
execution.

2. Two-Phase Locking (2PL) Protocol


The Two-Phase Locking (2PL) protocol ensures serializability by dividing the execution of a transaction into two
distinct phases:

1. Growing Phase: In this phase, a transaction can only acquire locks and cannot release any locks. It keeps
acquiring locks on data items until it gets all the locks it needs.
2. Shrinking Phase: After the transaction releases its first lock, it can only release locks and cannot acquire
any new locks. No new locks can be obtained in this phase.

This mechanism prevents transactions from overlapping in a way that causes conflicts, ensuring serializability.

Variants of Two-Phase Locking:

1. Strict 2PL: A transaction holds all the exclusive (write) locks until it commits or aborts. This guarantees
recoverability and cascadeless schedules.
2. Rigorous 2PL: A stricter variant where both read and write locks are held until the transaction commits or
aborts, ensuring more stringent control over concurrency.

3.Timestamp-Based Protocol
The Timestamp-Based Concurrency Control Protocol uses timestamps to order the transactions. Each transaction
is assigned a unique timestamp when it starts, and this timestamp determines the transaction’s priority in accessing
data items. The idea is to ensure that the order of transaction execution is consistent with the timestamp order.

Each data item in the database is associated with two timestamps:

● Read timestamp (RTS): The largest timestamp of any transaction that successfully read the data item.
● Write timestamp (WTS): The largest timestamp of any transaction that successfully wrote the data item.

Execution:

● If a transaction T wants to write a data item, it checks if any transaction with a later timestamp has read or
written that item. If yes, T is aborted; otherwise, it proceeds.
● If a transaction T wants to read a data item, it checks if any transaction with a later timestamp has written
that item. If yes, T is aborted; otherwise, it proceeds.

This method avoids deadlocks and ensures serializability by ordering transactions based on their timestamps.

4. Database Recovery
Database recovery ensures the system can recover to a consistent state after a failure (e.g., system crash, power
failure, disk failure). The goal is to preserve atomicity and durability of transactions (ACID properties).

1. Types of Failures:
○ Transaction failure: When a transaction cannot be completed.
○ System failure: When the database system crashes.
○ Media failure: When the disk or storage device fails.
2. Recovery Techniques:
○ Deferred Update: Changes made by a transaction are not written to the database until it commits.
If there’s a crash before commit, nothing is written.

72
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
○ Immediate Update: Changes are written to the database before the transaction commits. Undo
and redo logs are maintained for recovery.
○ Shadow Paging: The system maintains two copies of the database (original and shadow). Changes
are made in a new version and swapped if successful.

Authentication, Data Integrity, and Data Encryption


1. Authentication: This is the process of verifying the identity of users or systems. Common methods include
passwords, biometrics, and multi-factor authentication (MFA).
2. Data Integrity: Ensures that data remains accurate and consistent over its lifecycle. Integrity checks,
checksums, and constraints in databases ensure that data is not altered or corrupted in unauthorized ways.
3. Data Encryption: The process of converting data into a coded format to prevent unauthorized access.
Encryption algorithms like AES, RSA, etc., are used to ensure that even if the data is intercepted, it cannot
be read without the correct decryption key.

5. Access Control Methods for Data Security


1. Discretionary Access Control (DAC): In DAC, the owner of the data determines who can access it.
Access is granted through permissions or privileges. For example, file system permissions where users can
define read, write, or execute permissions.
2. Mandatory Access Control (MAC): In MAC, the system determines access based on fixed security
policies. Users cannot change these access rules. For example, in a classified system, users can access data
only if they have the necessary security clearance.
3. Role-Based Access Control (RBAC): Access is granted based on the role of the user within an
organization. Users are assigned roles, and roles have predefined permissions. This simplifies management
and ensures that users only have access to the information they need for their role.

Quiz:
1. Write down any transaction which is view serializable. Justify your answer.

View Serializability is a less strict form of serializability compared to conflict


serializability. A schedule is view serializable if it produces the same final
outcome as a serial schedule, meaning the transactions read and write the same
data values as they would in a serial schedule, even if their execution order
differs.

Example: Consider two transactions, T1 and T2, that operate on a shared variable A.

● T1: Reads A, modifies A, and writes it back.


● T2: Reads A, modifies A, and writes it back.

Schedule:

1. T1: Read(A)
2. T2: Read(A)
3. T1: Write(A)
4. T2: Write(A)

This schedule is not conflict serializable because T1 and T2 both read and write A, creating a conflict
that cannot be resolved by reordering operations.

73
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
However, the schedule is view serializable if:

● Both transactions see the same initial value of A.


● The final value of A is the same as that produced by either of the serial schedules (T1 → T2
or T2 → T1).

In this case, the write operations produce the same final value, even though the transactions are
interleaved. Therefore, the schedule is view serializable.

2. Explain Log based recovery method with example

Log-Based Recovery is a technique used to ensure that a database can recover


from failures by using a transaction log to record all modifications made to the
database. The log contains information necessary to redo or undo transactions in
case of system failure.

Two types of log records are maintained:

1. Undo logs: These allow the system to reverse the effects of a transaction that was not
completed successfully.
2. Redo logs: These allow the system to repeat the effects of a successfully committed
transaction, in case the changes were not yet written to the database when the failure
occurred.

Example:
Consider a transaction T1 that modifies a value in the database.

● Before modification, the system logs the original value of the data (undo log).
● After modification, the new value is logged (redo log).

Transaction log:

● [START T1]: Mark the beginning of transaction T1.


● [T1, A, old_value, new_value]: Record that T1 changes data item A from
old_value to new_value.
● [COMMIT T1]: Mark that T1 has successfully completed.

If a failure occurs after [START T1] but before [COMMIT T1], the system checks the log. Since T1
was not committed, the system undoes the changes using the old value (undo log).

If a failure occurs after [COMMIT T1] but before the new value is written to disk, the system redoes
the transaction using the new value (redo log).

Steps in Log-Based Recovery:


1. Undo Phase: The system looks for incomplete transactions and undoes their effects using
the undo logs.
2. Redo Phase: The system replays completed transactions by using redo logs to ensure their
changes are properly applied to the database.

74
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Example of Log-Based Recovery Process:

1. Assume the following transaction:

T1:
Read(A)
A = A + 100
Write(A)

2. The corresponding log entries might be:

[START T1]
[T1, A, 500, 600] -- T1 changes A from 500 to 600
[COMMIT T1]

● If a failure happens after the commit but before the changes are permanently saved in the
database, the system can redo T1 by applying the logged changes (A = 600).
● If the failure happens before the commit, the system can undo the transaction by restoring A
to its original value (A = 500).

This method ensures the Atomicity and Durability properties of transactions in the ACID model.

Suggested Reference:

1. “Database System Concepts”, 6th Edition by Abraham Silberschatz,


Henry F. Korth, S. Sudarshan, McGraw-Hill.
2. “An introduction to Database Systems”, C J Date, Pearson.
References used by the students:

75
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Experiment No: 10
1. Discuss the Steps of Query processing with a diagram.
2. How is query cost measured? Explain with an example.
3. How does join operation work in query processing?
4. How is query optimized?
Date:

Competency and PracticalSkills: Theory concept of Query processing and Optimization

Relevant CO: CO5


Objectives:
(a)To understand Steps of Query Processing
(b)to understand the process of measurement of query cost

(c) appreciate the concept of how query can be optimized to achieve least cost involved.

(d)understand complete steps of join query execution.


.
Equipment/Instruments: Pen and paper

Write answer of the Question here:

1. Steps of Query Processing


Query processing is the process of translating a high-level SQL query into an efficient execution plan. This involves
multiple steps, including parsing, optimization, and execution.

Here are the main steps of query processing:

1. Parsing and Translation:


○ The SQL query is parsed to check its syntax and semantics.
○ The query is translated into a parse tree or logical query plan.
○ During parsing, the system verifies the query is valid, such as checking for correct table names,
column names, and data types.
2. Logical Query Plan:
○ The parse tree is translated into a relational algebra expression (logical query plan), which
captures the relational operations required to satisfy the query.
○ This plan shows the sequence of operations that need to be performed on the data, such as
selection, projection, join, etc.
3. Optimization:
○ The system applies optimization techniques to improve the efficiency of the query.
○ The query optimizer chooses the best strategy or execution plan by considering multiple possible
ways to execute the logical query plan.
○ Techniques like join reordering, index utilization, and predicate pushdown are used to reduce
execution cost.
4. Physical Query Plan:
○ The optimized logical query plan is converted into a physical query plan that specifies the actual
methods (e.g., nested-loop join, hash join) and algorithms used to execute the operations.
5. Execution:
○ The physical query plan is executed, and the result is returned to the user.
○ The database engine fetches data, performs necessary computations (joins, filters, sorting), and
outputs the result.

76
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Diagram of Query Processing
Here’s a simplified diagram of the steps involved:

+------------------------+
| SQL Query |
+------------------------+
|
V
+------------------------+
| Parsing & |
| Translation (Syntax) |
+------------------------+
|
V
+------------------------+
| Logical Query Plan |
| (Relational Algebra) |
+------------------------+
|
V
+------------------------+
| Query Optimization |
+------------------------+
|
V
+------------------------+
| Physical Query Plan |
+------------------------+
|
V
+------------------------+
| Query Execution |
+------------------------+
|
V
+------------------+
| Result Set |
+------------------+
2. How Query Cost is Measured
The cost of a query is typically measured in terms of resource consumption, including:

1. Disk I/O: The number of disk accesses (reads/writes) required to execute the query, which is often the
dominant cost.
2. CPU Usage: The computational cost involved in performing operations such as sorting, joining, and
filtering.
3. Network Usage: If the data is distributed across different servers, network cost may also be a factor.

77
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Example:

SELECT * FROM Employees WHERE department = 'IT';

Here, the cost of the query would depend on:

● Whether there’s an index on the department column (if yes, the cost is lower).
● The size of the Employees table.
● The number of rows that satisfy the condition.

Without an index, a full table scan is required, which incurs a higher disk I/O cost as the entire table must be read.
With an index, the database can directly look up the rows, reducing the I/O cost.

3. How Join Operation Works in Query Processing


A join operation combines rows from two or more tables based on a related column between them. In query
processing, several algorithms are used to execute join operations efficiently.

Here are the primary types of joins used:

1. Nested-Loop Join:
○ For each row in the outer table, the system searches for matching rows in the inner table.
○ This can be inefficient for large tables, as it requires comparing every row of the outer table with
every row of the inner table.

Example:

SELECT *

FROM Employees e

JOIN Departments d

ON e.department_id = d.department_id;

2. Hash Join:
○ The database hashes one of the tables into an in-memory hash table, then probes the other table to
find matching rows.
○ It is faster than nested-loop join, especially when tables are large and there are many rows to
match.
3. Sort-Merge Join:
○ Both tables are sorted on the join key, and then the sorted tables are merged together.
○ This is efficient when both tables are already sorted, but sorting can add overhead if the tables are
unsorted.

4. Query Optimization
Query optimization refers to the process of choosing the most efficient execution plan for
a query. The optimizer explores different possible plans and chooses the one with the
lowest cost.

78
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Techniques for Query Optimization:

1. Rewriting the Query:


○ The query can be rewritten into an equivalent, but more efficient, form.
○ For example, subqueries can be rewritten into joins for efficiency.

SELECT *

FROM Employees

WHERE department IN (SELECT department FROM Departments);

can be rewritten as:

SELECT e.*

FROM Employees e

JOIN Departments d

ON e.department = d.department;

2. Predicate Pushdown:
○ Filters or conditions are applied as early as possible in the query plan to
reduce the number of rows processed.
○ For instance, in a join, it’s better to apply WHERE conditions before
performing the join to filter out unnecessary rows.
3. Join Reordering:
○ Changing the order in which joins are performed can significantly affect
performance.
○ The optimizer may reorder joins to minimize the intermediate result size,
thus reducing the processing cost.
4. Index Utilization:
○ Using an index can significantly reduce the cost of retrieving rows, as the
system can avoid scanning the entire table.
○ Indexes are used to optimize WHERE, JOIN, and ORDER BY clauses.

Example of Query Optimization

SELECT *

FROM Orders o

79
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
JOIN Customers c ON o.customer_id = c.customer_id

WHERE o.order_date = '2023-01-01';

Optimized Plan:

● Apply the WHERE clause to the Orders table first to filter the orders for the given
date.
● Then, join the filtered Orders table with the Customers table.

This reduces the number of rows involved in the join, improving efficiency. If an index
exists on order_date, it will be used to speed up the selection of rows.

Quiz:
1. How query can be parsed? Explain using example.

Parsing is the first step in query processing, where the SQL query is analyzed for
its syntax and semantics. The SQL query is converted into a parse tree or syntax
tree. This tree represents the query structure, ensuring that the query is valid
before proceeding to optimization and execution.

Here’s how a query is parsed:

1. Lexical Analysis:
○ The SQL query string is broken down into smaller units called tokens (keywords,
identifiers, operators, etc.).
2. Syntax Analysis:
○ These tokens are checked against SQL grammar rules to ensure that the query is
syntactically correct. If the syntax is incorrect, the query is rejected with an error
message.
3. Semantic Analysis:
○ The parsed query is checked for semantic correctness, like verifying if the table and
column names exist in the database, if data types are correct, etc.
4. Parse Tree Generation:
○ A parse tree (or abstract syntax tree) is generated from the query. This tree
represents the structure and elements of the SQL query.

Example: Parsing an SQL Query

Consider the following SQL query:

SELECT name, age FROM Employees WHERE department = 'IT';

80
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
● Lexical Analysis: The query is split into tokens: SELECT, name, ,, age, FROM, Employees,
WHERE, department, =, 'IT'.
● Syntax Analysis: The system checks if the sequence of tokens follows SQL grammar rules.
For example, SELECT must be followed by column names, and FROM must be followed by a
table name.
● Semantic Analysis: The system verifies if the Employees table exists and if name, age, and
department are valid columns in that table.
● Parse Tree Generation: A parse tree is generated to represent the structure of the query:

SELECT
|__ Columns: name, age
|__ FROM: Employees
|__ WHERE: department = 'IT'

The query then proceeds to the optimization and execution phases after parsing.

2. With the help of example show how single query can have
multiple SQL statements.
In some cases, a single query may involve multiple SQL statements executed together. This is
often achieved using UNION, subqueries, or transactions. Each individual statement may
perform a separate task, but they work together to achieve a single result.

1. Using UNION for Multiple SQL Statements

The UNION operator combines the results of two or more SELECT statements into a single result set. Each SELECT
statement can be thought of as an individual query.

Example:

SELECT name, age FROM Employees WHERE department = 'IT'


UNION
SELECT name, age FROM Employees WHERE department = 'HR';

● Here, two separate SQL queries are executed, one to fetch employees from the IT department and one from
HR. The results of both queries are combined and returned as a single result set.

2. Using Subqueries for Multiple SQL Statements

A subquery is a query inside another query. It allows you to execute multiple SQL statements in a single overall
query.

Example:

SELECT name, age


FROM Employees
WHERE department = (SELECT department FROM Managers WHERE manager_name
= 'John Doe');

81
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
● In this case, the inner query (SELECT department FROM Managers WHERE manager_name = 'John
Doe') is executed first to find the department of manager John Doe. Then, the outer query uses this result
to fetch employees from that department.

3. Using Transactions for Multiple SQL Statements

Transactions allow multiple SQL statements to be grouped together as a single unit of work, executed sequentially.

Example:

BEGIN;
INSERT INTO Employees (name, age, department) VALUES ('Alice', 30, 'IT');
UPDATE Departments SET total_employees = total_employees + 1 WHERE
department_name = 'IT';
COMMIT;

● Here, two SQL statements (an INSERT and an UPDATE) are part of a single transaction. Both statements
must succeed for the transaction to be committed. If any statement fails, the entire transaction is rolled back.

In each of these cases, multiple SQL statements are logically combined into a single query, allowing for more
complex operations in a single execution.

Suggested Reference:

1. “Database System Concepts”, 6th Edition by Abraham Silberschatz,


Henry F. Korth, S. Sudarshan, McGraw-Hill.

2. “An introduction to Database Systems”, C J Date, Pearson.


References used by the students:

82
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062

You might also like