Monday, 3 November 2025

Read committed Table Hint in SQL Server

The Read committed table hint is used to specify that a query should use the READ COMMITTED isolation level for a specific table. This is useful when the transaction isolation level of the session is different, but we want to particular query to follow read committed behavior.

Syntex

Select * from tablename (READCOMMITTED)

This hint forces the query to use read committed semantics, even if the transaction is running under a different isolation. It is useful when we want to ensure a query does not read uncommitted data (dirty read) but doesn’t need reparable read or phantom read.

Let’s consider a scenario in a retail application where customers can place orders for products. When a customer places an order, the system needs to check the current stock level of the ordered products before confirming the order.

To ensure that the stock level information is up-to-date while still allowing other transactions to modify it, you might use the READCOMMITTED hint in the transaction that retrieves the current stock level:

BEGIN TRANSACTION;
DECLARE @CurrentStockLevel INT;
-- Retrieve the current stock level with read committed isolation level
SELECT @CurrentStockLevel = StockLevel
FROM Products WITH (READCOMMITTED)
WHERE ProductID = @ProductID;
-- Check if there is enough stock to fulfill the order
IF @CurrentStockLevel >= @OrderQuantity
BEGIN
    -- Confirm the order and update the stock level
    UPDATE Products
    SET StockLevel = StockLevel - @OrderQuantity
    WHERE ProductID = @ProductID;
    COMMIT TRANSACTION;
    PRINT 'Order confirmed successfully.';
END
ELSE
BEGIN
    ROLLBACK TRANSACTION;
    PRINT 'Insufficient stock to fulfill the order.';
END

By applying the READCOMMITTED hint in the query that retrieves the current stock level, the system ensures a read committed isolation level, where only committed data is read, thus providing more accurate stock information.

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts