SP
← SQL
SeniorSQL

SQL at scale: concurrency, execution plans and data access patterns

Senior-level SQL is about trade-offs: what the engine does under load and why a plan changed. Engine details refer to SQL Server 2022.

Isolation levels and anomalies

Level Dirty read Non-repeatable read Phantom
READ UNCOMMITTED possible possible possible
READ COMMITTED — possible possible
REPEATABLE READ — — possible
SERIALIZABLE — — —
  • Dirty read: seeing another transaction's uncommitted change.
  • Non-repeatable read: the same row returns different values within one transaction.
  • Phantom: re-running a range query returns new rows inserted by someone else.

SQL Server adds row versioning:

  • RCSI (READ_COMMITTED_SNAPSHOT ON) changes how READ COMMITTED reads: no shared locks; each statement sees the last committed version as of its start. Readers and writers do not block each other, and uncommitted data is never visible. Reading a row twice can still return two committed values.
  • SNAPSHOT isolation gives the whole transaction one view as of its start, so a second read returns the same value. If two snapshot transactions update the same row, the later one fails with an update conflict.

Deadlocks

A deadlock is a cycle: A holds a lock B needs while waiting for one B holds. SQL Server detects it, rolls back a victim and raises error 1205; the application must retry.

To reduce deadlocks:

  • access tables and rows in a consistent order;
  • keep transactions short; never wait for user input inside one;
  • index so statements touch and lock fewer rows.

NOLOCK is not a fix: SQL Server rejects it on the target of an UPDATE/DELETE (error 1065), and reads become dirty.

Reading execution plans

  • Seek: navigates the B-tree to a key range. Scan: reads the whole index or table.
  • Key Lookup: a nonclustered index found the rows but lacks columns, so each row is fetched from the clustered index. INCLUDE the missing columns to make the index covering.
  • SARGability: a predicate can seek only if the column is bare. YEAR(OrderDate) = 2024 scans; OrderDate >= '2024-01-01' AND OrderDate < '2025-01-01' seeks.
  • Implicit conversions: the lower-precedence type is converted to the higher one. nvarchar outranks varchar, so a varchar column compared with an nvarchar parameter gets converted, and with a SQL collation that means a scan and a CONVERT_IMPLICIT warning. AddWithValue sends C# strings as nvarchar; declare SqlDbType.VarChar with a size instead.

Parameter sniffing

When a parameterized query is compiled, the optimizer estimates row counts from the first parameter values it sees, and the plan is cached and reused. With skewed data a plan built for a rare value (seek + lookup) is terrible for a common one, and vice versa.

Mitigations: OPTION (RECOMPILE), OPTIMIZE FOR, separate code paths, or Parameter Sensitive Plan optimization (SQL Server 2022).

Set-based thinking: N+1 vs cartesian explosion

One query per loop item (N+1) costs a round trip each: 500 orders plus each customer is 501 queries. The opposite extreme hurts too: joining two collections in one query returns their product per parent. 50 lines × 20 payments is 1,000 rows per order. EF Core's AsSplitQuery() sends one query per collection: fewer rows, more round trips, and without a snapshot-style transaction the queries may see different data.

Pagination

OFFSET … FETCH reads and discards every skipped row, so deep pages get slower. It also recomputes positions per request: an insert at the top shows a row twice, a delete makes one disappear.

Keyset pagination continues from the last row's key:

SELECT TOP (20) id, price
FROM products
WHERE price > @lastPrice OR (price = @lastPrice AND id > @lastId)
ORDER BY price, id;

The sort key must be unique; add the primary key as a tie-breaker. With ORDER BY created_at alone, rows sharing the last timestamp are skipped.

Window frames

With ORDER BY inside OVER and no frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE includes all peers (rows with the same sort value), so duplicate dates share one "running" total. Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW with a unique order instead.

Optimistic concurrency

Instead of locking a row while a user edits it, store a version and make the update conditional:

UPDATE accounts SET balance = @b
WHERE id = @id AND version = @originalVersion;

If someone saved first, 0 rows are affected: report a conflict instead of a lost update. SQL Server's rowversion changes automatically on every update; EF Core uses it as a concurrency token and throws DbUpdateConcurrencyException.

Denormalization trade-offs

Storing derived data (an order_count on customers) makes reads cheaper and writes more expensive. Every write path must keep the copy in sync in the same transaction, and a busy summary row becomes a contention hotspot.

Write-heavy tables

  • Every nonclustered index is extra work for inserts.
  • A random uniqueidentifier clustered key inserts into the middle of pages, which causes page splits and fragmentation. An ever-increasing key appends at the end but can hit last-page latch contention at very high concurrency (OPTIMIZE_FOR_SEQUENTIAL_KEY helps).
  • Partitioning is mainly about manageability: switching partitions as a metadata operation, archiving, per-partition maintenance. It does not speed up queries by itself.
Practise this level
15 questions
Practise →