DBMS Lab Manual
DBMS Lab Manual
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.
Explanation:
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)
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:
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.
13
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
5. List all data from table CUSTOMERS.
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.
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.
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:
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)
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
Observations:
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.
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).
Explanation:
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.
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.
29
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
4. Count total number of customers
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.
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;
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.
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.
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:
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
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.
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:
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.
53
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(k) Find only those routes that originate in madras and terminate at cochin.
(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’.
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’.
57
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
(e) Which bus runs the minimum distance?
(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.
(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.
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)
);
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.
Date:
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.
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.
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).
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:
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
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:
● 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.
Types of Cursors:
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;
68
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
2. Compare implicit and explicit cursor
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).
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:
70
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Experiment No: 9
1. Discuss serializability concepts with examples.
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
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:
● 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.
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.
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.
● 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.
Quiz:
1. Write down any transaction which is view serializable. Justify your answer.
Example: Consider two transactions, T1 and T2, that operate on a shared variable A.
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:
In this case, the write operations produce the same final value, even though the transactions are
interleaved. Therefore, the schedule is view serializable.
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:
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).
74
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
Example of Log-Based Recovery Process:
T1:
Read(A)
A = A + 100
Write(A)
[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:
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:
(c) appreciate the concept of how query can be optimized to achieve least cost involved.
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:
● 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.
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:
SELECT *
FROM Employees
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.
SELECT *
FROM Orders o
79
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062
JOIN Customers c ON o.customer_id = c.customer_id
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.
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.
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.
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:
● 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.
A subquery is a query inside another query. It allows you to execute multiple SQL statements in a single overall
query.
Example:
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.
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:
82
Name :- PANCHAL VISHVAS PANKAJKUMAR
Enrollment No. :- 230160107062