Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    SQL Server Indexes and Transaction Isolation Levels Cheat Sheet

    Compare SQL Server index types and query access paths.

    SQL Server indexes (what each kind stores, when a seek is possible) and transaction isolation levels (what a transaction sees of other transactions), for SQL Server and Azure SQL Database.

    At a glance

    • A clustered rowstore index stores the table's rows in key order, so a table has at most one clustered index. A table without one is a heap.
    • A nonclustered rowstore index is a separate B+ tree. Its leaf holds a row locator (the clustered key, or a row ID on a heap); fetching the other columns from the table is a key lookup (or RID lookup).
    • A composite index is used left to right: equality columns first, then the range or sort column, then INCLUDE the other columns the query returns.
    • READ COMMITTED is the default: no dirty reads, but non-repeatable reads and phantoms are possible.
    • Read committed snapshot isolation (RCSI) is OFF by default in SQL Server and ON in Azure SQL Database. SNAPSHOT gives the whole transaction one view and can end with update conflict error 3960.
    • In .NET, new TransactionScope() runs at Serializable unless you pass TransactionOptions.

    Index types

    IndexWhat it storesKey facts
    Clustered (rowstore)the data rows themselves, at the leaf level, in key orderone per table; a primary key creates one by default when the table has none (unless declared NONCLUSTERED); a query still needs ORDER BY to return rows in order
    Heapa table with no clustered indexrows are found by row ID (RID); a row that grows past its page leaves a forwarding pointer behind
    Nonclustered (rowstore)a separate B+ tree of the key columns, with a row locator at the leafup to 999 per table; columns it lacks come from a key lookup or RID lookup
    Coveringany index that holds every column one query needsadd non-key columns with INCLUDE (...) to remove key lookups
    Uniquean index that rejects duplicate keysa UNIQUE constraint or a primary key creates one
    Filtereda nonclustered index with a WHERE clausesmaller and cheaper to maintain; used only when the query's rows are known to be inside the filter
    Columnstorecolumn-wise, compressed storage, read in batchesfor scans and aggregates over many rows; rowstore indexes suit selective lookups

    Limits for disk-based rowstore indexes: 32 key columns; a key of at most 900 bytes for a clustered index and 1,700 bytes for a nonclustered index (SQL Server 2016 and later, Azure SQL Database), but at most 900 bytes for a primary key either way. Included columns do not count toward these key limits.

    A covering index and a filtered index

    SQL
    -- Seek on CustomerId, rows already in OrderDate order, no key lookup for Total and Status
    CREATE NONCLUSTERED INDEX IX_Orders_Customer_Date
        ON dbo.Orders (CustomerId, OrderDate DESC)
        INCLUDE (Total, Status);
    
    -- A small index for the hot subset only
    CREATE NONCLUSTERED INDEX IX_Orders_Open
        ON dbo.Orders (CreatedAt)
        WHERE Status = 'Open';
    • The first answers SELECT OrderDate, Total FROM dbo.Orders WHERE CustomerId = @id ORDER BY OrderDate DESC from the index alone.
    • The second serves a query whose predicate falls inside Status = 'Open'. If the status is a parameter, the plan must work for any value and may skip the index: check the plan.

    When a seek is possible

    Predicate (index on (CustomerId, OrderDate) unless noted)Seek?Why
    WHERE CustomerId = @idyesequality on the leading column
    WHERE CustomerId = @id AND OrderDate >= @fromyesequality, then a range on the next column
    WHERE OrderDate > @dusually a scannot the leading column
    WHERE YEAR(OrderDate) = 2026 (index on OrderDate)no range seekthe function hides the column: write OrderDate >= '20260101' AND OrderDate < '20270101'
    WHERE Name LIKE 'Ab%' (index on Name)yesa prefix is a range
    WHERE Name LIKE '%ab' (index on Name)noa leading wildcard has no starting point
    a varchar column compared with an nvarchar parameterdepends on the collationconverting the column can prevent a seek: match the parameter type to the column
    a predicate that matches a large share of the rowsthe optimizer may scanmany key lookups cost more than one scan

    Every index costs writes: each insert, delete or update maintains every index whose entries change, included columns too.

    Isolation levels

    LevelDirty readNon-repeatable readPhantomHow SQL Server does it
    READ UNCOMMITTED (NOLOCK)possiblepossiblepossiblereads take no shared locks; rows can be missed or read twice
    READ COMMITTED (default)preventedpossiblepossibleshared locks held only while a row or page is read, or statement-level row versions when RCSI is ON
    REPEATABLE READpreventedpreventedpossibleshared locks held until the transaction ends
    SERIALIZABLEpreventedpreventedpreventedlocks the rows and ranges it reads until the transaction ends (key-range locks when an index serves the range); the most blocking
    SNAPSHOTpreventedpreventedpreventedtransaction-level row versions; needs ALLOW_SNAPSHOT_ISOLATION ON
    • Dirty read: reading another transaction's uncommitted change.
    • Non-repeatable read: the same row gives different values within one transaction.
    • Phantom: the same range query returns new or missing rows.

    The isolation level changes what reads see, not how writes are protected: another transaction cannot change a row you changed until you commit or roll back.

    RCSI or SNAPSHOT?

    RCSISNAPSHOT
    Turn onALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT ONALTER DATABASE ... SET ALLOW_SNAPSHOT_ISOLATION ON, then each session runs SET TRANSACTION ISOLATION LEVEL SNAPSHOT
    Reads seethe data as of the start of each statementthe data as of the transaction's first read or write
    Code changenone: READ COMMITTED callers read versions (test the change in behaviour)each session opts in
    Readers block writers?no (schema locks and lock hints still can)no (same exceptions)
    Update conflictsnone reach the applicationerror 3960: roll back; retry only when the whole operation is safe to repeat
    DefaultOFF in SQL Server, ON in Azure SQL DatabaseOFF in SQL Server; check snapshot_isolation_state in sys.databases
    • Versions live in tempdb, or in the database's persistent version store when accelerated database recovery (ADR) is on; ADR is always on in Azure SQL Database.
    • Each row can carry up to 14 extra bytes of version information.
    • A long-running transaction keeps old versions alive, and the version store grows.
    • SNAPSHOT is not SERIALIZABLE: two transactions that change different rows can still break a rule that spans both (write skew).

    Preventing a lost update

    Read, check in code, then write loses updates under READ COMMITTED: two callers can read the same stock. Do the check and the change in one statement, and look at the row count:

    SQL
    UPDATE dbo.Products
    SET Stock = Stock - @qty
    WHERE ProductId = @id AND Stock >= @qty;
    -- 0 rows affected: not enough stock, or no such product

    Other ways: UPDLOCK, HOLDLOCK on the read inside a transaction, or optimistic concurrency with a rowversion column checked in the WHERE clause (EF Core supports it as a concurrency token).

    Isolation in .NET code

    C#Runs
    using System.Transactions;
    
    using (var scope = new TransactionScope())
    {
        Console.WriteLine($"new TransactionScope(): {Transaction.Current!.IsolationLevel}, timeout {TransactionManager.DefaultTimeout}");
    }
    
    var options = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };
    using (var scope = new TransactionScope(TransactionScopeOption.Required, options))
    {
        Console.WriteLine($"with TransactionOptions: {Transaction.Current!.IsolationLevel}");
    }
    Output
    new TransactionScope(): Serializable, timeout 00:01:00
    with TransactionOptions: ReadCommitted
    • In async code, create the scope with TransactionScopeAsyncFlowOption.Enabled. The default (Suppress) does not flow the ambient transaction across await.
    • With ADO.NET, connection.BeginTransaction(System.Data.IsolationLevel.Snapshot) asks for a level (SNAPSHOT also needs the database option). The level stays set on that connection after the transaction, until the connection is closed or disposed.

    Common mistakes

    • NOLOCK "for speed": you trade blocking for wrong results (uncommitted, missing or doubled rows). Fix the query, or turn on RCSI.
    • Read, check in code, then write a counter: lost updates. Use one UPDATE ... WHERE with the check in it and look at the row count.
    • SERIALIZABLE everywhere "to be safe": more blocking and deadlocks. Pick the level that protects the rule, and keep transactions short.
    • A function on the column in WHERE (YEAR(OrderDate), UPPER(Name)): no seek. Rewrite the predicate as a range, or index a computed column.
    • An index for every slow query: each one adds work to the writes that change its entries. Check the plan, and drop indexes nothing uses.
    • Leaving new TransactionScope() at Serializable: pass TransactionOptions with the level you mean.

    In an interview

    Clustered or nonclustered: what is at the leaf level? A clustered index's leaf level is the data rows, in key order. A nonclustered index's leaf holds its key columns, any included columns and a row locator: the clustered key, or a row ID on a heap.

    What is a key lookup, and how do you remove it? The engine found the rows in a nonclustered index but needs more columns, so it fetches each row from the clustered index. Add those columns with INCLUDE to make the index covering, if the extra write cost is worth it.

    Why can WHERE YEAR(OrderDate) = 2026 stop a seek? The function is applied to the column, so the optimizer cannot turn it into a range on the index. Write OrderDate >= '20260101' AND OrderDate < '20270101'.

    Which anomaly does REPEATABLE READ still allow? Phantoms. Rows already read cannot change, but another transaction can insert a new row that matches the range. SERIALIZABLE also locks the range (key-range locks on the index that serves it) to stop that.

    RCSI or SNAPSHOT? RCSI gives each statement a consistent view and needs no code change. SNAPSHOT gives the whole transaction one view; sessions opt in, and an update that meets a newer committed change fails with error 3960.

    How do you prevent a lost update on a stock counter? Put the check and the change in one statement, UPDATE ... SET Stock = Stock - @qty WHERE Stock >= @qty, and check the rows affected. Other options are UPDLOCK, HOLDLOCK on the read, or optimistic concurrency with a rowversion column.

    Check yourself

    A transaction at REPEATABLE READ reads every order in a date range. What can still happen before it ends?

    A Another transaction inserts a new order inside that range
    B It reads another transaction's uncommitted change
    C Another transaction updates an order it already read
    D Its shared locks on the rows it read are released
    Show answer

    Correct answer: A

    REPEATABLE READ holds shared locks on the rows it read until the end, but it does not lock the range, so a new matching row (a phantom) can appear. SERIALIZABLE locks the range.

    Option B: Dirty reads are prevented from READ COMMITTED upward.

    Option C: The shared locks it holds block updates to those rows until it ends.

    Option D: At REPEATABLE READ, shared locks are held until the transaction ends.

    dbo.Orders is clustered on OrderId. Which index answers SELECT OrderDate, Total FROM dbo.Orders WHERE CustomerId = @id ORDER BY OrderDate with a seek, no key lookup and no sort?

    A (OrderDate) INCLUDE (CustomerId, Total)
    B (CustomerId, OrderDate) INCLUDE (Total)
    C (Total, CustomerId) INCLUDE (OrderDate)
    D (CustomerId) INCLUDE (OrderDate, Total)
    Show answer

    Correct answer: B

    The equality column leads, the sort column comes next, and the returned column is included: the engine seeks, reads the rows already in order and never visits the table.

    Option A: CustomerId is not a key column here, so there is nothing to seek on.

    Option C: The leading key Total is not in the filter, so there is no seek.

    Option D: Included columns are not sorted, so the rows need a sort after the seek.

    Under SNAPSHOT isolation, a transaction updates a row that another transaction changed and committed after the first one's snapshot began. What happens?

    A The update silently overwrites the newer value
    B The update waits, then applies on top of it
    C The transaction fails with update conflict error 3960
    D The update is skipped and reports 0 rows affected
    Show answer

    Correct answer: C

    SNAPSHOT checks that the row has not changed since its snapshot. When it has, the transaction is rolled back with error 3960, and the application decides whether to retry.

    Option A: Overwriting a newer committed change is the lost update that SNAPSHOT prevents.

    Option B: Reading the latest committed row and updating it is how READ COMMITTED behaves, not SNAPSHOT.

    Option D: The engine raises an error; it does not silently skip the row.

    Which isolation level does new TransactionScope() use when you pass no options?

    A ReadCommitted
    B Serializable
    C Snapshot
    D The database's default level
    Show answer

    Correct answer: B

    TransactionScope defaults to IsolationLevel.Serializable; pass TransactionOptions to choose another level.

    Option A: ReadCommitted is SQL Server's default for a plain connection, not the scope's.

    Option C: Snapshot is used only when you ask for it, and the database must allow it.

    Option D: The scope sets its own level; it does not take the database's.

    Sources

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·