Dbms Important Questions
Dbms Important Questions
Dbms Important Questions
2 MARKS
1. Define Physical Independence.
It refers to the ability to change the physical storage structures of a database without
affecting its conceptual schema or logical design.
3. Define Constraints
Constraints are rules enforced on data in a database to ensure its accuracy and integrity.
Examples include primary key, foreign key, and NOT NULL constraints.
8. Explain Trigger.
A trigger is a procedural code in a DBMS that automatically executes in response to
certain events on a particular table or view, like INSERT, UPDATE, or DELETE.
9. Define Serializability.
It is the concept in transaction management that ensures that the concurrent execution
of transactions results in a system state that could be obtained if transactions were
executed serially.
16 MARKS
Table control
LOCK LOCK TABLE table_name IN lock_mode;
concurrency
Call a PL/SQL or
CALL CALL procedure_name(arguments);
JAVA subprogram
Removes previously
REVOKE [GRANT OPTION FOR]
granted privileges from a
privilege_type [(column_list)] ON
REVOKE user account, taking away
[object_type] object_name FROM
their access to certain
user [CASCADE];
database objects or actions.
Example of Entities:
A university may have some departments. All these departments employ various lecturers
and offer several programs.
Relationship
Relationship is nothing but an association among two or more entities. E.g., Tom works in
the Chemistry department.
Entities take part in relationships. We can often identify relationships with verbs or verb
phrases.
Weak Entities
A weak entity is a type of entity which doesn’t have its key attribute. It can be identified
uniquely by considering the primary key of another entity. For that, weak entity sets need to
have participation.
2.One-to-many:
One entity from entity set X can be associated with multiple entities of entity set Y, but an
entity from entity set Y can be associated with at least one entity.
For example, one class is consisting of multiple students.
3. Many to One
More than one entity from entity set X can be associated with at most one entity of entity set
Y. However, an entity from entity set Y may or may not be associated with more than one
entity from entity set X.
For example, many students belong to the same class.
4. Many to Many:
One entity from X can be associated with more than one entity from Y and vice versa.
For example, Students as a group are associated with multiple faculty members, and faculty
members can be associated with multiple students.
First Last
Aisha Arora
Bikash Dutta
Makku Singh
First Last
Raju Chopra
FirstN LastN
Raj Kumar
Honey Chand
Makku Singh
Karan Rao
First Last
Aisha Arora
Bikash Dutta
Makku Singh
Raju Chopra
Raj Kumar
Honey Chand
Karan Rao
2. Student INTERSECTION Faculty :
Student ∩ Faculty
First Last
Makku Singh
First Last
Aisha Arora
Bikash Dutta
Raju Chopra
Not-Null Constraints
It specifies that within a tuple, attributes overs which not-null constraint is specified must not
contain any null value.
Example:
Let, the not-null constraint be specified on the “Semester” attribute in the relation/table given
below, then the data entry of 4th tuple will violate this integrity constraint, because the
“Semester” attribute in this tuple contains null value. To make this database instance a legal
instance, its entry must not be allowed by database management system.
21CSE103 Mukesh 20
Mukesh 5th 20
Key Constraints
Keys are the entity set that are used to identify an entity within its entity set uniquely. An entity
set can contain multiple keys, bit out of them one key will be primary key. A primary key is
always unique, it does not contain any null value in table.
Example:
Student_id Name Semester Age
20 Chandigarh
21 Punjab
25 Delhi
6. Articulate the join functions with student academic and personal databases.
Join functions in relational databases are used to retrieve data from two or more related tables
based on a common field between them. When dealing with student information systems, it is
common to have separate databases for academic and personal information of students.
These databases can be linked using a primary key and foreign key relationship, typically
based on a unique identifier such as student_id.
In this section, we will explore various join functions (INNER JOIN, LEFT JOIN, RIGHT
JOIN, FULL OUTER JOIN, and CROSS JOIN) by applying them to a Student Personal
Database and a Student Academic Database. These functions help in fetching combined
records that provide comprehensive information about students, such as their academic
performance along with their personal details.
1. INNER JOIN
The INNER JOIN retrieves only those records where there is a match between the two tables.
In the case of student databases, this means that only students who have records in both the
personal and academic tables will be included in the result set.
Example Scenario:
We have two tables:
● student_personal: Contains personal information such as student_id, name, email, and
phone_number.
● student_academic: Contains academic information such as student_id, course_name,
grade, and semester.
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
INNER JOIN student_academic sa ON sp.student_id = sa.student_id;
Explanation:
● In this query, we are joining the student_personal (aliased as sp) and student_academic
(aliased as sa) tables based on the student_id field.
● The result will include only those students who have both personal and academic
records, ensuring that there are matches in both tables.
● For example, if a student exists in the personal database but doesn’t have any academic
record, that student will not appear in the result.
Sample Output:
student_id name email course_name grade semester
5. CROSS JOIN
The CROSS JOIN returns the Cartesian product of two tables, which means every row from
the first table is paired with every row from the second table.
Example Scenario:
Retrieve a combination of every student from the personal database with every academic record
(not commonly used, but useful in specific cases like creating testing datasets).
SQL Query:
sql
SELECT sp.student_id, sp.name, sp.email, sa.course_name, sa.grade, sa.semester
FROM student_personal sp
CROSS JOIN student_academic sa;
Explanation:
● This query will return every possible combination of student personal details and
academic details, regardless of whether they are related or not.
Sample Output:
student_id name email course_name grade semester
It is in 1NF.
All non-key attributes are fully functionally dependent on the entire primary key. In other
words, no partial dependencies are allowed (i.e., attributes should depend on the entire
primary key, not a part of it).
Example: For a composite key, each non-key attribute must depend on the entire key, not just
part of it.
It is in 2NF.
All attributes are functionally dependent only on the primary key. There should be no
transitive dependencies (i.e., non-key attributes should not depend on other non-key
attributes).
Example: If in a table, City depends on ZIP Code, which in turn depends on Address, the
transitive dependency must be eliminated by creating separate tables for ZIP codes and cities.
iv) BCNF (Boyce-Codd Normal Form) & 4NF (Fourth Normal Form)
BCNF: A table is in BCNF if:
It is in 3NF.
Every determinant is a superkey. This means that for every functional dependency A -> B, A
must be a candidate key.
Example: Consider a table where a non-candidate key determines part of the primary key.
This table needs to be decomposed to achieve BCNF.
8. What do you understand by PL/SQL cursors? and Explain its various types.
In PL/SQL (Procedural Language for SQL), a cursor is a pointer or a handle to a context area,
which is a memory region where Oracle executes SQL statements. When you execute an SQL query,
Oracle needs to process and store the result set in a context area. Cursors allow you to fetch rows
from this result set one at a time, which is especially useful when working with queries that return
multiple rows.
IF SQL%ROWCOUNT = 1 THEN
DBMS_OUTPUT.PUT_LINE('1 row updated successfully.');
END IF;
END;
In this example:
● An implicit cursor is created and executed for the UPDATE statement.
● SQL%ROWCOUNT is an implicit cursor attribute that returns the number of rows
affected by the SQL operation.
Common Implicit Cursor Attributes:
● SQL%FOUND: Returns TRUE if one or more rows are affected by the SQL statement.
● SQL%NOTFOUND: Returns TRUE if no rows are affected.
● SQL%ROWCOUNT: Returns the number of rows affected by the SQL statement.
2. Explicit Cursors
Explicit cursors are created and managed by the programmer when a query returns more than
one row. In these cases, you need to define a cursor, open it, fetch the rows into variables, and
finally close it. Explicit cursors provide greater control over the result set, allowing the
programmer to process each row one at a time.
Steps in Using Explicit Cursors:
1. Declare the cursor: Define the SQL query that will be associated with the cursor.
2. Open the cursor: Execute the query and allocate memory for the result set.
3. Fetch data: Retrieve rows from the cursor into PL/SQL variables one row at a time.
4. Close the cursor: Release the memory associated with the cursor.
Example:
sql
Copy code
DECLARE
CURSOR employee_cursor IS
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = 10;
v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN employee_cursor;
LOOP
FETCH employee_cursor INTO v_employee_id, v_first_name, v_last_name;
EXIT WHEN employee_cursor%NOTFOUND;
v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN param_cursor(10); -- Passing department_id = 10 to the cursor.
LOOP
FETCH param_cursor INTO v_employee_id, v_first_name, v_last_name;
EXIT WHEN param_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee_id || ', Name: ' || v_first_name || ' ' ||
v_last_name);
END LOOP;
CLOSE param_cursor;
END;
o Here, the cursor param_cursor accepts a department ID as a parameter and
retrieves employee information based on that.
3. Ref Cursor (Cursor Variables)
o A REF CURSOR (cursor variable) allows for more flexibility since it can point
to different result sets at runtime.
o Unlike regular explicit cursors, a REF CURSOR is not tied to a particular query.
It can be passed as a parameter between procedures and can dynamically
associate itself with different queries during execution.
Example:
sql
DECLARE
TYPE ref_cursor_type IS REF CURSOR;
emp_cursor ref_cursor_type;
v_employee_id employees.employee_id%TYPE;
v_first_name employees.first_name%TYPE;
v_last_name employees.last_name%TYPE;
BEGIN
OPEN emp_cursor FOR
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = 20;
LOOP
FETCH emp_cursor INTO v_employee_id, v_first_name, v_last_name;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('ID: ' || v_employee_id || ', Name: ' || v_first_name || ' ' ||
v_last_name);
END LOOP;
CLOSE emp_cursor;
END;
Advantages of Cursors:
1. Row-by-Row Processing: Cursors allow you to fetch and process rows one by one,
which is useful for handling large datasets where batch processing is required.
2. Control over Execution: Explicit cursors give more control over how and when data
is retrieved, enabling more complex and flexible operations.
3. Dynamic Query Handling: With REF CURSOR, you can handle different queries
dynamically, making it useful in scenarios where the SQL statement might change
during execution.
Disadvantages of Cursors:
1. Performance Overhead: Cursors can slow down performance, especially when used
in loops for large datasets, as row-by-row processing is typically slower than bulk
operations.
2. Memory Usage: Cursors allocate memory for the result set, which might lead to higher
memory usage, especially if not managed properly (e.g., failing to close cursors).
3. Complexity: The use of cursors can add complexity to PL/SQL code, making it harder
to debug and maintain.
● If a transaction succeeds, all changes made during the transaction are saved to the
database.
● If a transaction fails at any point, all changes made are rolled back, and the database is
left as it was before the transaction began.
In simpler terms, atomicity guarantees that a transaction is "all or nothing." It ensures complete
execution or total rollback, protecting the database from partial updates.
Example:
Imagine a banking transaction where money is being transferred from Account A to Account
B. The transaction consists of two steps:
1. Deducting the amount from Account A.
2. Adding the same amount to Account B.
If the system fails after the deduction from Account A but before the addition to Account B,
without atomicity, the money would be deducted from Account A, and Account B would not
receive the amount, leading to an inconsistent state.
However, because of atomicity, if such a failure occurs, the system rolls back the deduction
from Account A, ensuring that no partial transaction takes place.
Implementation in DBMS:
● DBMS systems use a transaction log to record changes. If a failure occurs, the DBMS
uses the log to rollback incomplete transactions and restore the database to a consistent
state.
● Commit and Rollback operations are used to enforce atomicity. A transaction is
committed if it successfully completes, and it is rolled back if it encounters an error.
2. Consistency
Consistency ensures that a transaction brings the database from one valid state to another valid
state, maintaining all predefined rules, integrity constraints, and database invariants.
In other words, after the transaction is executed, the database should not violate any integrity
constraints (such as unique keys, foreign keys, data types, etc.) defined on the schema. The
database remains in a valid state before and after the transaction, even if the transaction alters
the data.
Example:
Consider a scenario where a bank has a rule that the balance of any account cannot go below
zero. If a transaction attempts to deduct more money than the account holds, the system should
reject the transaction to maintain consistency. Thus, a transaction should only be allowed if it
keeps the database in a consistent state according to all rules and constraints.
Implementation in DBMS:
● DBMS enforces consistency by applying integrity constraints. Any operation that
violates these constraints is aborted and rolled back.
● Constraints like primary keys, foreign keys, and check constraints are used to ensure
the consistency of the database throughout the transaction.
3. Isolation
Isolation ensures that the execution of multiple transactions occurs in isolation from one
another. Even if multiple transactions are executed concurrently, they should not interfere with
each other. Each transaction must be isolated from others, meaning that the result of each
transaction should be the same as if it were executed alone, without any other transactions
running simultaneously.
This property is critical for maintaining concurrency control in multi-user environments,
where several users or applications might access the database at the same time.
Example:
Consider two transactions happening at the same time:
● Transaction 1: Withdraws money from an account.
● Transaction 2: Checks the balance of the same account.
Without isolation, Transaction 2 might read the balance after the withdrawal but before the
transaction is committed, leading to inaccurate data. However, with isolation, Transaction 2
either sees the balance before Transaction 1 or after Transaction 1, but not during it.
Isolation Levels in DBMS:
DBMS systems implement different isolation levels to balance concurrency and performance:
● Read Uncommitted: A transaction may read data that is not yet committed by other
transactions (can lead to dirty reads).
● Read Committed: A transaction can only read data that has been committed (prevents
dirty reads, but other phenomena like non-repeatable reads may occur).
● Repeatable Read: A transaction can read the same data multiple times without seeing
any changes from other transactions (prevents non-repeatable reads).
● Serializable: The strictest level of isolation where transactions are executed
sequentially to ensure complete isolation.
4. Durability
Durability ensures that once a transaction has been committed, its changes are permanent.
Even in the event of a system crash or power failure, the changes made by the transaction are
saved and cannot be undone. This property guarantees that committed data will be available in
the database even after unexpected events.
Example:
Imagine a scenario where a transaction updates a customer’s information in the database. Once
the transaction commits, this updated information must be stored permanently, even if the
system crashes immediately afterward.
Implementation in DBMS:
● Write-ahead logging (WAL) is a mechanism used to ensure durability. Before making
any changes to the actual database, the DBMS writes the transaction details to a log
file. Once the log is written, the changes are made to the database.
● In case of a crash, the DBMS uses the log to restore the committed transactions,
ensuring that no committed data is lost.
-- Calculate total allowances (this can be more complex based on allowance structure)
v_allowances := 0.20 * v_basic_salary; -- Example: Allowance is 20% of basic salary
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ID not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred during payroll generation.');
END;
5. Generating Employee Payslip
A simple payslip can be generated by fetching the payroll details from the database. Here's a
basic SQL query to display the payslip for an employee:
sql
Copy code
SELECT e.emp_name, p.payroll_month, p.basic_salary, p.allowances, p.deductions,
p.net_salary
FROM Employee e
JOIN Payroll p ON e.emp_id = p.emp_id
WHERE e.emp_id = 101 AND p.payroll_month = 'September';
Output Example (payslip):
yaml
Employee Name: John Doe
Payroll Month: September
Basic Salary: 50,000
Allowances: 10,000
Deductions: 8,000
Net Salary: 52,000
6. User Interface for Payroll System
In a full-fledged system, a graphical user interface (GUI) can be built using any web framework
like Java (JSP/Servlets), Python (Django/Flask), or PHP. The interface will allow users to:
● Add new employees
● Update salary details
● Generate payroll
● View and print payslips
7. Advanced Features to Include
● Taxation Rules: Different employees may have different tax slabs or deductions, so
it’s essential to implement a tax table with variable rates based on income levels.
● Leave Management: Deduct salary for unpaid leaves.
● Bonus Calculation: Vary the bonus based on employee performance or company
policies.
● Reports: Monthly or yearly payroll reports for management, tax compliance, or
auditing purposes.
UPDATE Employee
SET department = 'HR'
WHERE empno = 101;
Step 7: Displaying Data after Alteration
After adding the department and updating values, you can retrieve the data using the following
query:
sql
SELECT * FROM Employee;
Result:
empno name salary department
● Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address.
Code is Primary Key for Bank Entity.
● Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone
Number and Address.
Customer_id is Primary Key for Customer Entity.
● Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address.
Branch_id is Primary Key for Branch Entity.
● Account Entity : Attributes of Account Entity are Account_number, Account_Type
and Balance.
Account_number is Primary Key for Account Entity.
● Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount.
Loan_id is Primary Key for Loan Entity.
Relationships are :
1 A 802
2 B 403
3 C 604
4 D 705
5 E 606
6 F NULL
1. Inner Join
An Inner Join returns only the rows that have matching values in both tables. If there is no
match, the rows are not included in the result.
Syntax:
sql
SELECT column_names
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example:
Consider two tables, Students and Courses.
Students Table:
student_id name
101 John
102 Jane
103 Alice
Courses Table:
sql
SELECT Students.name, Courses.course_name
FROM Students
INNER JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name
John Math
Jane Physics
2. Left (Outer) Join
A Left Join returns all the rows from the left table and the matching rows from the right table.
If no match is found, NULL values are returned for columns from the right table.
Syntax:
sql
SELECT column_names
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Example:
Using the same Students and Courses tables, let's perform a Left Join to get all students and
their enrolled courses (including students who are not enrolled in any courses):
sql
SELECT Students.name, Courses.course_name
FROM Students
LEFT JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name
John Math
Jane Physics
Alice NULL
John Math
Jane Physics
NULL Chemistry
4. Full (Outer) Join
A Full Outer Join returns all the rows when there is a match in either the left or right table. If
there is no match, NULL values are returned for the missing side.
Syntax:
sql
SELECT column_names
FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;
Example:
Let’s retrieve all students and all courses, including students without courses and courses
without students:
sql
SELECT Students.name, Courses.course_name
FROM Students
FULL OUTER JOIN Courses
ON Students.student_id = Courses.student_id;
Result:
name course_name
John Math
Jane Physics
Alice NULL
NULL Chemistry
5. Cross Join
A Cross Join returns the Cartesian product of two tables, meaning every row from the first
table is combined with every row from the second table.
Syntax:
sql
SELECT column_names
FROM table1
CROSS JOIN table2;
Example:
Let’s perform a Cross Join between the Students and Courses tables:
sql
SELECT Students.name, Courses.course_name
FROM Students
CROSS JOIN Courses;
Result:
name course_name
John Math
John Physics
John Chemistry
Jane Math
Jane Physics
Jane Chemistry
name course_name
Alice Math
Alice Physics
Alice Chemistry
6. Self Join
A Self Join is a join where a table is joined with itself. This is often useful for comparing rows
within the same table.
Syntax:
sql
SELECT A.column_name, B.column_name
FROM table_name A, table_name B
WHERE condition;
Example:
Suppose we have an Employees table with a hierarchical structure (e.g., a manager supervises
other employees). We want to list all employees and their managers.
Employees Table:
emp_id name manager_id
1 John NULL
2 Jane 1
3 Alice 1
4 Bob 2
We can use a Self Join to retrieve the employee names along with their respective manager
names:
sql
SELECT A.name AS Employee, B.name AS Manager
FROM Employees A
LEFT JOIN Employees B
ON A.manager_id = B.emp_id;
Result:
Employee Manager
John NULL
Jane John
Alice John
Bob Jane
17. What do you understand by PL/SQL Trigger? and Explain with suitable example.
A PL/SQL Trigger is a named block of PL/SQL code that automatically executes (or "fires") in
response to certain events on a particular table or view. Triggers are used to enforce business rules,
maintain data integrity, and automate certain tasks within the database. They are invoked
automatically by the database, ensuring that actions are taken consistently whenever data
modifications occur.
Types of Triggers
There are primarily two types of triggers in PL/SQL:
1. Row-Level Triggers: These triggers fire for each row affected by a triggering event.
For example, if an INSERT operation affects five rows, the row-level trigger executes
five times.
2. Statement-Level Triggers: These triggers fire once for each triggering event,
regardless of how many rows are affected. For instance, if an INSERT operation affects
five rows, the statement-level trigger executes only once.
Triggers can also be classified based on the timing of their execution:
● BEFORE Trigger: Executes before the triggering event (e.g., before an INSERT,
UPDATE, or DELETE operation).
● AFTER Trigger: Executes after the triggering event.
Syntax of PL/SQL Trigger
The basic syntax of creating a trigger is as follows:
sql
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
[FOR EACH ROW]
BEGIN
-- PL/SQL code to execute
END;
Example of a PL/SQL Trigger
Let’s consider a scenario where we have an Employees table. We want to create a trigger that
automatically updates a last_updated timestamp column whenever an employee's salary is
updated.
Step 1: Create the Employees Table
First, we’ll create the Employees table with the necessary columns:
sql
CREATE TABLE Employees (
emp_id NUMBER PRIMARY KEY,
name VARCHAR2(100),
salary NUMBER(10, 2),
last_updated TIMESTAMP
);
Step 2: Create the Trigger
Next, we’ll create a trigger that updates the last_updated column whenever an employee’s
salary is modified.
sql
CREATE OR REPLACE TRIGGER trg_salary_update
BEFORE UPDATE OF salary
ON Employees
FOR EACH ROW
BEGIN
:NEW.last_updated := SYSTIMESTAMP; -- Set the last_updated to the current timestamp
END;
Explanation:
● Trigger Name: trg_salary_update.
● Timing: BEFORE UPDATE OF salary means this trigger will fire before an update
operation specifically on the salary column.
● Target Table: The trigger is defined on the Employees table.
● FOR EACH ROW: This clause indicates that the trigger will execute once for each
row affected by the update operation.
● : A PL/SQL context variable that holds the new value of the row being modified. In this
case, we assign the current timestamp (SYSTIMESTAMP) to the last_updated column.
Step 3: Testing the Trigger
Now, let’s insert some initial data into the Employees table and test the trigger.
sql
INSERT INTO Employees (emp_id, name, salary, last_updated)
VALUES (1, 'John Doe', 50000, SYSTIMESTAMP);
In this example, the last_updated column for John Doe should reflect the current timestamp
when his salary was updated.
Advantages of Using Triggers
1. Automatic Actions: Triggers allow automatic execution of code in response to specific
changes in the database.
2. Data Integrity: Triggers can help enforce data integrity rules that cannot be enforced
by constraints alone.
3. Audit Trails: Triggers can maintain an audit trail of changes to data for compliance or
monitoring purposes.
4. Business Logic Enforcement: They can be used to enforce complex business logic
within the database.
Disadvantages of Using Triggers
1. Complexity: Overusing triggers can lead to complex interdependencies that are hard to
maintain and troubleshoot.
2. Performance Impact: Triggers can affect performance, especially if they contain
complex logic or if they are fired frequently.
3. Hidden Logic: Triggers operate in the background, which can make the logic less
transparent to developers and database administrators.
-- Transaction 2
LOCK TABLE accounts IN SHARE MODE; -- waits for Transaction 1 to release the
lock
SELECT balance FROM accounts WHERE account_id = 'A';
b. Timestamp-Based Protocols
In timestamp-based protocols, each transaction is assigned a unique timestamp when it
starts. The timestamps determine the order of transaction execution and maintain
consistency.
● Basic Idea: Each operation is checked against the timestamps of other operations to
ensure serializability. If a transaction attempts to perform an operation that would
violate the timestamp order, it is rolled back.
● Read and Write Timestamps: Each data item maintains a read timestamp and a write
timestamp to track the last transaction that read or wrote to it.
Example:
1. Transaction T1 reads item A and is assigned a timestamp.
2. Transaction T2 tries to write to item A. If T2's timestamp is earlier than T1's read
timestamp, T2 is rolled back.
c. Optimistic Concurrency Control
Optimistic concurrency control allows transactions to execute without locking
resources, under the assumption that conflicts are rare. It consists of three phases:
1. Read Phase: The transaction reads data and performs its operations in a private
workspace.
2. Validation Phase: Before committing, the system checks for conflicts with other
transactions that might have modified the data during the transaction’s execution.
3. Write Phase: If validation is successful, changes are applied to the database; otherwise,
the transaction is rolled back.
Example:
sql
-- Transaction T1
READ A;
-- Modify A to A' in the private workspace
-- Transaction T2
READ A;
-- Modify A to A'' in the private workspace