Disclaimer: This is work in progress intended to consolidate information from various sources. It considers only on-premise SQL Server, for other platforms please refer to the documentation.
Last updated: 9-Apr-2025
[SQL Server 2005] Tempdb database
- {def} system database available as a global resource to all users connected to a Database Engine instance [1]
- does not persist after SQL Server shuts down
- created at restart using the specifications from the model database
- doesn’t need crash recovery
- requires rollback capabilities
- {scenario} when updating a row in a global temporary table and rolling back the transaction [12]
- there's no way to undo this change unless was logged the ‘before value’ of the update [12]
- there is no need to log the ‘after value’ of the update because this value is only needed when the transaction needs to be ‘redone’ which happens during database recovery [12]
- {scenario} during an Insert operation
- only redo information is needed
- when insert a row in say a global temporary table, the actual ‘row value’ is not logged because SQL Server does not need the ‘row’ to undo except it needs to set the offsets within the page appropriately or if this insert had caused a new page to be allocate, de-allocate the page [12]
- only redo information is needed
- not all objects in TempDB are subject to logging [18]
- {characteristic} critical database
- ⇒ needs to be configured adequately
- has the highest level of create and drop actions [5]
- under high stress the allocation pages, syscolumns and sysobjects can become bottlenecks [5]
- workers use tempdb like any other database
- any worker can issue I/O to and from tempdb as needed [5]
- if the tempdb database cannot be created, SQL Server will not start [7]
- {recommendation} start SQL Server by using the (-f) startup parameter
- files
- {operation} changing the tempdb database
- {step} use ALTER database statement and MODIFY FILE clause to change the physical file names of each file in the tempdb database to refer to the new physical location [7]
- {step} stop and restart SQL Server
- {operation} create file group
- only one file group for data and one file group for logs are allowed.
- {default} the number of files is set to 1
- can be a high contention point for internal tracking structures
- often it's better to create multiple files for tempdb
- multiple files can be created for each file group
- {recommendation} set the number of files to match the number of CPUs that are configured for the instance
- ⇐ if the number of logical processors is less than or equal to eight [1]
- otherwise, use eight data files [1]
- contention is still observed, increase the number of data files by multiples of four until the contention decreases to acceptable levels, or make changes to the workload [1]
- ⇐ it’s not imperative
- {scenario}add a file per CPU (aka multiple files)
- allows the file group manager to
- pick the next file
- there are some optimizations here for tempdb to avoid contention and skip to the next file when under contention [4]
- then use the target location to start locating free space [4]
- ⇐ SQL Server creates a logical scheduler for each of the CPUs presented to it (logical or physical)
- allows each of the logical schedulers to loosely align with a file [4]
- since can be only 1 active worker per scheduler this allows each worker to have its own tempdb file (at that instant) and avoid allocation contention [4]
- internal latching and other activities achieve better separation (per file)
- ⇒ the workers don’t cause a resource contention on a single tempdb file
- rare type of contention [5]
- {misconception}
- leads to new I/O threads per file [5]
- {scenario} add more data files
- may help to solve potential performance problems that are due to I/O operations.
- helps to avoid a latch contention on allocation pages
- ⇐ manifested as a UP-latch)
- {downside} having too many files
- increases the cost of file switching
- requires more IAM pages
- increases the manageability overhead.
- {recommendation} configure the size of the files to be equal
- ⇐ to better use the allocation mechanism (proportional fill),
- {recommendation} create tempdb files striped across fast disks
- the size of the tempdb affect the performance of the database
- {event} server restarts
- the tempdb file size is reset to the configured value (the default is 8 MB).
- {feature} auto grow
- temporary
- ⇐ unlike other types of databases)
- when the tempdb grows, all transactional activity may come to an halt
- because TempDB is used by most operations and these activities will get blocked until more disk space gets allocated to the TempDB [12]
- {recommendation} pre-allocate the size of the TempDB that matches the needs of workload [12]
- {recommendation} should only be used more for exceptions rather than as a strategy [12]
- transactions
- lose the durability attribute
- can be rolled back
- there is no need to REDO them because the contents of tempdb do not persist across server restarts
- because the transaction log does not need to be flushed, transactions are committed faster in tempdb than in user databases. In tempdb, transactions
- most internal operations on tempdb do not generate log records because there is no need to roll back
- {restriction} add filegroups [1]
- {restriction} remove the primary filegroup, primary data file, or log file [1]
- {restriction} renaming the database or primary filegroup [1]
- {restriction} back up or restore the database [1]
- {restriction} change collation [1]
- the default collation is the server collation [1]
- {restriction} change the database owner [1]
- {restriction} create a database snapshot [1]
- {restriction} drop the database [1]
- {restriction} drop the quest user from the database [1]
- {restriction} enable CDC
- {restriction} participate in database mirroring [1]
- {restriction} can only be configured in the simple recovery model
- ⇒ the value can’t be changed
- {restriction} auto shrink is not allowed for tempdb
- database shrink and file shrink capabilities are limited
- ⇐ because many of the hidden objects stored in tempdb cannot be moved by shrink operations
- {restriction} the database CHECKSUM option cannot be enabled
- {restriction} database snapshots cannot be created
- {restriction} DBCC CHECKALLOC and DBCC CHECKCATALOG are not supported.
- only offline checking for DBCC CHECKTABLE is performed
- ⇒ TAB-S lock is needed
- here are internal consistency checks that occur when tempdb is in use
- if the checks fail, the user connection is broken and the tempdb space used by the connection is freed.
- {restriction} set the database to OFFLINE
- {restriction} set the database or primary filegroup to READ_ONLY [1]
- used by
- {feature} query
- {feature} temporary tables
- {feature} table variables
- {feature} table-valued functions
- {feature} user-defined functions
- {feature} online/offline index creation
- {feature} triggers
- {feature} cursors
- {feature} RCSI
- {feature} MARS
- {feature} DBCC CHECK
- {feature} LOB parameters
- {feature} Service Broker and event notification
- {feature} XML and LOB variable
- {feature} query notifications
- {feature} database mail
- used to store
- user objects
- objects explicitly created
- user objects that can be created in a user database can also be created in tempdb [1]
- {limitation} there's no durability guarantee [1]
- {limitation} dropped when the Database Engine instance restarts [1]
- {type} global and local temporary tables
- correspond to ## and # tables and table variables created explicitly by the application [12]
- REDO information is not logged
- {type} indexes on global and local temporary tables
- {type} table variables
- {type} tables returned in table-valued functions
- {type} cursors
- improved caching for temporary objects
- temp objects
- only cached when none of the following conditions is violated: [12]
- named constraints are not created
- DDL statements that affect the table are not run after the temp table has been created
- e.g. CREATE INDEX or CREATE STATISTICS statements
- not created by using dynamic SQ
- e.g. sp_executesql N'create table #t(a int)'
- internal objects
- objects created internally by SQL Server
- each object uses a minimum of nine pages [1]
- an IAM page and an eight-page extent [1]
- {type} work tables
- store intermediate results for spools, cursors, sorts, and temporary LOB storage [1]
- {type} work files
- used for for hash join or hash aggregate operations [1]
- {type} intermediate sort results
- used for operations
- creating or rebuilding indexes
- if SORT_IN_TEMPDB is specified
- certain GROUP BY, ORDER BY
- UNION queries
- {restriction} applications cannot directly insert into or delete rows from them
- {restriction} metadata is stored in memory
- {restriction} metadata does not appear in system catalog views such as sys.all_objects.
- {restriction} considered to be hidden objects
- {restriction} updates to them do not generate log records
- {restriction} page allocations do not generate log records unless on a sort unit. If the statement fails, these objects are deallocated.
- each object occupies at least nine pages (one IAM page and eight data pages) in tempdb
- used
- to store intermediate runs for sort
- to store intermediate results for hash joins and hash aggregates.
- to store XML variables or other LOB data type variables
- e.g. text, image, ntext, varchar(max), varbinary(max), and all others
- by queries that need a spool to store intermediate results
- by keyset cursors to store the keys
- by static cursors to store a query result
- by Service Broker to store messages in transit
- by INSTEAD OF triggers to store data for internal processing
- by any feature that uses the above mentioned operations
- version stores
- collections of data pages that hold the data rows that support row versioning [1]
- {type} common version store
- {type} online index build version store
- {} storage
- I/O characteristics
- {requirement} read after rights
- {def} the ability of the subsystem to service read requests with the latest data image when the read is issued after any write is successfully completed [7]
- {recommendation} writer ordering
- {def} the ability of the subsystem to maintain the correct order of write operations [7]
- {recommendation} torn I/O prevention
- {def} the ability of the system to avoid splitting individual I/O requests [7]
- {requirement} physical sector alignment and size
- devices are required to support sector attributes permitting SQL Server to perform writes on physical sector-aligned boundaries and in multiples of the sector size [7]
- can be put on specialty systems
- ⇐ they can’t be used for other databases
- RAM disks
- non-durable media
- support double RAM cache
- one in the buffer pool and one on the RAM disk
- ⇐ directly takes away from the buffer pool’s total possible size and generally decreases the performance [7]
- give up RAM
- implementations of RAM disks and RAM-based files caches
- solid state
- high speed subsystems
- {recommendation} confirm with the product vendor to guarantee full compliance with SQL Server I/O needs [7]
- sort errors were frequently solved by moving tempdb to a non-caching local drive or by disabling the read caching mechanism [8]
- {feature} logging optimization
- avoids logging the "after value" in certain log records in tempdb
- when an UPDATE operation is performed without this optimization, the before and after values of the data are recorded in the log file
- can significantly reduce the size of the tempdb log as well as reduce the amount of I/O traffic on the tempdb log device
- {feature} instant data file initialization
- isn’t zeroing out the NTFS file when the file is created or when the size of the file is increased
- {benefit} minimizes overhead significantly when tempdb needs to auto grow.
- without this, auto grow could take a long time and lead to application timeout.
- reduces the impact of database creation [5]
- because zero’s don’t have to be stamped in all bytes of a database file, only the log files [5]
- reduces the gain from using multiple threads during database creation. [5]
- {feature} proportional fill optimization
- reduces UP latch contention in tempdb
- when there are multiple data files in tempdb, each file is filled in proportion to the free space that is available in the file so that all of the files fill up at about the same time
- ⇐ accomplished by removing a latch that was taken during proportional fill.
- {feature} deferred drop in tempdb
- when a large temporary table is dropped by an application, it is handled by a background task and the application does not have to wait
- ⇒ faster response time to applications.
- {feature} worktable caching
- {improvement} when a query execution plan is cached, the work tables needed by the plan are not dropped across multiple executions of the plan but merely truncated
- ⇐ in addition, the first nine pages for the work table are kept.
- {feature} caches temporary objects
- when a table-valued functions, table variables, or local temporary tables are used in a stored procedure, function, or trigger, the frequent drop and create of these temporary objects can be time consuming
- ⇐ this can cause contentions on tempdb system catalog tables and allocation pages
References
[1] Microsoft Learn (2024) SQL Server: Tempdb database [
link]
[2] Wei Xiao et al (2006) Working with tempdb in SQL Server 2005
[4] CSS SQL Server Engineers (2009) SQL Server TempDB – Number of Files – The Raw Truth [
link]
[5] SQL Server Support Blog (2007) SQL Server Urban Legends Discussed [
link]
[6] Microsoft Learn (2023) SQL Server: Microsoft SQL Server I/O subsystem requirements for the tempdb database [
link]
[7] Microsoft Learn (2023) SQL Server: Microsoft SQL Server I/O subsystem requirements for the tempdb database [
link]
[8] Microsoft Learn (2023) SQL Server: SQL Server diagnostics detects unreported I/O problems due to stale reads or lost writes [
link]
[12a] SQL Server Blog (2008) Managing TempDB in SQL Server: TempDB Basics (Version Store: Simple Example), by Sunil Agarwal [
link]
[12b] SQL Server Blog (2008) Managing TempDB in SQL Server: TempDB Basics (Version Store: logical structure), by Sunil Agarwal [
link]
[18] Simple Talk (2020) Temporary Tables in SQL Server, by Phil Factor [
link]
[19] Microsoft Learn (2023) SQL Server: Recommendations to reduce allocation contention in SQL Server tempdb database [
link]
Acronyms:
DB - database
DDL - Data Definition Language
I/O - Input/Output
LOB - large object
MARS - Multiple Active Result Sets
NTFS - New Technology File System
RAM - Random-Access Memory
RCSI - Read Committed Snapshot Isolation