Explain the differences and use cases for temporary tables, table variables, and CTEs.

Instruction: Compare local temporary tables, table variables and CTEs in SQL Server. Discuss scope, persistence, statistics, transaction behavior and suitable workloads; do not assume all three are materialized temporary storage.

Context: This question tests the candidate's knowledge of various SQL features for managing temporary data and their ability to choose the appropriate tool for different scenarios.

Updated

Official answer

These terms are engine-specific; in SQL Server:

  • A local temporary table such as #work is a tempdb object, supports indexes and statistics, and can serve several statements in its scope. It is useful for staged processing and repeated joins.
  • A table variable such as @work is scoped to its batch, procedure or function. It is also backed by tempdb, not inherently memory-only. It lacks ordinary distribution statistics; deferred compilation at compatibility level 150 can improve initial row-count estimates but does not add those statistics. Outer transaction rollback does not undo table-variable contents as it would ordinary table changes.
  • A CTE names a query expression for the following statement. It is not persistent temporary storage or a promise that the result is computed and cached once. Recursive CTEs support hierarchy traversal with termination safeguards.

For example, use a CTE to make a single aggregation readable, a temporary table when several later statements need indexed intermediate results, and consider a table variable for a small scoped set after checking the plan. Choose from actual row counts, reuse, indexes, estimates and transaction needs; there is no universal size cutoff.

Sources: table variables, CTEs.

Related Questions