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
INCLUDEthe 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 passTransactionOptions.
Index types
| Index | What it stores | Key facts |
|---|---|---|
| Clustered (rowstore) | the data rows themselves, at the leaf level, in key order | one 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 |
| Heap | a table with no clustered index | rows 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 leaf | up to 999 per table; columns it lacks come from a key lookup or RID lookup |
| Covering | any index that holds every column one query needs | add non-key columns with INCLUDE (...) to remove key lookups |
| Unique | an index that rejects duplicate keys | a UNIQUE constraint or a primary key creates one |
| Filtered | a nonclustered index with a WHERE clause | smaller and cheaper to maintain; used only when the query's rows are known to be inside the filter |
| Columnstore | column-wise, compressed storage, read in batches | for 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
-- 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 DESCfrom 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 = @id | yes | equality on the leading column |
WHERE CustomerId = @id AND OrderDate >= @from | yes | equality, then a range on the next column |
WHERE OrderDate > @d | usually a scan | not the leading column |
WHERE YEAR(OrderDate) = 2026 (index on OrderDate) | no range seek | the function hides the column: write OrderDate >= '20260101' AND OrderDate < '20270101' |
WHERE Name LIKE 'Ab%' (index on Name) | yes | a prefix is a range |
WHERE Name LIKE '%ab' (index on Name) | no | a leading wildcard has no starting point |
a varchar column compared with an nvarchar parameter | depends on the collation | converting the column can prevent a seek: match the parameter type to the column |
| a predicate that matches a large share of the rows | the optimizer may scan | many 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
| Level | Dirty read | Non-repeatable read | Phantom | How SQL Server does it |
|---|---|---|---|---|
READ UNCOMMITTED (NOLOCK) | possible | possible | possible | reads take no shared locks; rows can be missed or read twice |
| READ COMMITTED (default) | prevented | possible | possible | shared locks held only while a row or page is read, or statement-level row versions when RCSI is ON |
| REPEATABLE READ | prevented | prevented | possible | shared locks held until the transaction ends |
| SERIALIZABLE | prevented | prevented | prevented | locks the rows and ranges it reads until the transaction ends (key-range locks when an index serves the range); the most blocking |
| SNAPSHOT | prevented | prevented | prevented | transaction-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?
| RCSI | SNAPSHOT | |
|---|---|---|
| Turn on | ALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT ON | ALTER DATABASE ... SET ALLOW_SNAPSHOT_ISOLATION ON, then each session runs SET TRANSACTION ISOLATION LEVEL SNAPSHOT |
| Reads see | the data as of the start of each statement | the data as of the transaction's first read or write |
| Code change | none: 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 conflicts | none reach the application | error 3960: roll back; retry only when the whole operation is safe to repeat |
| Default | OFF in SQL Server, ON in Azure SQL Database | OFF 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:
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
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}");
}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 acrossawait. - 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 ... WHEREwith 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: passTransactionOptionswith 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?
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?
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?
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?
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.
Related on TechInterviewNotes
- Advanced C#, EF Core and SQL Interview Q&A: the lessons Dynamic SQL, transactions, and concurrency details and Performance tuning, plans, and operational questions
- Transactions, Retry Boundaries and Uncertain Commit Outcomes (EF Core Data Correctness, lesson 3)
- Optimistic Concurrency and an Explicit Conflict Policy (EF Core Data Correctness, lesson 2)
- Stable Pagination in .NET APIs: Offset Drift, Keyset Cursors, and Tie Breakers
Sources
- Clustered and nonclustered indexes described: one clustered index per table, row locators, the primary key's index.
- Index architecture and design guide: key column order, included columns, filtered indexes.
- Maximum capacity specifications for SQL Server: 999 nonclustered indexes, 32 key columns, the 900 and 1,700 byte key limits.
- SET TRANSACTION ISOLATION LEVEL: what each level allows, the defaults, RCSI in Azure SQL Database.
- Transaction locking and row versioning guide: the version store, the 14 bytes, update conflicts.
- Implement an implicit transaction using TransactionScope: the Serializable default and
TransactionOptions.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·