Copy-and-run T-SQL for everyday SQL Server administration. Each block links to the full article when you need the explanation. To keep a copy, press Ctrl+P and choose Save as PDF: the page prints without menus. Read every statement before running it, and test changes on a non-production server first.
Know the server
SELECT @@VERSION;
SELECT SERVERPROPERTY('ProductVersion') AS version, SERVERPROPERTY('Edition') AS edition,
SERVERPROPERTY('ProductLevel') AS level, SERVERPROPERTY('MachineName') AS machine;
SELECT sqlserver_start_time FROM sys.dm_os_sys_info; -- last restart
SELECT name, state_desc, recovery_model_desc, compatibility_level FROM sys.databases;
-- Size of every database file
SELECT DB_NAME(database_id) AS db, name, type_desc, size * 8 / 1024 AS size_mb, physical_name
FROM sys.master_files ORDER BY size DESC;
-- Memory limit (an unlimited default can starve the operating system)
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'max server memory (MB)';
Backups and restores
Details: How to Back Up and Restore a SQL Server Database with T-SQL.
-- Full, differential and log backups
BACKUP DATABASE SalesDB TO DISK = N'D:\Backup\SalesDB_full.bak'
WITH COMPRESSION, CHECKSUM, STATS = 10;
BACKUP DATABASE SalesDB TO DISK = N'D:\Backup\SalesDB_diff.bak'
WITH DIFFERENTIAL, COMPRESSION, CHECKSUM;
BACKUP LOG SalesDB TO DISK = N'D:\Backup\SalesDB_log.trn' WITH COMPRESSION, CHECKSUM;
-- Look inside a backup before restoring
RESTORE HEADERONLY FROM DISK = N'D:\Backup\SalesDB_full.bak';
RESTORE FILELISTONLY FROM DISK = N'D:\Backup\SalesDB_full.bak';
RESTORE VERIFYONLY FROM DISK = N'D:\Backup\SalesDB_full.bak' WITH CHECKSUM;
-- Restore as a copy under a new name
RESTORE DATABASE SalesDB_Copy FROM DISK = N'D:\Backup\SalesDB_full.bak'
WITH MOVE 'SalesDB' TO N'D:\Data\SalesDB_Copy.mdf',
MOVE 'SalesDB_log' TO N'E:\Log\SalesDB_Copy.ldf',
RECOVERY, STATS = 10;
-- To add more backups afterwards use WITH NORECOVERY, then finish with: RESTORE DATABASE SalesDB_Copy WITH RECOVERY;
-- When was each database last backed up?
SELECT d.name,
MAX(CASE WHEN b.type = 'D' THEN b.backup_finish_date END) AS last_full,
MAX(CASE WHEN b.type = 'I' THEN b.backup_finish_date END) AS last_diff,
MAX(CASE WHEN b.type = 'L' THEN b.backup_finish_date END) AS last_log
FROM sys.databases d
LEFT JOIN msdb.dbo.backupset b ON b.database_name = d.name
GROUP BY d.name ORDER BY d.name;
Database settings
| Task | Statement |
|---|---|
| Recovery model | ALTER DATABASE SalesDB SET RECOVERY FULL; (or SIMPLE) |
| Compatibility level | ALTER DATABASE SalesDB SET COMPATIBILITY_LEVEL = 150; |
| Kick everyone out | ALTER DATABASE SalesDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE; |
| Let everyone back in | ALTER DATABASE SalesDB SET MULTI_USER; |
| Rename | ALTER DATABASE OldName MODIFY NAME = NewName; |
| Take offline / online | ALTER DATABASE SalesDB SET OFFLINE; / SET ONLINE; |
| Check for corruption | DBCC CHECKDB ('SalesDB') WITH NO_INFOMSGS; |
| Turn on Query Store | ALTER DATABASE SalesDB SET QUERY_STORE = ON; |
Who is connected and what is running
SELECT r.session_id, r.status, r.command, r.wait_type, r.wait_time, r.cpu_time,
r.total_elapsed_time / 1000 AS elapsed_s, DB_NAME(r.database_id) AS db,
s.login_name, s.host_name, t.text
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s ON s.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE s.is_user_process = 1 AND r.session_id <> @@SPID
ORDER BY r.total_elapsed_time DESC;
DBCC INPUTBUFFER (55); -- what a session ran last
KILL 55; -- end a session (it rolls back; this can take as long as the work it did)
Blocking
Details: How to Find and Fix Blocking in SQL Server.
SELECT r.session_id AS blocked, r.blocking_session_id AS blocker, r.wait_type,
r.wait_time / 1000 AS wait_s, DB_NAME(r.database_id) AS db, t.text AS blocked_sql
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE r.blocking_session_id <> 0;
-- Who is at the head of the chain? Look for a blocker that is not itself blocked, and check:
SELECT session_id, login_name, host_name, program_name, status, open_transaction_count
FROM sys.dm_exec_sessions WHERE session_id = 55; -- use the blocker's ID
A blocker with status = sleeping and open_transaction_count > 0 is an application that forgot to commit.
Slow queries and waits
Details: How to Find and Fix Slow Queries in SQL Server.
-- The 10 statements that used the most total time since their plans were cached
SELECT TOP 10 qs.execution_count,
qs.total_elapsed_time / 1000 AS total_ms,
qs.total_elapsed_time / qs.execution_count / 1000 AS avg_ms,
qs.total_logical_reads / qs.execution_count AS avg_reads,
SUBSTRING(st.text, (qs.statement_start_offset / 2) + 1,
((CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2) + 1) AS statement_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
ORDER BY qs.total_elapsed_time DESC;
-- Measure one query
SET STATISTICS IO, TIME ON;
-- What the server waits for most (idle waits are filtered out)
SELECT TOP 10 wait_type, wait_time_ms / 1000 AS wait_s, waiting_tasks_count
FROM sys.dm_os_wait_stats
WHERE wait_type NOT LIKE '%SLEEP%' AND wait_type NOT IN
('XE_TIMER_EVENT','XE_DISPATCHER_WAIT','LOGMGR_QUEUE','CHECKPOINT_QUEUE','WAITFOR',
'DIRTY_PAGE_POLL','REQUEST_FOR_DEADLOCK_SEARCH','BROKER_TO_FLUSH','BROKER_TASK_STOP',
'SQLTRACE_BUFFER_FLUSH','FT_IFTS_SCHEDULER_IDLE_WAIT','DISPATCHER_QUEUE_SEMAPHORE')
ORDER BY wait_time_ms DESC;
| Top wait | Usually means |
|---|---|
PAGEIOLATCH_* |
Reading data from disk: slow storage, missing index, or too little memory |
LCK_M_* |
Blocking between sessions |
CXPACKET, CXCONSUMER |
Parallel queries (check MAXDOP and cost threshold before panicking) |
WRITELOG |
Slow transaction log disk |
SOS_SCHEDULER_YIELD |
CPU pressure |
ASYNC_NETWORK_IO |
The client is slow to read results |
Indexes and statistics
Details: SQL Server Indexes Explained.
-- Fragmentation (run inside the database; ignore tiny indexes)
SELECT OBJECT_NAME(ips.object_id) AS table_name, i.name AS index_name,
ips.avg_fragmentation_in_percent AS frag_pct, ips.page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') ips
JOIN sys.indexes i ON i.object_id = ips.object_id AND i.index_id = ips.index_id
WHERE ips.page_count > 1000 AND ips.avg_fragmentation_in_percent > 10
ORDER BY ips.avg_fragmentation_in_percent DESC;
ALTER INDEX IX_Orders_Customer ON dbo.Orders REORGANIZE; -- 10-30% fragmented
ALTER INDEX IX_Orders_Customer ON dbo.Orders REBUILD; -- over 30%
UPDATE STATISTICS dbo.Orders WITH FULLSCAN;
-- Suggestions from the optimizer (treat as hints, not orders)
SELECT TOP 10 mid.statement, mid.equality_columns, mid.inequality_columns, mid.included_columns,
migs.user_seeks, migs.avg_user_impact
FROM sys.dm_db_missing_index_group_stats migs
JOIN sys.dm_db_missing_index_groups mig ON migs.group_handle = mig.index_group_handle
JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
ORDER BY migs.user_seeks * migs.avg_user_impact DESC;
-- Indexes that are only costing writes (counters reset at restart)
SELECT OBJECT_NAME(s.object_id) AS table_name, i.name, s.user_seeks, s.user_scans, s.user_lookups, s.user_updates
FROM sys.dm_db_index_usage_stats s
JOIN sys.indexes i ON i.object_id = s.object_id AND i.index_id = s.index_id
WHERE s.database_id = DB_ID() AND i.is_primary_key = 0 AND s.user_seeks + s.user_scans + s.user_lookups = 0
ORDER BY s.user_updates DESC;
Disk space and the transaction log
DBCC SQLPERF (LOGSPACE); -- log size and % used for every database
SELECT name, recovery_model_desc, log_reuse_wait_desc FROM sys.databases; -- why the log cannot be reused
-- Largest tables in the current database
SELECT TOP 20 OBJECT_SCHEMA_NAME(object_id) + '.' + OBJECT_NAME(object_id) AS table_name,
SUM(CASE WHEN index_id IN (0, 1) THEN row_count END) AS row_count,
SUM(used_page_count) * 8 / 1024 AS used_mb
FROM sys.dm_db_partition_stats
WHERE OBJECTPROPERTY(object_id, 'IsUserTable') = 1
GROUP BY object_id ORDER BY used_mb DESC;
EXEC sp_spaceused; -- database totals
EXEC sp_spaceused 'dbo.Orders'; -- one table
log_reuse_wait_desc |
What to do |
|---|---|
LOG_BACKUP |
Take a log backup (and schedule them) in the FULL recovery model |
ACTIVE_TRANSACTION |
Find the long open transaction: DBCC OPENTRAN |
REPLICATION, AVAILABILITY_REPLICA |
The replica or log reader is behind |
NOTHING |
The log is fine |
Avoid shrinking data files as routine maintenance. It fragments indexes and the file grows again. Fix the cause: log backups, a long transaction, or genuinely too little disk.
Logins, users and permissions
Details: SQL Server Logins, Users and Permissions.
CREATE LOGIN appuser WITH PASSWORD = 'Use-A-Long-Unique-Password-1!', CHECK_POLICY = ON;
USE SalesDB;
CREATE USER appuser FOR LOGIN appuser;
ALTER ROLE db_datareader ADD MEMBER appuser;
GRANT EXECUTE ON SCHEMA::dbo TO appuser;
DENY DELETE ON dbo.Orders TO appuser;
ALTER LOGIN appuser DISABLE; -- ENABLE to undo
ALTER LOGIN appuser WITH PASSWORD = 'New-Password-2!' UNLOCK;
-- Who is sysadmin?
SELECT m.name FROM sys.server_role_members rm
JOIN sys.server_principals r ON r.principal_id = rm.role_principal_id
JOIN sys.server_principals m ON m.principal_id = rm.member_principal_id
WHERE r.name = 'sysadmin';
-- What can this user do?
EXECUTE AS USER = 'appuser';
SELECT * FROM fn_my_permissions('dbo.Orders', 'OBJECT');
REVERT;
-- Orphaned user after a restore (the user exists but its login does not match)
ALTER USER appuser WITH LOGIN = appuser;
SQL Server Agent jobs
Details: SQL Server Agent Jobs: Schedule Backups and Get Alerts on Failure.
EXEC msdb.dbo.sp_start_job @job_name = N'Nightly full backup';
EXEC msdb.dbo.sp_stop_job @job_name = N'Nightly full backup';
EXEC msdb.dbo.sp_update_job @job_name = N'Nightly full backup', @enabled = 0; -- disable
-- Last 20 job outcomes (run_status 1 = succeeded, 0 = failed)
SELECT TOP 20 j.name, h.run_date, h.run_time, h.run_status, h.message
FROM msdb.dbo.sysjobs j
JOIN msdb.dbo.sysjobhistory h ON h.job_id = j.job_id AND h.step_id = 0
ORDER BY h.instance_id DESC;
Deadlocks and the error log
Details: SQL Server Deadlocks: How to Capture, Read and Fix Them.
EXEC sp_readerrorlog 0, 1, N'deadlock'; -- search the current error log
EXEC sp_readerrorlog 0, 1, N'Login failed';
EXEC sp_readerrorlog 1, 1, N'error'; -- the previous log file
Deadlock history is recorded by the built-in system_health Extended Events session: see the article above for the query that reads it.
T-SQL snippets you need all the time
SELECT TOP (10) * FROM dbo.Orders ORDER BY OrderDate DESC;
SELECT * FROM dbo.Orders ORDER BY OrderID OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY; -- paging
SELECT COALESCE(Phone, Mobile, 'n/a') FROM dbo.Customers;
SELECT DATEADD(DAY, -30, SYSDATETIME()), DATEDIFF(DAY, '2026-01-01', SYSDATETIME()), EOMONTH(SYSDATETIME());
SELECT STRING_AGG(Name, ', ') WITHIN GROUP (ORDER BY Name) FROM dbo.Customers; -- SQL Server 2017+
-- Remove duplicates, keep the first
WITH d AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CustomerID) AS rn FROM dbo.Customers)
DELETE FROM d WHERE rn > 1;
-- A safe change: try it, look at the result, then decide
BEGIN TRAN;
UPDATE dbo.Orders SET Status = 'Closed' WHERE OrderDate < '2025-01-01';
SELECT @@ROWCOUNT AS rows_changed;
-- ROLLBACK; -- undo
-- COMMIT; -- keep
Always write the WHERE clause first, and run it as a SELECT before you turn it into an UPDATE or DELETE.
sqlcmd from the command line
sqlcmd -S localhost -d master -E -Q "SELECT @@VERSION" # Windows authentication
sqlcmd -S server,1433 -U appuser -P "password" -Q "SELECT 1" # SQL login
sqlcmd -S localhost -E -i script.sql -o result.txt # run a file, save the output
sqlcmd -S localhost -E -C -Q "SELECT 1" # -C trusts a self-signed certificate
Five rules
- A backup you have never restored is only a hope. Test restores on another server.
- Use the FULL recovery model only if you take log backups, otherwise the log grows until the disk is full.
- Do not fix a slow query by throwing indexes at it: read the plan and measure with
SET STATISTICS IO, TIME ONbefore and after. - Use the least permission that works. Applications should not run as
saor assysadmin. - Keep SQL Server patched, and keep
CHECKDBand backups on a schedule with alerts when a job fails.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
