--- title: "tempdb Database | Microsoft Docs" description: This topic provides details regarding the configuration and use of the tempdb database in SQL Server and Azure SQL Database ms.custom: "P360" ms.date: 08/21/2019 ms.prod: sql ms.prod_service: "database-engine" ms.technology: ms.topic: conceptual helpviewer_keywords: - "temporary tables [SQL Server], tempdb database" - "tempdb database [SQL Server], about tempdb" - "temporary stored procedures [SQL Server]" - "tempdb database [SQL Server]" ms.assetid: ce4053fb-e37a-4851-b711-8e504059a780 author: "stevestein" ms.author: "sstein" ms.reviewer: carlrab monikerRange: "=azuresqldb-current||>=sql-server-2016||=sqlallproducts-allversions||>=sql-server-linux-2017||=azuresqldb-mi-current" --- # TempDB Database [!INCLUDE[appliesto-ss-asdb-xxxx-xxx-md](../../includes/appliesto-ss-asdb-xxxx-xxx-md.md)] The **TempDB** system database is a global resource that is available to all users connected to the instance of [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] or connected to SQL Database. Tempdb is used to hold: - Temporary **user objects** that are explicitly created, such as: global or local temporary tables and indexes, temporary stored procedures, table variables, Tables returned in table-valued functions, or cursors. - **Internal objects** that are created by the database engine. These include: - Work tables to store intermediate results for spools, cursors, sorts, and temporary large object (LOB) storage. - Work files for hash join or hash aggregate operations. - Intermediate sort results for operations such as creating or rebuilding indexes (if SORT_IN_TEMPDB is specified), or certain GROUP BY, ORDER BY, or UNION queries. > [!NOTE] > Each internal object uses a minimum of nine pages; an IAM page and an eight-page extent. For more information about pages and extents, see [Pages and Extents](../../relational-databases/pages-and-extents-architecture-guide.md#pages-and-extents). > [!IMPORTANT] > Azure SQL Database single databases and elastic pools support global temporary tables and global temporary stored procedures that are stored in TempDB and are scoped to the database level. Global temporary tables and global temporary stored procedures are shared for all users' sessions within the same Azure SQL database. User sessions from other Azure SQL databases cannot access global temporary tables. For more information, see [Database scoped global temporary tables (Azure SQL Database)](../../t-sql/statements/create-table-transact-sql.md#database-scoped-global-temporary-tables-azure-sql-database). [Azure SQL Database Managed Instance](https://docs.microsoft.com/azure/sql-database/sql-database-managed-instance)) supports the same temporary objects as does SQL Server. > For Azure SQL Database single databases and elastic pools, only master database and TempDB database apply. For more information, see [What is an Azure SQL Database server](https://docs.microsoft.com/azure/sql-database/sql-database-servers-databases#what-is-an-azure-sql-database-server). For a discussion of TempDB in the context of Azure SQL Database single databases and elastic pools, see [TempDB Database in Azure SQL Database single databases and elastic pools](#tempdb-database-in-sql-database). For Azure SQL Database Managed Instance, all system databases apply. - **Version stores**, which are a collection of data pages that hold the data rows that are required to support the features that use row versioning. There are two version stores: a common version store and an online-index-build version store. The version stores contain: - Row versions that are generated by data modification transactions in a database that uses read-committed using row versioning isolation or snapshot isolation transactions. - Row versions that are generated by data modification transactions for features, such as: online index operations, Multiple Active Result Sets (MARS), and AFTER triggers. Operations within **TempDB** are minimally logged so that transactions can be rolled back. **TempDB** is re-created every time [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] is started so that the system always starts with a clean copy of the database. Temporary tables and stored procedures are dropped automatically on disconnect, and no connections are active when the system is shut down. Therefore, there is never anything in **TempDB** to be saved from one session of [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] to another. Backup and restore operations are not allowed on **TempDB**. ## Physical Properties of TempDB in SQL Server The following table lists the initial configuration values of the **TempDB** data and log files in SQL Server, which are based on the defaults for the Model database. The sizes of these files may vary slightly for different editions of [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)]. |File|Logical name|Physical name|Initial size|File growth| |----------|------------------|-------------------|------------------|-----------------| |Primary data|tempdev|tempdb.mdf|8 megabytes|Autogrow by 64 MB until the disk is full| |Secondary data files*|temp#|tempdb_mssql_#.ndf|8 megabytes|Autogrow by 64 MB until the disk is full| |Log|templog|templog.ldf|8 megabytes|Autogrow by 64 megabytes to a maximum of 2 terabytes| \* The number of files depends on the number of (logical) processors on the machine. As a general rule, if the number of logical processors is less than or equal to eight, use the same number of data files as logical processors. If the number of logical processors is greater than eight, use eight data files and then if contention continues, increase the number of data files by multiples of 4 until the contention is reduced to acceptable levels or make changes to the workload/code. > [!NOTE] > The default value for the number of data files is based on the general guidelines in [KB 2154845](https://support.microsoft.com/kb/2154845/). ### Moving the TempDB data and log files in SQL Server To move the **TempDB** data and log files, see [Move System Databases](../../relational-databases/databases/move-system-databases.md). ### Database Options for TempDB in SQL Server The following table lists the default value for each database option in the **TempDB** database and whether the option can be modified. To view the current settings for these options, use the [sys.databases](../../relational-databases/system-catalog-views/sys-databases-transact-sql.md) catalog view. |Database option|Default value|Can be modified| |---------------------|-------------------|---------------------| |ALLOW_SNAPSHOT_ISOLATION|OFF|Yes| |ANSI_NULL_DEFAULT|OFF|Yes| |ANSI_NULLS|OFF|Yes| |ANSI_PADDING|OFF|Yes| |ANSI_WARNINGS|OFF|Yes| |ARITHABORT|OFF|Yes| |AUTO_CLOSE|OFF|No| |AUTO_CREATE_STATISTICS|ON|Yes| |AUTO_SHRINK|OFF|No| |AUTO_UPDATE_STATISTICS|ON|Yes| |AUTO_UPDATE_STATISTICS_ASYNC|OFF|Yes| |CHANGE_TRACKING|OFF|No| |CONCAT_NULL_YIELDS_NULL|OFF|Yes| |CURSOR_CLOSE_ON_COMMIT|OFF|Yes| |CURSOR_DEFAULT|GLOBAL|Yes| |Database Availability Options|ONLINE

MULTI_USER

READ_WRITE|No

No

No| |DATE_CORRELATION_OPTIMIZATION|OFF|Yes| |DB_CHAINING|ON|No| |ENCRYPTION|OFF|No| |MIXED_PAGE_ALLOCATION|OFF|No| |NUMERIC_ROUNDABORT|OFF|Yes| |PAGE_VERIFY|CHECKSUM for new installations of [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)].

NONE for upgrades of [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)].|Yes| |PARAMETERIZATION|SIMPLE|Yes| |QUOTED_IDENTIFIER|OFF|Yes| |READ_COMMITTED_SNAPSHOT|OFF|No| |RECOVERY|SIMPLE|No| |RECURSIVE_TRIGGERS|OFF|Yes| |Service Broker Options|ENABLE_BROKER|Yes| |TRUSTWORTHY|OFF|No| For a description of these database options, see [ALTER DATABASE SET Options (Transact-SQL)](../../t-sql/statements/alter-database-transact-sql-set-options.md). ## TempDB database in SQL Database ### TempDB sizes for DTU-based service tiers |SLO|Max TempDB Data File Size (GBs)|# of TempDB data files|Max TempDB data size (GB)| |---|---:|---:|---:| |Basic|13|1|13| |S0|13|1|13| |S1|13|1|13| |S2|13|1|13| |S3|32|1|32 |S4|32|2|64| |S6|32|3|96| |S7|32|6|192| |S9|32|12|384| |S12|32|12|384| |P1|13|12|156| |P2|13|12|156| |P4|13|12|156| |P6|13|12|156| |P11|13|12|156| |P15|13|12|156| |Premium Elastic Pools (all DTU configurations)|13|12|156| |Standard Elastic Pools (S0-S2)|13|12|156| |Standard Elastic Pools (S3 and above) |32|12|384| |Basic Elastic Pools (all DTU configurations)|13|12|156| |||| ### TempDB sizes for vCore-based service tiers See [vCore-based resource limits](https://docs.microsoft.com/azure/sql-database/sql-database-vcore-resource-limits) ## Restrictions The following operations cannot be performed on the **TempDB** database: - Adding filegroups - Backing up or restoring the database - Changing collation. The default collation is the server collation - Changing the database owner. **TempDB** is owned by **sa** - Creating a database snapshot - Dropping the database - Dropping the **guest** user from the database - Enabling change data capture - Participating in database mirroring - Removing the primary filegroup, primary data file, or log file - Renaming the database or primary filegroup - Running DBCC CHECKALLOC - Running DBCC CHECKCATALOG - Setting the database to OFFLINE - Setting the database or primary filegroup to READ_ONLY ## Permissions Any user can create temporary objects in TempDB. Users can only access their own objects, unless they receive additional permissions. It is possible to revoke the connect permission to TempDB to prevent a user from using TempDB, but is not recommended as some routine operations require the use of TempDB. ## Optimizing TempDB performance in SQL Server The size and physical placement of the TempDB database can affect the performance of a system. For example, if the size that is defined for TempDB is too small, part of the system-processing load may be taken up with auto growing TempDB to the size required to support the workload every time you restart the instance of [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)]. If possible, use [database instant file initialization](../../relational-databases/databases/database-instant-file-initialization.md) to improve the performance of data file grow operations. Preallocate space for all TempDB files by setting the file size to a value large enough to accommodate the typical workload in the environment. Preallocation prevents TempDB from expanding too frequently, which affects performance. The TempDB database should be set to autogrow, but this should be used to increase disk space for unplanned exceptions. Data files should be of equal size within each [filegroup](../../relational-databases/databases/database-files-and-filegroups.md#filegroups), as [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] uses a proportional-fill algorithm that favors allocations in files with more free space. Dividing TempDB into multiple data files of equal size provides a high degree of parallel efficiency in operations that use TempDB. Set the file growth increment to a reasonable size to avoid the TempDB database files from growing by too small a value. If the file growth is too small, compared to the amount of data that is being written to TempDB, TempDB may have to constantly expand and affect performance. To check current TempDB size and growth parameters, use the following query: ```sql SELECT name AS FileName, size*1.0/128 AS FileSizeInMB, CASE max_size WHEN 0 THEN 'Autogrowth is off.' WHEN -1 THEN 'Autogrowth is on.' ELSE 'Log file grows to a maximum size of 2 TB.' END, growth AS 'GrowthValue', 'GrowthIncrement' = CASE WHEN growth = 0 THEN 'Size is fixed.' WHEN growth > 0 AND is_percent_growth = 0 THEN 'Growth value is in 8-KB pages.' ELSE 'Growth value is a percentage.' END FROM tempdb.sys.database_files; GO ``` Put the TempDB database on a fast I/O subsystem. Use disk striping if there are many directly attached disks. Individual or groups of TempDB data files do not necessarily need to be on different disks or spindles unless you are also encountering I/O bottlenecks. Put the TempDB database on disks that differ from those that are used by user databases. ## Performance improvements in TempDB for SQL Server Starting with [!INCLUDE[ssSQL15](../../includes/sssql15-md.md)], **TempDB** performance is further optimized in the following ways: - Temporary tables and table variables are cached. Caching allows operations that drop and create the temporary objects to execute very quickly and reduces page allocation contention. - Allocation page latching protocol is improved to reduce the number of UP (update) latches that are used. - Logging overhead for **TempDB** is reduced to reduce disk I/O bandwidth consumption on the **TempDB** log file. - Setup adds multiple TempDB data files during a new instance installation. This task can be accomplished with the new UI input control on the **Database Engine Configuration** section and a command-line parameter `/SQLTEMPDBFILECOUNT`. By default, setup adds as many TempDB data files as the logical processor count or eight, whichever is lower. - When there are multiple **TempDB** data files, all files autogrow at same time and by the same amount depending on growth settings. [Trace flag 1117](../../t-sql/database-console-commands/dbcc-traceon-trace-flags-transact-sql.md) is no longer required. - All allocations in **TempDB** use uniform extents. [Trace flag 1118](../../t-sql/database-console-commands/dbcc-traceon-trace-flags-transact-sql.md) is no longer required. - For the primary filegroup, the AUTOGROW_ALL_FILES property is turned on and the property cannot be modified. For more information on performance improvements in TempDB, see the following blog article: [TEMPDB - Files and Trace Flags and Updates, Oh My!](https://blogs.msdn.microsoft.com/sql_server_team/tempdb-files-and-trace-flags-and-updates-oh-my/) ## Memory-Optimized TempDB Metadata TempDB metadata contention has historically been a bottleneck to scalability for many workloads running on [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)]. [!INCLUDE[sql-server-2019](../../includes/sssqlv15-md.md)] introduces a new feature that is part of the [In-Memory Database](../in-memory-database.md) feature family, memory-optimized TempDB metadata, which effectively removes this bottleneck and unlocks a new level of scalability for TempDB-heavy workloads. In [!INCLUDE[sql-server-2019](../../includes/sssqlv15-md.md)], the system tables involved in managing temporary table metadata can be moved into latch-free non-durable memory-optimized tables. Watch this 7-minute video for an overview of how and when to use memory optimized TempDB metadata: > [!VIDEO https://channel9.msdn.com/Shows/Data-Exposed/How-and-When-To-Memory-Optimized-TempDB-Metadata/player?WT.mc_id=dataexposed-c9-niner] In order to opt-in to this new feature, use the following script: ```sql ALTER SERVER CONFIGURATION SET MEMORY_OPTIMIZED TEMPDB_METADATA = ON ``` This configuration change requires a restart of the service to take effect. There are some limitations with this implementation that are important to note: 1. Toggling the feature on and off is not dynamic. Because of the intrinsic changes that need to be made to the structure of TempDB, a restart is required to either enable or disable the feature. 2. A single transaction may not access memory-optimized tables in more than one database. This means that any transactions that involve a memory-optimized table in a user database will not be able to access TempDB system views in the same transaction. If you attempt to access TempDB system views in the same transaction as a memory-optimized table in a user database, you will receive the following error: ``` A user transaction that accesses memory optimized tables or natively compiled modules cannot access more than one user database or databases model and msdb, and it cannot write to master. ``` Example: ```sql BEGIN TRAN SELECT * FROM tempdb.sys.tables -----> Creates a user In-Memory OLTP Transaction on Tempdb INSERT INTO .. VALUES (1) ----> Attempts to create user In-Memory OLTP transaction but will fail COMMIT TRAN ``` 3. Queries against memory-optimized tables do not support locking and isolation hints, so queries against memory-optimized TempDB catalog views will not honor locking and isolation hints. As with other system catalog views in [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)], all transactions against system views will be in READ COMMITTED (or in this case READ COMMITTED SNAPSHOT) isolation. 4. [Columnstore indexes](../indexes/columnstore-indexes-overview.md) cannot be created on temporary tables when Memory-Optimized TempDB Metadata is enabled. 5. Due to the limitation on columnstore indexes, use of the sp_estimate_data_compression_savings system stored procedure with the COLUMNSTORE or COLUMNSTORE_ARCHIVE data compression parameter is not supported when Memory-Optimized TempDB Metadata is enabled. > [!NOTE] > These limitations only apply when referencing TempDB system views, you will be able to create a temp table in the same transaction as you access a memory-optimized table in a user database if desired. You can verify whether or not TempDB is memory-optimized by using the following T-SQL command: ``` SELECT SERVERPROPERTY('IsTempdbMetadataMemoryOptimized') ``` If the server fails to start for any reason after enabling Memory-Optimized TempDB Metadata, you can bypass the feature by starting the SQL Server with [minimal configuration](../../database-engine/configure-windows/start-sql-server-with-minimal-configuration.md) using the **-f** startup option. This will enable you to disable the feature and then restart SQL Server in normal mode. ## Capacity Planning for TempDB in SQL Server Determining the appropriate size for TempDB in a [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] production environment depends on many factors. As described previously in this article, these factors include the existing workload and the [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] features that are used. We recommend that you analyze the existing workload by performing the following tasks in a SQL Server test environment: - Set autogrow on for TempDB. - Execute individual queries or workload trace files and monitor TempDB space use. - Execute index maintenance operations, such as rebuilding indexes and monitor TempDB space. - Use the space-use values from the previous steps to predict your total workload usage; adjust this value for projected concurrent activity, and then set the size of TempDB accordingly. ## How to Monitor TempDB use Running out of disk space in TempDB can cause significant disruptions in the [!INCLUDE[ssNoVersion](../../includes/ssnoversion-md.md)] production environment and can prevent applications that are running from completing operations. You can use the [sys.dm_db_file_space_usage](../../relational-databases/system-dynamic-management-views/sys-dm-db-session-space-usage-transact-sql.md) dynamic management view to monitor the disk space that is used in the TempDB files: ```sql -- Determining the Amount of Free Space in TempDB SELECT SUM(unallocated_extent_page_count) AS [free pages], (SUM(unallocated_extent_page_count)*1.0/128) AS [free space in MB] FROM sys.dm_db_file_space_usage; -- Determining the Amount Space Used by the Version Store SELECT SUM(version_store_reserved_page_count) AS [version store pages used], (SUM(version_store_reserved_page_count)*1.0/128) AS [version store space in MB] FROM sys.dm_db_file_space_usage; -- Determining the Amount of Space Used by Internal Objects SELECT SUM(internal_object_reserved_page_count) AS [internal object pages used], (SUM(internal_object_reserved_page_count)*1.0/128) AS [internal object space in MB] FROM sys.dm_db_file_space_usage; -- Determining the Amount of Space Used by User Objects SELECT SUM(user_object_reserved_page_count) AS [user object pages used], (SUM(user_object_reserved_page_count)*1.0/128) AS [user object space in MB] FROM sys.dm_db_file_space_usage; ``` Additionally, to monitor the page allocation or deallocation activity in TempDB at the session or task level, you can use the [sys.dm_db_session_space_usage](../../relational-databases/system-dynamic-management-views/sys-dm-db-session-space-usage-transact-sql.md) and [sys.dm_db_task_space_usage](../../relational-databases/system-dynamic-management-views/sys-dm-db-task-space-usage-transact-sql.md) dynamic management views. These views can be used to identify large queries, temporary tables, or table variables that are using lots of TempDB disk space. There are also several counters that can be used to monitor the free space that is available in TempDB and also the resources that are using TempDB. For more information, see the next section. ```sql -- Obtaining the space consumed by internal objects in all currently running tasks in each session SELECT session_id, SUM(internal_objects_alloc_page_count) AS task_internal_objects_alloc_page_count, SUM(internal_objects_dealloc_page_count) AS task_internal_objects_dealloc_page_count FROM sys.dm_db_task_space_usage GROUP BY session_id; -- Obtaining the space consumed by internal objects in the current session for both running and completed tasks SELECT R2.session_id, R1.internal_objects_alloc_page_count + SUM(R2.internal_objects_alloc_page_count) AS session_internal_objects_alloc_page_count, R1.internal_objects_dealloc_page_count + SUM(R2.internal_objects_dealloc_page_count) AS session_internal_objects_dealloc_page_count FROM sys.dm_db_session_space_usage AS R1 INNER JOIN sys.dm_db_task_space_usage AS R2 ON R1.session_id = R2.session_id GROUP BY R2.session_id, R1.internal_objects_alloc_page_count, R1.internal_objects_dealloc_page_count;; ``` ## Related Content [SORT_IN_TEMPDB Option For Indexes](../../relational-databases/indexes/sort-in-TempDB-option-for-indexes.md) [System Databases](../../relational-databases/databases/system-databases.md) [sys.databases](../../relational-databases/system-catalog-views/sys-databases-transact-sql.md) [sys.master_files](../../relational-databases/system-catalog-views/sys-master-files-transact-sql.md) [Move Database Files](../../relational-databases/databases/move-database-files.md)