SQL Server Connections, Cursors, and Plan Cache
In SQL Server, a connection is lightweight, because a session does not use a worker thread while it has no request (memory and thread architecture). Compiling a SQL statement, on the other hand, is treated as expensive. SQL Server puts compiled execution plans in the plan cache so that all sessions reuse them, and it provides several layers of mechanisms that parameterize statements so they can be reused. By default, results are returned not through a cursor but as a default result set, which streams rows to the client as the server produces them.
Key Specifications
| Item | Value |
|---|---|
| Protocol | TDS (Tabular Data Stream). TCP default port 1433, shared memory, named pipes |
| Maximum connections | user connections default 0 = up to 32,767 (@@MAX_CONNECTIONS) |
| Packet size | network packet size default 4,096 bytes |
| Dedicated administrator connection (DAC) | Separate endpoint and scheduler. For diagnostics when the server is unresponsive. One at a time |
| Concurrent requests per connection | One by default. With MARS on, multiple requests run interleaved |
| Execution plan cache | Shared by all sessions. A cache store within max server memory |
| Cache key | Hash of the statement text (whitespace and case sensitive) + SET options that affect the plan + database |
| Automatic parameterization | Simple (default): only safe, simple statements. Forced (PARAMETERIZATION FORCED): most literals |
| Ad hoc plan reduction | optimize for ad hoc workloads (default 0): on first execution, stores only a small stub instead of the plan |
| Default result mode | Default result set (forward-only, read-only, no server cursor) |
| Server cursor types | STATIC, KEYSET, DYNAMIC, FAST_FORWARD |
| Cursor scope | Default GLOBAL (whole connection). Change with CURSOR_DEFAULT LOCAL |
| Commit and cursors | CURSOR_CLOSE_ON_COMMIT default OFF: cursors are not closed on commit |
| Result cache | None |
Connections
Figure. One request through a connection pool
sequenceDiagram
participant A as Application
participant P as Client connection pool
participant S as SQL Server session
participant W as Worker thread
A->>P: Open connection
P->>S: If not in the pool, TDS pre-login, TLS, login
P-->>A: Lend the connection
A->>S: Send batch or RPC
S->>W: Create a task and assign it to a worker
W-->>A: Send result rows as they are produced
W-->>S: Request ends, worker returned
A->>P: Close connection (actually returned to the pool)
Note over P,S: The session stays in the sleeping state and uses no worker
A->>P: Open connection again
P->>S: Reuse the same session, sp_reset_connection on the first request
Diagram notes: time flows from top to bottom.
- When the application opens a connection, the driver's
Client connection poolreceives the call first. An actual login happens only when there is no idle connection with the same connection string. A login goes through pre-login (version, encryption negotiation), TLS, and authentication, in that order. - When a batch (SQL text) or an RPC (stored procedure call,
sp_executesql) arrives, the session gets a request and a worker thread is assigned. When the request ends, the worker goes back and only the session remains. - Even when the application closes the connection, the pool keeps the real connection. In
sys.dm_exec_sessions, this session appears assleeping. - When a connection is taken from the pool again, the driver attaches
sp_reset_connectionto the first request. Session state such as temporary tables,SEToptions, and open cursors is reset at this point.
The pool is on the client, not the server. ADO.NET has pooling on by default, and the maximum size of one pool is 100 by default. If the connection string differs by even one character, it becomes a different pool. If the pool is full and nothing is returned, the application fails with a connection timeout; the cause is often code that does not close connections rather than the server.
Cancellation. When the client's command timeout (ADO.NET default 30 seconds) elapses, the driver sends an attention signal over the same connection and the server stops the running request. The server has no default setting that limits statement execution time. A transaction opened by an aborted request may not be rolled back automatically, so also use SET XACT_ABORT ON.
| View | One row | Key columns |
|---|---|---|
sys.dm_exec_connections | Network connection | net_transport, encrypt_option, auth_scheme, client_net_address |
sys.dm_exec_sessions | Session | status, login_name, program_name, open_transaction_count, is_user_process |
sys.dm_exec_requests | Running request | status, command, wait_type, blocking_session_id, sql_handle, plan_handle |
Plan Cache
Figure. Structure of the plan cache
block-beta
columns 6
t1["Plan cache: shared by all sessions"]:6
s1["SQL plan store<br/>CACHESTORE_SQLCP<br/>ad hoc, prepared statements"]:2 s2["Object plan store<br/>CACHESTORE_OBJCP<br/>procedures, triggers, functions"]:2 s3["Bound tree store<br/>CACHESTORE_PHDR<br/>views, constraints"]:2
t2["One cache entry"]:6
cp["Compiled plan<br/>read-only, used by many sessions at once"]:3 k["Key<br/>text hash, SET options, database"]:3
e1["Execution context<br/>parameter values of session A"]:2 e2["Execution context<br/>parameter values of session B"]:2 e3["Execution context<br/>idle, waiting for reuse"]:2
class t1,t2 plain
class s1,s2,s3 meta
class cp data
class k slot
class e1,e2 hot
class e3 muted
Diagram notes: the upper row is the cache stores, and the lower part is one entry inside them.
- The plan cache is divided into several stores. The
SQL plan storeholds plans of ad hoc statements and prepared statements (sp_executesql, parameterized commands), and theObject plan storeholds plans of procedures, triggers, and functions. TheBound tree storeis not plans but the parsed trees of views and constraints. - One entry is a
Compiled planand itsKey. A compiled plan is read-only, so many sessions use the same one at the same time. - Each execution needs an
Execution contextof that plan. It is the part that holds parameter values and runtime state, and there is one for each concurrently executing session. A finished context is not discarded; it stays in the cache and is reused by the next execution.
How a statement gets a plan
Figure. When a batch arrives
flowchart TB
A["Batch arrives"] --> B["Search the plan cache by<br/>text hash and SET options"]
B --> C{"Is there a plan?"}
C -->|"Yes"| D{"Still valid?<br/>schema, statistics"}
D -->|"Yes"| R["Get an execution context and execute"]
D -->|"No"| RC["Statement-level recompilation"]
C -->|"No"| P["Parse, bind"]
P --> AP{"Eligible for simple<br/>parameterization?"}
AP -->|"Yes"| PZ["Compile as a prepared plan<br/>with literals replaced by parameters"]
AP -->|"No"| AD["Compile as an ad hoc plan<br/>with the text as is"]
PZ --> ST["Store in the plan cache"]
AD --> ST
RC --> ST
ST --> R
Diagram notes: it proceeds from top to bottom.
- The server searches the cache with the hash of the whole batch text and the current
SEToptions. The text is compared character for character, so a difference in whitespace, case, or comments makes a different entry. - Even if a plan exists, if the schema of a referenced table changed or statistics were updated, only that statement is recompiled (
Statement-level recompilation). - If there is no plan, SQL Server parses, binds names to actual objects (
Bind), and then optimizes. If the statement is so simple that the plan would be the same for any value, it builds a plan with the literals replaced by parameters so that statements differing only in values share it (simple parameterization). Statements with joins,INlists,TOP, or subqueries are not eligible. - Other statements become an
ad hoc planwith the text as is. One plan accumulates for each statement with different values.
Parameterization
-- Ad hoc: one plan per value
SELECT * FROM orders o JOIN customers c ON c.cust_id = o.cust_id WHERE o.cust_id = 101;
-- Explicit parameterization: one plan reused with only the value changing
EXEC sp_executesql
N'SELECT * FROM orders o JOIN customers c ON c.cust_id = o.cust_id WHERE o.cust_id = @id',
N'@id int', @id = 101;
| Method | Description |
|---|---|
| Explicit parameterization | sp_executesql, stored procedures, parameterized commands of a driver. The most reliable method |
| Simple parameterization | Default behavior. The server does it automatically, only for simple statements |
| Forced parameterization | ALTER DATABASE … SET PARAMETERIZATION FORCED. Replaces literals with parameters in most statements. Costs you for statements whose plan should differ by value |
optimize for ad hoc workloads | Stores only a small stub instead of the whole plan for an ad hoc statement seen for the first time, and stores the whole plan on the second execution. Reduces single-use plans filling the cache |
| Prepared handle | A handle returned by sp_prepare is executed with sp_execute. The handle belongs to the session, but the plan it points to is in the shared cache |
Parameter sniffing. When a parameterized statement is first compiled, the plan is decided using the values at that moment (sniffing), and later executions with other values use the same plan. If the value distribution is even, this is a gain; if it is skewed, a plan that fits only the first value that arrived becomes fixed.
| Countermeasure | Description |
|---|---|
OPTION (RECOMPILE) | Compiles with that value on every execution. Does not cache the plan |
OPTION (OPTIMIZE FOR (@p = value)), OPTIMIZE FOR UNKNOWN | Decides the plan using a specified value or the average distribution |
| Parameter Sensitive Plan optimization (2022, compatibility level 160) | Finds predicates with a skewed value distribution and caches separate plan variants for ranges of values |
| Query Store | Stores per-statement plan history and execution statistics in the database. Can force a plan that performed well. On by default in new databases since 2022 |
Invalidation and eviction
- Recompilation. Schema changes, statistics updates, changes to
SEToptions that affect the plan,sp_recompile, and changes in the row count of a temporary table trigger statement-level recompilation. - Eviction. Each entry has a value determined by its compile cost and usage frequency, and under memory pressure, entries with the lowest value are evicted first. The plan cache has a pressure limit proportional to total memory, so it does not grow without bound.
- Full clearing. A server restart,
DBCC FREEPROCCACHE, and somesp_configurechanges empty the cache. Right after that, every statement is recompiled and CPU spikes. To clear only one database, useALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE.
Result Sets and Cursors
| Method | How to open | Behavior |
|---|---|---|
| Default result set | Run a SELECT with no special settings | The server sends rows over the network as it produces them. Forward-only, read-only. No cursor state on the server. Until the client reads everything, it cannot send another request on that connection (without MARS) |
| T-SQL cursor | DECLARE … CURSOR, OPEN, FETCH, CLOSE, DEALLOCATE | Processes one row at a time in a procedure or script |
| API server cursor | The driver calls sp_cursoropen, sp_cursorfetch | When a cursor type is specified in ODBC or JDBC. Fetches the specified number of rows at a time |
If the client does not read a default result set, the server's worker waits for the network buffer to empty (an ASYNC_NETWORK_IO wait). Meanwhile it may hold read locks or row versions, so code that does slow per-row processing while receiving results shows up as waits on the server side.
Server cursor types
| Type | Membership (which rows) | Values | Where stored |
|---|---|---|---|
STATIC | Fixed at open | Copy as of open | Copies the whole result into tempdb |
KEYSET | Fixed at open | Current values at fetch | Stores only the keys in tempdb |
DYNAMIC | Re-evaluated on every fetch | Current values | Not stored |
FAST_FORWARD | Forward-only, read-only | Runs in one of the ways above depending on the plan | Depends on the plan |
DECLARE @ord_id int, @amt int;
DECLARE c CURSOR LOCAL FAST_FORWARD FOR
SELECT ord_id, amt FROM orders WHERE cust_id = 101;
OPEN c;
FETCH NEXT FROM c INTO @ord_id, @amt;
WHILE @@FETCH_STATUS = 0
BEGIN
-- process one row
FETCH NEXT FROM c INTO @ord_id, @amt;
END;
CLOSE c;
DEALLOCATE c;
- The default scope of a cursor is
GLOBAL, so it stays on the connection after the procedure ends. AddLOCAL, or change the database'sCURSOR_DEFAULTtoLOCAL. A cursor that is onlyCLOSEd and notDEALLOCATEd keeps its name and plan. - If the statement does not support the requested type, the server changes it to another type (implicit cursor conversion).
- A cursor runs separately for each
FETCH, so a cursor loop that processes one row at a time is much slower than a single set-based statement that does the same job. Use it only for administrative tasks that must process one row at a time.
In the Sandbox
These are the values seen in this site's SQL Server sandbox (2022 CU28).
| Item | Value |
|---|---|
@@MAX_CONNECTIONS / user connections | 32,767 / 0 |
network packet size | 4,096 |
| Endpoints | Dedicated Admin Connection, TSQL Default TCP, TSQL Local Machine (shared memory), TSQL Named Pipes, TSQL Default VIA |
| Sessions | 1 user, 46 system sessions (sleeping) |
| Cached plans | 157 ad hoc at 22.8MB, 7 prepared plans at 1.2MB |
| Bound trees (views) | 173 at 23.6MB |
CACHESTORE_SQLCP / CACHESTORE_OBJCP | 164 entries at 28MB / 0 entries |
optimize for ad hoc workloads | 0 |
tune database | Forced parameterization off, Query Store on, CURSOR_CLOSE_ON_COMMIT off, default cursor scope GLOBAL |
Most statements in the sandbox arrive as ad hoc statements with the text as is, so there are 157 ad hoc plans against 7 prepared plans.
Configuration and Checks
-- Number and size of cached plans by type
SELECT objtype, cacheobjtype, COUNT(*) AS plans, SUM(CAST(size_in_bytes AS bigint)) / 1024 AS kb, SUM(usecounts) AS uses
FROM sys.dm_exec_cached_plans GROUP BY objtype, cacheobjtype ORDER BY kb DESC;
-- Size occupied by ad hoc plans used only once
SELECT COUNT(*) AS plans, SUM(CAST(size_in_bytes AS bigint)) / 1024 / 1024 AS mb
FROM sys.dm_exec_cached_plans WHERE objtype = 'Adhoc' AND usecounts = 1;
-- Find statements that differ only in literals: many plans under the same query_hash
SELECT query_hash, COUNT(*) AS entries, SUM(execution_count) AS execs
FROM sys.dm_exec_query_stats GROUP BY query_hash HAVING COUNT(*) > 20 ORDER BY entries DESC;
-- Text and plan of cached statements
SELECT TOP 10 qs.execution_count, qs.total_worker_time, st.text, qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_worker_time DESC;
-- Attributes that go into the plan key (SET options and so on)
SELECT * FROM sys.dm_exec_plan_attributes(<plan_handle>) WHERE is_cache_key = 1;
-- Open server cursors
SELECT session_id, name, properties, creation_time, is_open FROM sys.dm_exec_cursors(0);
-- Sessions and connections
SELECT s.session_id, s.status, s.program_name, s.open_transaction_count, c.net_transport, c.encrypt_option
FROM sys.dm_exec_sessions s LEFT JOIN sys.dm_exec_connections c ON c.session_id = s.session_id
WHERE s.is_user_process = 1;
- If the same statement gets separate plans per application, look at differences in
SEToptions. SSMS connects withARITHABORT ONand most drivers withOFF, so the cache entries split. This is a common cause of the "fast in SSMS but slow in the application" phenomenon: the two entries were sniffed with different values. - The plan cache is emptied on restart, so
sys.dm_exec_query_statsalso holds values since the restart. If you need history, look at Query Store.
Comparison with Other DBMSs
| SQL Server | PostgreSQL | MySQL | Oracle | KDBS | |
|---|---|---|---|---|---|
| Execution plan cache | Plan cache (all sessions) | Session-local, prepared statements only | None | Shared pool (all sessions) | None. Remembers only join order |
| Automatic literal replacement | Simple and forced parameterization | None | None | CURSOR_SHARING = FORCE | Literals excluded when computing the shape |
| Plan by value | Parameter sniffing, PSP optimization | Value-specific plan and generic plan | Optimized on every execution | Bind peeking, adaptive cursor sharing | Compiled on every execution |
| Default result delivery | Streamed (no cursor) | Whole result to the client | Whole result to the client | Array fetch from the cursor | Streamed or collected in a portal |
| Connection pool | Client driver | External pooler | Client, proxy | Client, shared server, DRCP | Client |
The full comparison is in DBMS Architecture at a Glance.
NOTE Default pool sizes and timeouts of drivers differ by driver. The default behavior of Parameter Sensitive Plan optimization and Query Store depends on the version and compatibility level.
Related pages
- DBMS Architecture at a Glance
- SQL Server / Azure SQL
- SQL Server Memory and Thread Structure
- SQL Server Buffer Pool
- SQL Server Locks and Lock Escalation
- RCSI and Snapshot Isolation
- PostgreSQL connections, cursors, and SQL cache
- MySQL Connections, Cursors, and SQL Cache
- Oracle Connections, Cursors, and the SQL Cache
- KDBS connections, portals, and statement cache