This repository contains a database schema and several SQL scripts designed to demonstrate SQL Server concurrency issues, deadlocks, and isolation levels for educational purposes.
- SQL Server (2016 or newer)
- SQL Server Management Studio (SSMS) or Azure Data Studio
- Clone this repository
- Run the
create-database.sql
script to create the sample database and populate it with data - Review the example scripts and run them following the instructions inside each file
This workshop covers the following concurrency topics:
- Deadlocks - When two transactions block each other
- Transaction Isolation Levels - Various isolation levels and their effects:
- READ UNCOMMITTED
- READ COMMITTED
- REPEATABLE READ
- SERIALIZABLE
- Concurrency Phenomena:
- Dirty reads
- Non-repeatable reads
- Phantom reads
- Lock Escalation - How row-level locks can escalate to table-level locks
- Optimistic Concurrency Control - Using row versioning to detect conflicts
Demonstrates a classic deadlock scenario where two transactions acquire locks in different orders.
Shows how READ UNCOMMITTED isolation level can lead to reading uncommitted data that might be rolled back.
Compares READ COMMITTED with REPEATABLE READ to show how the latter prevents data from changing during a transaction.
Compares REPEATABLE READ with SERIALIZABLE to show how the latter prevents new rows from appearing in result sets.
Shows how SQL Server can escalate from row-level locks to table-level locks when many rows are affected.
Demonstrates optimistic concurrency control using SQL Server's ROWVERSION feature.
The sample database contains the following main tables:
- Organizations - Companies in the system
- Branches - Physical locations belonging to organizations
- Users - People who use the system
- Products - Items that can be ordered
- Categories - Product categories
- Orders - Orders placed by users
- OrderItems - Line items within orders
- Inventory - Stock level changes for products
- AuditLogs - Record of changes to the database
When designing applications to handle concurrency, consider these best practices:
- Keep transactions as short as possible
- Access objects in the same order across all transactions
- Use appropriate isolation levels for your needs
- Consider optimistic concurrency for low-contention scenarios
- Use snapshot isolation for reporting queries
- Be aware of lock escalation thresholds
- Implement retry logic for deadlock victims
- Monitor for deadlocks using SQL Server's deadlock graph
- SQL Server Transaction Locking and Row Versioning Guide
- Deadlocks Guide
- Analyze and prevent deadlocks
- Transaction Isolation Levels
Connectionsträng
jdbc:sqlserver://localhost:1434;user=sa;password=secure_password123