- Advanced SQL
-
Overview
- Indexing for Performance Optimization
- Transactions and ACID Properties
- Triggers and Event Scheduling in SQL
- Window Functions and Ranking
- Pivoting Data in SQL
- JSON and XML Data Handling
- Recursive Queries in SQL
- Performance Tuning and Query Optimization
- Role-Based Access Control in Databases
- Handling Large Datasets in SQL
Transactions and ACID Properties
Add to BookmarkIntroduction
A database transaction is a sequence of one or more SQL operations executed as a single unit of work. Transactions ensure data integrity and consistency, especially in multi-user environments where multiple processes access the database simultaneously. SQL databases follow the ACID properties to maintain reliability.
What is a Transaction?
A transaction represents a logical unit of work that must be executed completely or not at all. It starts with one or more SQL statements and can either be committed (saved) or rolled back (undone) if an error occurs.
Example of a Transaction
START TRANSACTION;
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 1000 WHERE account_id = 2;
COMMIT;
In this example, money is deducted from one account and added to another. If any statement fails, the changes can be rolled back to maintain consistency.
ACID Properties
The ACID properties ensure that database transactions are processed reliably. ACID stands for:
1. Atomicity
- Ensures that a transaction is treated as a single unit of work.
- If any part of the transaction fails, the entire transaction is rolled back.
Example:
START TRANSACTION;
DELETE FROM orders WHERE order_id = 1001;
INSERT INTO archive_orders VALUES (1001, 'Completed');
COMMIT;
If the INSERT statement fails, the DELETE statement is also rolled back, preventing partial execution.
2. Consistency
- Ensures the database remains in a valid state before and after the transaction.
- Transactions must follow database constraints, foreign keys, and rules.
Example: If a bank transfer violates the rule that account balances cannot be negative, the transaction is aborted.
3. Isolation
- Ensures that multiple concurrent transactions do not interfere with each other.
- Different isolation levels control how transactions interact with each other.
Isolation Levels:
- Read Uncommitted: Allows reading uncommitted data, leading to dirty reads.
- Read Committed: Ensures that only committed data is read.
- Repeatable Read: Prevents non-repeatable reads but allows phantom reads.
- Serializable: Highest level of isolation, preventing all concurrency issues.
Example:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
SELECT * FROM customers WHERE id = 5;
UPDATE customers SET balance = balance - 500 WHERE id = 5;
COMMIT;
Using SERIALIZABLE
ensures that no other transaction can modify or read the same data until this transaction is complete.
4. Durability
- Ensures that once a transaction is committed, it remains permanently stored in the database.
- Even if the system crashes, the changes persist.
Example: In MySQL, the InnoDB storage engine ensures durability by writing committed transactions to logs that persist after crashes.
Implementing Transactions in SQL
Using MySQL:
START TRANSACTION;
UPDATE inventory SET stock = stock - 10 WHERE product_id = 123;
UPDATE sales SET quantity_sold = quantity_sold + 10 WHERE product_id = 123;
COMMIT;
If an error occurs, you can roll back the transaction:
ROLLBACK;
Using PostgreSQL:
BEGIN;
UPDATE users SET status = 'active' WHERE user_id = 10;
COMMIT;
Using SQL Server:
BEGIN TRANSACTION;
UPDATE orders SET status = 'Shipped' WHERE order_id = 2023;
IF @@ERROR <> 0
ROLLBACK TRANSACTION;
ELSE
COMMIT TRANSACTION;
Conclusion
Transactions and ACID properties ensure database reliability by maintaining consistency, integrity, and security. Understanding these concepts is essential for developing robust database applications, especially in scenarios requiring high data reliability, such as banking, inventory management, and user authentication systems.
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Python Challenging Programming Exercises Part 3
- Types of Numbers in Python
- Top 10 Knowledge for Machine Learning & Data Science Students
- Best Platform to Learn Digital Marketing in Free
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Extract RGB Color From a Image Using CV2
- Loan Default Prediction Project Using Machine Learning
- Transforming Logistics: The Power of AI in Supply Chain Management
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Store Data Into CSV File Using Python Tkinter GUI Library
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- Why to learn Digital Marketing?
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset