Search code examples
sqlsql-serveroptimizationtime

Temporary tables vs table variables


Temporary tables store on disk and table variables - in memory. This means that write to temp table should be significantly slower since writing to disk is slower than writing to RAM. However when I checked two below scripts, it turned out that their execution time is almost identical 900/1000 and temp table surprisingly wins. Why is that?

DROP TABLE #TEST

Create Table #test
(
    Id UNIQUEIDENTIFIER 
)

DECLARE @i INT = 1;

WHILE @i < 1000
     BEGIN 
        INSERT INTO #test VALUES  (NEWID())
        SET @i = @i + 1;
    END

AND

DECLARE @table1 TABLE
(
    Id UNIQUEIDENTIFIER 
)
DECLARE @i INT = 1;

WHILE @i < 1000
     BEGIN 
        INSERT INTO @table1 VALUES  (NEWID())
        SET @i = @i + 1;
    END

Solution

  • Hypothesis: Temporary tables store on disk and table variables - in memory.

    Experiment: When I checked two below scripts, it turned out that their execution time is almost identical

    Conclusion: Hypothesis is incorrect.

    In fact temporary tables are not written directly to disk, they are written into the buffer pool in memory, and only are written to disk if there's not enough memory available.

    Before SQL Server 2014, loading temp tables shared a code path with bulk loading regular tables, which wrote directly to the data files on disk. But in modern versions, a temp table might never be written to disk at all.