The Wayback Machine - https://web.archive.org/web/20240812015811/https://www.geeksforgeeks.org/dbms-dirty-read-in-sql/
Open In App

Dirty Read in SQL

Last Updated : 26 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pre-Requisite – Types of Schedules, Transaction Isolation Levels in DBMS

A Dirty Read in SQL occurs when a transaction reads data that has been modified by another transaction, but not yet committed. In other words, a transaction reads uncommitted data from another transaction, which can lead to incorrect or inconsistent results.

This situation can occur when a transaction modifies a data item and then fails to commit the changes due to a system failure, network error, or other issue. If another transaction reads the modified data before the first transaction has a chance to commit, it can lead to a dirty read.

For example, consider two transactions T1 and T2. T1 modifies a row in a table and starts a transaction, but does not commit it. Meanwhile, T2 tries to read the same row before T1 commits its changes. If T2 is allowed to read the uncommitted data, it will result in a dirty read, potentially leading to incorrect or inconsistent results.

To prevent dirty reads, SQL provides transaction isolation levels, which specify how transactions should be isolated from one another. The isolation levels include:

  • Read uncommitted: This level allows transactions to read uncommitted data from other transactions, leading to potential dirty reads.
  • Read committed: This level allows transactions to read only committed data, preventing dirty reads.
  • Repeatable read: This level prevents dirty reads and also ensures that a transaction always reads the same data for a given query, even if other transactions modify the data in the meantime.
  • Serializable: This level provides the highest level of isolation and ensures that transactions are executed serially, preventing dirty reads and other anomalies.
  • Dirty reads in SQL can lead to incorrect or inconsistent results and should be prevented through the use of transaction isolation levels. There are mainly four types of common concurrency problems: dirty read, lost read, non-repeatable read and phantom reads. 
  • Dirty Reads – When a transaction is allowed to read a row that has been modified by another transaction that is not been committed yet that time Dirty Reads occurred. It is mainly occurred because of multiple transactions at a time which is not committed. 

Example: Table Record

ID

Cus_Name

Balance

1

S Adam

100

2

Zee Young

150

Transaction: Transfer 10 from S Adam’s account to Zee Young’s account.

Input:
BEGIN TRY
BEGIN TRANSACTION
UPDATE Table SET Balance = Balance - 10 WHERE ID=1;
UPDATE Table SET Balance = Balance + 10 WHERE ID='C';
COMMIT TRANSACTION
PRINT 'Committed'
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
PRINT 'Not Committed'
END CATCH

Output:
Not committed

By executing the above query the output will be “Not committed” because there is an error, there is no ID=C. So at that time if we want to execute another transaction with that row time Dirty Reads occur. There is no partial commitment if both the UPDATE query succeeds only then the output will be “Committed”. Before Execution.

Table Record

ID

Cus_Name

Balance

1

S Adam

100

2

Zee Young

150

After Execution:

Input:
BEGIN TRY
BEGIN TRANSACTION
UPDATE Table SET Balance = Balance - 10 WHERE ID=1;
UPDATE Table SET Balance = Balance + 10 WHERE ID='C';
COMMIT TRANSACTION
PRINT 'Committed'
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
PRINT 'Not Committed'
END CATCH
Output:
(1row affected)
(0row affected)
Not Committed

Note that if we put a valid ID first transaction result will come out as committed or 1 row affected but the 2nd one will not be affected.

Explanation: If we have a ticket booking system and One Customer is trying to book a ticket at that time an available number of the ticket is 10, before completing the payment, the Second Customer wants to book a ticket at that time this 2nd transaction will show the second customer that the number of the available tickets is 9. The twist is here if the first customer does not have sufficient funds in his debit card or in his wallet then the 1st transaction will Rollback, At that time 9 seats are available which is read by the 2nd transaction is Dirty Read. 

Example: Available ticket: For 1st customer

Step 1:

Input: Transaction 1
Select *from Bus_ticket;

Output:

ID

Bus_Name

Available_Seat

1

KA0017

10

Step 2: Booking time for 1st customer

Input:  
--Transaction 1
BEING Transaction
UPDATE Bus_Ticket set Available_Seat=9
WHERE ID=1

--Payment for Transaction 1
Waitfor Delay '00.00.30'
Rollback transaction

Available ticket: For the 2nd customer while the 1st customer is paying for the ticket.

Step 3: Input

Transaction 1

set transaction isolation level read uncommitted
Select *from Bus_ticket where ID=1;

Output:

ID

Bus_Name

Available_Seat

1

KA0017

9

Note that during the payment of the 1st customer’s 2nd transaction read 9 seat is available if somehow the 1st transaction Rollback then available seat 9 is Dirty read data. After the rollback of the 1st transaction available seat is 10 again. 2nd and 3rd steps happening at the same time. Actually available seat after rollback of transaction 1.

ID

Bus_Name

Available_Seat

1

KA0017

10

Advantages of Dirty Read

  • Increased Concurrency: Dirty reads can increase the degree of concurrency in the database system, as transactions are allowed to read uncommitted data. This can lead to improved performance and throughput.
  • Reduced Locking Overhead: Since dirty reads do not require locks, the overhead associated with acquiring and releasing locks can be reduced.
  • Faster Response Time: Dirty reads can improve the response time of database queries, as transactions can read data without waiting for other transactions to commit.

Disadvantages of Dirty Read

  • Inconsistent Data: Dirty Reads can lead to inconsistent and incorrect data, as transactions may be reading data that has been modified by other transactions that have not yet been committed. This can lead to errors and inaccuracies in the database.
  • Unreliable Results: Dirty reads can lead to unreliable query results, as the data being read may change before the transaction is completed.
  • Data Integrity Issues: Dirty reads can cause data integrity issues, as transactions may be reading data that is in an inconsistent or incomplete state.
  • Hard to Debug: Dirty reads can be difficult to debug, as the data being read may be inconsistent or incomplete, making it hard to trace the source of errors.

FAQs on Dirty Read in SQL

1. What is Dirty Read?

Answer:

If a transaction reads any modified data before the first transaction has been committed, then it can lead to Dirty Read.

2. How Dirty Read can be prevented?

Answer:

Dirty Read can be prevented by making the schedule serializable.



Previous Article
Next Article

Similar Reads

Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL vs NO SQL vs NEW SQL
SQL stands for Structured Query Language. Which is based on relational algebra and schema is fixed in this which means data is stored in the form of columns and tables. SQL follows ACID properties which means Atomicity, Consistency, Isolation, and Durability are maintained. There are three types of languages present in SQL : Data Definition Languag
2 min read
SQL | Difference between functions and stored procedures in PL/SQL
Prerequisite: Procedures in PL/SQLFunctions in PL/SQL.Difference between functions and stored procedures in PL/SQL Differences between Stored procedures(SP) and Functions(User-defined functions (UDF)): 1. SP may or may not return a value but UDF must return a value. The return statement of the function returns control to the calling program and ret
3 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
Article Tags :
three90RightbarBannerImg