MODULO SQL & Database Design Master SeriesLAB

"Unlocking Concurrency: Mastering Locks and Deadlocks in SQL"

Introduction to Locking

In a multi-user database environment, concurrency control is crucial to ensure data consistency and integrity. One of the primary mechanisms used to achieve this is locking. Locking allows the database to manage simultaneous access to shared resources, preventing data corruption and inconsistencies.

Types of Locks

There are two primary types of locks in SQL:

  • Shared Lock (S-Lock): A shared lock allows multiple transactions to read the same data simultaneously. It prevents any transaction from modifying the data until all shared locks are released.
  • Exclusive Lock (X-Lock): An exclusive lock grants exclusive access to a transaction, allowing it to modify the data. No other transaction can access the data until the exclusive lock is released.

Shared Lock Example

Suppose we have a table employees with the following structure:

CREATE TABLE employees (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  salary DECIMAL(10, 2)
);

We can demonstrate a shared lock using the following SQL queries:

-- Transaction 1: Acquire a shared lock on the employees table
BEGIN TRANSACTION;
SELECT * FROM employees WHERE id = 1;

-- Transaction 2: Attempt to acquire a shared lock on the same table
BEGIN TRANSACTION;
SELECT * FROM employees WHERE id = 1;  -- This query will succeed

In this example, both transactions can read the data simultaneously, as they both hold shared locks.

Exclusive Lock Example

Now, let's demonstrate an exclusive lock:

-- Transaction 1: Acquire an exclusive lock on the employees table
BEGIN TRANSACTION;
UPDATE employees SET salary = 50000 WHERE id = 1;

-- Transaction 2: Attempt to acquire a shared lock on the same table
BEGIN TRANSACTION;
SELECT * FROM employees WHERE id = 1;  -- This query will be blocked

In this example, Transaction 1 holds an exclusive lock, preventing Transaction 2 from accessing the data until the lock is released.

Deadlocks

A deadlock occurs when two or more transactions are blocked, each waiting for the other to release a lock. This creates a cycle of dependencies, causing the transactions to wait indefinitely.

Deadlock Example

Suppose we have two tables, orders and customers, with the following structures:

CREATE TABLE orders (
  id INT PRIMARY KEY,
  customer_id INT,
  order_date DATE
);

CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(50)
);

We can demonstrate a deadlock using the following SQL queries:

-- Transaction 1: Acquire an exclusive lock on the orders table
BEGIN TRANSACTION;
UPDATE orders SET order_date = '2022-01-01' WHERE id = 1;

-- Transaction 2: Acquire an exclusive lock on the customers table
BEGIN TRANSACTION;
UPDATE customers SET name = 'John Doe' WHERE id = 1;

-- Transaction 1: Attempt to acquire a shared lock on the customers table
SELECT * FROM customers WHERE id = 1;  -- This query will be blocked

-- Transaction 2: Attempt to acquire a shared lock on the orders table
SELECT * FROM orders WHERE id = 1;  -- This query will be blocked

In this example, Transaction 1 holds an exclusive lock on the orders table and waits for a shared lock on the customers table. Transaction 2 holds an exclusive lock on the customers table and waits for a shared lock on the orders table. This creates a deadlock, as both transactions are blocked, waiting for each other to release a lock.

Avoiding Deadlocks

To avoid deadlocks, follow these best practices:

  • Access tables in a consistent order: Always access tables in the same order to prevent deadlocks.
  • Avoid using SELECT FOR UPDATE: Instead, use UPDATE statements with a WHERE clause to update specific rows.
  • Use transactions judiciously: Keep transactions short and to the point to minimize the risk of deadlocks.
  • Monitor database activity: Regularly monitor database activity to detect potential deadlocks.

Conclusion

In this masterclass, we explored the concepts of shared locks, exclusive locks, and deadlocks in SQL. We demonstrated examples of each and provided best practices for avoiding deadlocks. By understanding these concepts and following best practices, you can write more efficient and scalable SQL code.

⚔️ YOUR MISSION

Practical Exercise:

Create a database schema with two tables, products and orders. Write a SQL script that demonstrates a deadlock scenario between two transactions. Then, modify the script to avoid the deadlock by accessing tables in a consistent order.

Deliverables:

  • A database schema with two tables, products and orders
  • A SQL script that demonstrates a deadlock scenario
  • A modified SQL script that avoids the deadlock

Grading criteria:

  • Correctness of the database schema and SQL scripts
  • Clarity and organization of the code
  • Effectiveness in demonstrating a deadlock scenario and avoiding it
SQL practice editor
Read the exercise prompt
-- Create the database schema
CREATE TABLE products (
  id INT PRIMARY KEY,
  name VARCHAR(50),
  price DECIMAL(10, 2)
);

CREATE TABLE orders (
  id INT PRIMARY KEY,
  product_id INT,
  order_date DATE
);

-- Insert sample data
INSERT INTO products (id, name, price) VALUES (1, 'Product A', 19.99);
INSERT INTO orders (id, product_id, order_date) VALUES (1, 1, '2022-01-01');

-- Start Transaction 1
BEGIN TRANSACTION;
UPDATE products SET price = 20.99 WHERE id = 1;

-- Start Transaction 2
BEGIN TRANSACTION;
UPDATE orders SET order_date = '2022-01-15' WHERE id = 1;

-- Attempt to acquire a shared lock on the orders table (Transaction 1)
SELECT * FROM orders WHERE id = 1;

-- Attempt to acquire a shared lock on the products table (Transaction 2)
SELECT * FROM products WHERE id = 1;
WAITING FOR SIGNAL...
BACKNEXT STAGE