Where is Table Variable Created? – Interview Question of the Week #243

Question: Are ordinary table variables created in memory or on disk? They use tempdb storage, just as temporary tables do. Their pages can be cached in memory, so “table variable” does not mean “memory-only.”

Temporary luggage rests in designated storage spaces on a shelf

After my table-variable and temporary-table articles, readers sent me enough versions of this question that it deserved an interview answer of its own. The original answer was deliberately blunt: hard disk, not memory. The useful correction is more precise: allocation in tempdb does not mean every access goes straight to a physical disk.

Both ordinary table variables and temporary tables can have pages in the buffer pool. Both can involve tempdb I/O. They still differ in scope, transaction behavior and optimization features. Choosing one because its name sounds like a programming-language variable is a poor starting point for a performance comparison.

There is a separate feature called a memory-optimized table type. A variable declared with such a type is different from the ordinary DECLARE @T TABLE example this question addresses. Don’t use that exception to claim that every table variable is memory-optimized.

The original demonstrations are worth reading together:

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

Disk, SQL Scripts, SQL Server, SQL TempDB, Temp Table
Previous Post
How to List All DML Triggers Created or Modified in the Last N Days in SQL Server? – Interview Question of the Week #242
Next Post
How to Download the Latest SQL Server Docker Image? – Interview Question of the Week #244

Related Posts

1 Comment. Leave new

  • I remember that long time ago a read something about table variables saying that when a small amount of data is inserted, it is handled in “Memory”, on the other hand, when a large amount of data is inserted, it will be treated as a Temp table, being created on Hard Disk. I’m not sure if it was true.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.