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

ItemValue
ProtocolTDS (Tabular Data Stream). TCP default port 1433, shared memory, named pipes
Maximum connectionsuser connections default 0 = up to 32,767 (@@MAX_CONNECTIONS)
Packet sizenetwork 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 connectionOne by default. With MARS on, multiple requests run interleaved
Execution plan cacheShared by all sessions. A cache store within max server memory
Cache keyHash of the statement text (whitespace and case sensitive) + SET options that affect the plan + database
Automatic parameterizationSimple (default): only safe, simple statements. Forced (PARAMETERIZATION FORCED): most literals
Ad hoc plan reductionoptimize for ad hoc workloads (default 0): on first execution, stores only a small stub instead of the plan
Default result modeDefault result set (forward-only, read-only, no server cursor)
Server cursor typesSTATIC, KEYSET, DYNAMIC, FAST_FORWARD
Cursor scopeDefault GLOBAL (whole connection). Change with CURSOR_DEFAULT LOCAL
Commit and cursorsCURSOR_CLOSE_ON_COMMIT default OFF: cursors are not closed on commit
Result cacheNone

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.

  1. When the application opens a connection, the driver's Client connection pool receives 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.
  2. 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.
  3. Even when the application closes the connection, the pool keeps the real connection. In sys.dm_exec_sessions, this session appears as sleeping.
  4. When a connection is taken from the pool again, the driver attaches sp_reset_connection to the first request. Session state such as temporary tables, SET options, 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.

ViewOne rowKey columns
sys.dm_exec_connectionsNetwork connectionnet_transport, encrypt_option, auth_scheme, client_net_address
sys.dm_exec_sessionsSessionstatus, login_name, program_name, open_transaction_count, is_user_process
sys.dm_exec_requestsRunning requeststatus, 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 store holds plans of ad hoc statements and prepared statements (sp_executesql, parameterized commands), and the Object plan store holds plans of procedures, triggers, and functions. The Bound tree store is not plans but the parsed trees of views and constraints.
  • One entry is a Compiled plan and its Key. A compiled plan is read-only, so many sessions use the same one at the same time.
  • Each execution needs an Execution context of 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.

  1. The server searches the cache with the hash of the whole batch text and the current SET options. The text is compared character for character, so a difference in whitespace, case, or comments makes a different entry.
  2. 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).
  3. 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, IN lists, TOP, or subqueries are not eligible.
  4. Other statements become an ad hoc plan with 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;
MethodDescription
Explicit parameterizationsp_executesql, stored procedures, parameterized commands of a driver. The most reliable method
Simple parameterizationDefault behavior. The server does it automatically, only for simple statements
Forced parameterizationALTER 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 workloadsStores 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 handleA 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.

CountermeasureDescription
OPTION (RECOMPILE)Compiles with that value on every execution. Does not cache the plan
OPTION (OPTIMIZE FOR (@p = value)), OPTIMIZE FOR UNKNOWNDecides 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 StoreStores 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 SET options 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 some sp_configure changes empty the cache. Right after that, every statement is recompiled and CPU spikes. To clear only one database, use ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE.

Result Sets and Cursors

MethodHow to openBehavior
Default result setRun a SELECT with no special settingsThe 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 cursorDECLARE … CURSOR, OPEN, FETCH, CLOSE, DEALLOCATEProcesses one row at a time in a procedure or script
API server cursorThe driver calls sp_cursoropen, sp_cursorfetchWhen 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

TypeMembership (which rows)ValuesWhere stored
STATICFixed at openCopy as of openCopies the whole result into tempdb
KEYSETFixed at openCurrent values at fetchStores only the keys in tempdb
DYNAMICRe-evaluated on every fetchCurrent valuesNot stored
FAST_FORWARDForward-only, read-onlyRuns in one of the ways above depending on the planDepends 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. Add LOCAL, or change the database's CURSOR_DEFAULT to LOCAL. A cursor that is only CLOSEd and not DEALLOCATEd 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).

ItemValue
@@MAX_CONNECTIONS / user connections32,767 / 0
network packet size4,096
EndpointsDedicated Admin Connection, TSQL Default TCP, TSQL Local Machine (shared memory), TSQL Named Pipes, TSQL Default VIA
Sessions1 user, 46 system sessions (sleeping)
Cached plans157 ad hoc at 22.8MB, 7 prepared plans at 1.2MB
Bound trees (views)173 at 23.6MB
CACHESTORE_SQLCP / CACHESTORE_OBJCP164 entries at 28MB / 0 entries
optimize for ad hoc workloads0
tune databaseForced 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 SET options. SSMS connects with ARITHABORT ON and most drivers with OFF, 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_stats also holds values since the restart. If you need history, look at Query Store.

Comparison with Other DBMSs

SQL ServerPostgreSQLMySQLOracleKDBS
Execution plan cachePlan cache (all sessions)Session-local, prepared statements onlyNoneShared pool (all sessions)None. Remembers only join order
Automatic literal replacementSimple and forced parameterizationNoneNoneCURSOR_SHARING = FORCELiterals excluded when computing the shape
Plan by valueParameter sniffing, PSP optimizationValue-specific plan and generic planOptimized on every executionBind peeking, adaptive cursor sharingCompiled on every execution
Default result deliveryStreamed (no cursor)Whole result to the clientWhole result to the clientArray fetch from the cursorStreamed or collected in a portal
Connection poolClient driverExternal poolerClient, proxyClient, shared server, DRCPClient

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