SQL Server DBCC Commands Guide
An incident rarely announces which DBCC statement it needs. A log file stops truncating, a query slows after a plan changes, an identity column runs ahead of its table, and each one has a Database Console Command that answers it, sitting next to a few that can make the same situation worse. The DBCC statements are easiest to handle sorted by what they are used for, with a runnable statement for the ones you reach for most and a note on each one's cost and permissions.
Purpose and Overview
Where a dynamic management view reports state and leaves it alone, and ALTER INDEX or ALTER DATABASE change a single named object, the DBCC statements cover both jobs under one verb: some only read, some validate a whole database, and some rewrite storage or empty a memory cache. They fall into four categories, Maintenance, Miscellaneous, Informational, and Validation, but it is more useful to arrange them by the question a DBA is asking: is the database consistent, what is using the log, how do I free space or memory, and how do I fix a counter.
The practical split is between commands that observe and commands that change something. DBCC CHECKDB, CHECKTABLE, CHECKALLOC, and CHECKCATALOG validate structures. SQLPERF, OPENTRAN, SHOW_STATISTICS, and INPUTBUFFER report information. SHRINKDATABASE, SHRINKFILE, and the deprecated DBREINDEX and INDEXDEFRAG change how data sits on disk. FREEPROCCACHE, FREESYSTEMCACHE, and DROPCLEANBUFFERS empty memory structures. Several of these also have newer DMV or ALTER equivalents, and the sections below point to them where one exists.
Permissions differ by command. CHECKDB, CHECKALLOC, and the shrink commands require membership in the sysadmin fixed server role or the db_owner fixed database role. CHECKTABLE and DBREINDEX also allow table owners and db_ddladmin. The cache commands FREEPROCCACHE and FREESYSTEMCACHE require ALTER SERVER STATE. SQLPERF (LOGSPACE) requires VIEW SERVER STATE. Check the permission before you build an unattended job around any of them.
Code Breakdown
The table groups the commands you will actually run. Treat the validation rows as routine, the informational rows as on-demand, and the maintenance and cache rows as deliberate actions that need a reason.
| Family | Command | What it does |
|---|---|---|
| Validation | DBCC CHECKDB | Checks the logical and physical integrity of all objects in the database; runs CHECKALLOC, CHECKTABLE, and CHECKCATALOG internally |
| Validation | DBCC CHECKTABLE | Checks the integrity of all pages and structures of one table or indexed view |
| Validation | DBCC CHECKALLOC | Checks the consistency of disk space allocation structures for a database |
| Validation | DBCC CHECKCATALOG | Checks for catalog consistency within a database |
| Maintenance | DBCC SHRINKDATABASE | Shrinks the data and log files of a database |
| Maintenance | DBCC SHRINKFILE | Shrinks one data or log file; can empty a file with EMPTYFILE |
| Maintenance | DBCC DBREINDEX | Rebuilds indexes; feature will be removed in a future version, use ALTER INDEX |
| Maintenance | DBCC INDEXDEFRAG | Defragments indexes; feature will be removed in a future version, use ALTER INDEX |
| Informational | DBCC SQLPERF | Provides transaction log space usage statistics for all databases |
| Informational | DBCC OPENTRAN | Displays the oldest active transaction in a database's log |
| Informational | DBCC SHOW_STATISTICS | Displays the header, histogram, and density vector of a statistics object |
| Informational | DBCC INPUTBUFFER | Displays the last statement sent from a client to the instance |
| Cache | DBCC FREEPROCCACHE | Removes all plans, or one plan, or one resource pool's entries from the plan cache |
| Cache | DBCC FREESYSTEMCACHE | Releases unused cache entries from all caches or from one Resource Governor pool cache |
| Cache | DBCC DROPCLEANBUFFERS | Removes all clean buffers from the buffer pool |
Validation: DBCC CHECKDB
CHECKDB is the integrity check you schedule and do not skip. Because it already runs CHECKALLOC, CHECKTABLE, and CHECKCATALOG, plus checks of indexed views, FILESTREAM links, and Service Broker data, those commands do not need to be run separately. NO_INFOMSGS suppresses informational messages so that any output line is an error worth reading.
1DBCC CHECKDB (N'YourDatabase') WITH NO_INFOMSGS;
Two options control cost. PHYSICAL_ONLY limits the check to the physical structure of page and record headers and allocation consistency, and it is the form recommended for frequent use on production systems, with a full run still advised periodically. ESTIMATEONLY displays the estimated amount of tempdb space the check needs without running it. Run the estimate first on a large database. REPAIR_ALLOW_DATA_LOSS is an emergency last resort; restoring from the last known good backup is always recommended instead.
While CHECKDB runs, percent_complete in sys.dm_exec_requests reports its progress, as it does for CHECKTABLE, CHECKFILEGROUP, and the shrink commands:
1SELECT session_id, command, percent_complete
2FROM sys.dm_exec_requests
3WHERE percent_complete > 0;
Informational: DBCC SQLPERF and the log
DBCC SQLPERF (LOGSPACE) returns the current log size and percentage of log space used for each database, in one statement.
1DBCC SQLPERF (LOGSPACE);
From SQL Server 2012, use the sys.dm_db_log_space_usage DMV instead, which returns space usage information for the transaction log, including used_log_space_in_percent:
1SELECT * FROM sys.dm_db_log_space_usage;
Informational: DBCC OPENTRAN
An open transaction can prevent the log from truncating completely, because only the inactive part of the log can be truncated. OPENTRAN shows the oldest active transaction, including its SPID and start time. WITH TABLERESULTS returns the output in a form you can insert into a table for comparison between runs.
1DBCC OPENTRAN (N'YourDatabase');
Informational: DBCC INPUTBUFFER
INPUTBUFFER shows the last statement a session sent. Starting with SQL Server 2014 SP2, sys.dm_exec_input_buffer, which takes a session ID and request ID, returns the same information. Without VIEW SERVER STATE or sysadmin membership, DBCC INPUTBUFFER shows only your own session.
1SELECT * FROM sys.dm_exec_input_buffer(52, NULL);
Cache: removing one plan instead of all
DBCC FREEPROCCACHE with no argument evicts every plan, and incoming queries then compile new plans, which can cause a sudden, temporary decrease in query performance. The argument form removes a single plan by plan_handle. Find the handle in sys.dm_exec_cached_plans with sys.dm_exec_sql_text:
1SELECT plan_handle, st.text
2FROM sys.dm_exec_cached_plans
3CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
4WHERE st.text LIKE N'%YourQueryFragment%';
5
6DBCC FREEPROCCACHE (0x060006001ECA270EC0215D05000000000000000000000000);
Replace the sample handle with the value returned. ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE clears the plan cache for the current database, available from SQL Server 2016.
Cache: DBCC DROPCLEANBUFFERS
DBCC DROPCLEANBUFFERS lets you test queries with a cold buffer cache without shutting down and restarting the server. Run CHECKPOINT first so dirty pages are written to disk and the buffers become clean.
1CHECKPOINT;
2DBCC DROPCLEANBUFFERS;
Identity and statistics
DBCC CHECKIDENT (table_name, NORESEED) returns the current identity value and the current maximum value in the column without changing anything. RESEED, new_reseed_value sets the current identity value; setting it below the column's maximum on a non-empty table produces error 2627 on later inserts when a primary key or unique constraint exists, or duplicate values when one does not. DBCC SHOW_STATISTICS displays the header, histogram, and density vector the optimizer uses for cardinality estimates, and it requires SELECT permission on the table.
Key Benefits and Use Cases
- Corruption detection: the validation commands check page, allocation, and catalog structures and report errors.
- Log troubleshooting:
SQLPERFshows how full each log is, andOPENTRANpoints at the transaction that can block truncation. - Targeted plan eviction: one
plan_handlecan be removed instead of the whole cache, which limits the recompile cost. - Identity repair:
CHECKIDENTcompares the identity value with the column maximum and reseeds when they disagree. - Optimizer insight:
SHOW_STATISTICSexposes the header, histogram, and density vector behind a cardinality estimate.
Performance Considerations
- CHECKDB uses a snapshot: it creates an internal database snapshot, as a set of sparse files in the same folder as the database files, to get a transactionally consistent view without blocking. The snapshot files grow with the amount of data updated in the source database during the run, so keep free space on that volume.
- No snapshot means locks: if a snapshot cannot be created, or
TABLOCKis specified,CHECKDBacquires locks instead. Againsttempdbit never uses a snapshot and takes shared table locks. - Size tempdb: use
ESTIMATEONLYto see the tempdb space required before scheduling a check on a large database. - Shrinking fragments indexes: a shrink operation does not preserve the fragmentation state of indexes and can increase index fragmentation, which might reduce read I/O throughput for queries using large scans.
- Shrink is not maintenance: shrink operations are not regular maintenance, and
AUTO_SHRINKshould not be set to ON without a specific requirement. - Cache clears cost CPU: after a global
FREEPROCCACHE, every incoming query compiles a new plan. Severalsp_configurechanges, includingmax degree of parallelismandmax server memory, also clear the procedure cache when reconfigured. - DBREINDEX is offline: unlike
ALTER INDEXwithREORGANIZE, it holds a shared table lock for nonclustered indexes and an exclusive lock for a clustered index.
Practical Tips
- Schedule validation through SQL Agent: run
CHECKDBon a schedule, withPHYSICAL_ONLYfor frequent runs and a full check periodically. The open-source maintenance solution listed in References wraps integrity checks and index and statistics maintenance. - Look at what the error log says: when
CHECKDBfinishes, a message is written to the SQL Server error log stating success and run time, or that the command was terminated with a state value. - Use the narrowest form: evict one plan, shrink one file with
TRUNCATEONLY(which releases free space at the end of the file without moving pages), or reseed one table, rather than the database-wide forms. - Keep shrink out of maintenance plans: data and log files that grow from regular, recurring business operations do not need shrink operations, and a shrink is most effective after an operation that creates unused space, such as a truncate table or drop table.
- Migrate legacy index jobs: replace
DBCC DBREINDEXandDBCC INDEXDEFRAGwithALTER INDEX REBUILDorREORGANIZE, the supported replacement. - Test destructive commands off production:
DROPCLEANBUFFERSand a globalFREEPROCCACHEchange performance for every session, so try them on a test instance first.
Conclusion
DBCC is a mixed set of statements: validation you schedule, diagnostics you run during an incident, and storage and cache commands that carry a cost. Knowing which group a command belongs to, and its permissions and side effects, is the useful part. Use this page as the index and follow the deep dives below for the commands you run most.
Deep dives in this series:
- DBCC CHECKDB guide and repair options — corruption detection and the repair clauses.
- DBCC FREEPROCCACHE: clear the plan cache safely — targeted plan eviction.
- DBCC SHRINKDATABASE: when (and when not) to shrink — the fragmentation cost and the few legitimate cases.
- DBCC CHECKIDENT: check and reseed identity columns — closing identity gaps after archiving rows.
- DBCC DBREINDEX vs ALTER INDEX REBUILD — moving legacy index maintenance to the supported syntax.
References
- SQL Server Maintenance Solution — open-source scripts for integrity checks and index and statistics maintenance
- DBCC (Transact-SQL) — the four DBCC categories, the internal snapshot rules, and progress reporting
- DBCC CHECKDB (Transact-SQL) — options, repair levels, snapshot behavior, error log message, and permissions
- DBCC CHECKTABLE (Transact-SQL) — table and indexed view checks and permissions
- DBCC CHECKALLOC (Transact-SQL) — allocation structure checks and permissions
- DBCC CHECKCATALOG (Transact-SQL) — catalog consistency checks
- DBCC SQLPERF (Transact-SQL) — LOGSPACE output and the DMV replacement
- DBCC OPENTRAN (Transact-SQL) — oldest active transaction and TABLERESULTS
- DBCC INPUTBUFFER (Transact-SQL) — last statement sent by a session
- DBCC SHOW_STATISTICS (Transact-SQL) — header, histogram, density vector, and the SELECT permission
- DBCC FREEPROCCACHE (Transact-SQL) — evicting all plans, one plan, or a resource pool's plans
- DBCC FREESYSTEMCACHE (Transact-SQL) — releasing unused cache entries
- DBCC DROPCLEANBUFFERS (Transact-SQL) — cold buffer cache testing
- DBCC SHRINKDATABASE (Transact-SQL) — shrink behavior and best practices
- DBCC SHRINKFILE (Transact-SQL) — single-file shrink, TRUNCATEONLY, EMPTYFILE
- DBCC CHECKIDENT (Transact-SQL) — NORESEED and RESEED behavior
- DBCC DBREINDEX (Transact-SQL) — deprecated index rebuild and its locking
- DBCC INDEXDEFRAG (Transact-SQL) — deprecated index defragmentation
- sys.dm_exec_requests (Transact-SQL) — the percent_complete column and the commands it covers
- sys.dm_exec_input_buffer (Transact-SQL) — the DMV that replaces INPUTBUFFER
- sys.dm_db_log_space_usage (Transact-SQL) — space usage information for the transaction log
- ALTER DATABASE SCOPED CONFIGURATION (Transact-SQL) — CLEAR PROCEDURE_CACHE for the current database
Posts in this series
- Generate DBCC SHOWCONTIG Commands for All SQL Server Tables
- DBCC DBREINDEX: SQL Server Index Rebuild Script
- SQL Server DBCC DBREINDEX with Timing: Index Maintenance
- SQL Server Index Fragmentation: dm_db_index_physical_stats
- SQL Server DBCC CHECKDB Last Run Date Report
- SQL Server VLF Count Report: Virtual Log File Analysis
- SQL Server Duplicate and Overlapping Index Detection Script
- DBCC DBREINDEX vs ALTER INDEX REBUILD in SQL Server
- SQL Server DBCC SHRINKDATABASE: When and When Not to Shrink
- SQL Server DBCC CHECKDB Guide and Repair Options
- SQL Server DBCC Commands Guide
- How to Update Statistics in SQL Server
- Apply Row and Page Compression to Tables and Indexes
- Detect Suspect Database Pages with msdb.dbo.suspect_pages