SQL DBA Performance Tunning Book 1740934042
SQL DBA Performance Tunning Book 1740934042
Connect to the instance of SQL Server and run the following query:
sql
SELECT @@VERSION
Connect to the instance of SQL Server and run the following query in SSMS:
sql
This will return the product version, product level, and edition of SQL Server.
Look at the first few lines of the Errorlog file for that instance. By default, the error log is
located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
This script helps you quickly determine if your SQL Server is up to date and whether you’re
utilizing an enterprise or standard edition.
Knowing how long your SQL Server instance has been running helps diagnose unexpected
restarts and server stability issues.
How?
SELECT sqlserver_start_time FROM sys.dm_os_sys_info;
If your server restarts frequently, you may need to investigate crash logs or resource
constraints.
You can use the sys.dm_os_sys_info DMV to get the SQL Server instance uptime. Run
the following query:
sql
Another way to check uptime is by querying the sys.sysprocesses DMV. Run the
following query:
sql
The SQL Server error log contains information about the server startup time. By default,
the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\
LOG\ERRORLOG.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Open the error log and look for the startup entry to determine the uptime.
Tracking database size trends helps in capacity planning and storage management.
How?
SELECT DB_NAME(database_id) AS DatabaseName,
size * 8 / 1024 AS SizeMB
FROM sys.master_files;
This script provides a breakdown of database sizes in megabytes.
Running out of disk space can cause SQL Server to halt, leading to critical downtime.
How?
EXEC xp_fixeddrives;
This built-in procedure provides an overview of available disk space across all drives.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle);
This script identifies slow queries so you can optimize them.
SELECT
r.session_id,
r.start_time,
r.status,
r.command,
r.cpu_time,
r.total_elapsed_time,
r.reads,
r.writes,
r.logical_reads,
r.text_size,
r.plan_handle,
s.text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
WHERE r.status = 'running'
ORDER BY r.total_elapsed_time DESC;
Identifying and addressing long-running queries in SQL Server is crucial for optimizing
performance. Here are a few methods you can use:
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
SELECT
r.session_id,
r.start_time,
r.status,
r.command,
r.cpu_time,
r.total_elapsed_time,
r.reads,
r.writes,
r.logical_reads,
r.text_size,
r.plan_handle,
s.text
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
WHERE r.status = 'running'
ORDER BY r.total_elapsed_time DESC;
sql
sql
SELECT
PERFORMANCE TUNNING
MAME TECHNOLOGIES
qsqt.query_sql_text,
qsrs.avg_duration,
qsrs.execution_count
FROM sys.query_store_runtime_stats qsrs
JOIN sys.query_store_plan qsp ON qsrs.plan_id = qsp.plan_id
JOIN sys.query_store_query qsq ON qsp.query_id = qsq.query_id
JOIN sys.query_store_query_text qsqt ON qsq.query_text_id =
qsqt.query_text_id
ORDER BY qsrs.avg_duration DESC;
Knowing how many users are connected helps identify performance bottlenecks and
unauthorized access.
How?
SELECT login_name, COUNT(session_id) AS SessionCount
FROM sys.dm_exec_sessions
GROUP BY login_name;
ou can check active user sessions in SQL Server using various methods. Here are some common
approaches:
sql
SELECT
s.session_id,
s.login_name,
s.host_name,
s.status,
c.connect_time,
c.client_net_address
PERFORMANCE TUNNING
MAME TECHNOLOGIES
FROM sys.dm_exec_sessions s
JOIN sys.dm_exec_connections c ON s.session_id = c.session_id
WHERE s.is_user_process = 1;
sql
EXEC sp_who;
sql
EXEC sp_who2;
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
How?
SELECT blocking_session_id AS Blocker, session_id AS BlockedProcess
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0;
This helps in diagnosing and resolving blocking issues quickly.
Finding and resolving blocked processes in SQL Server is important for maintaining optimal
performance. Here are several methods to identify blocked processes:
sql
SELECT
r.session_id AS BlockingSessionID,
r.blocking_session_id AS BlockedSessionID,
r.wait_type AS WaitType,
r.wait_time AS WaitTime,
r.wait_resource AS WaitResource,
s.login_name AS LoginName,
s.host_name AS HostName,
s.program_name AS ProgramName
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
WHERE r.blocking_session_id <> 0;
sql
EXEC sp_who2;
o Look for rows where the BlkBy column is not empty, indicating that the process
is blocked by another process.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
4. Using SQL Server Profiler:
o SQL Server Profiler allows you to trace and monitor blocking events.
o Open SQL Server Profiler and create a new trace.
o Choose the appropriate events (e.g., Lock:Deadlock, Lock:Deadlock Chain,
Lock:Timeout) to capture details about blocking and deadlock events.
5. Using Extended Events:
o Extended Events offer a lightweight way to capture and monitor blocking events.
o You can create an Extended Events session to capture blocking information.
Here's an example script to create a session that captures blocking events:
sql
High CPU usage can slow down your database and impact application performance.
How?
SELECT TOP 10 text AS QueryText,
total_worker_time / 1000 AS CPUTimeMs
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle)
ORDER BY total_worker_time DESC;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Identifying CPU-intensive queries in SQL Server is crucial for optimizing performance. Here are
several methods you can use:
sql
SELECT
TOP 10
qs.sql_handle,
qs.execution_count,
qs.total_worker_time AS TotalCPU,
qs.total_worker_time / qs.execution_count AS AvgCPU,
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
query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY TotalCPU DESC;
o This query will return the top 10 CPU-intensive queries based on total CPU time.
2. Using SQL Server Profiler:
o SQL Server Profiler allows you to trace and monitor the execution of SQL
queries.
o Open SQL Server Profiler and create a new trace.
o Choose the appropriate events (e.g., SQL:BatchCompleted and RPC:Completed)
and set filters to capture queries with high CPU usage.
3. Using Extended Events:
o Extended Events offer a lightweight way to capture and monitor query
performance.
o You can create an Extended Events session to capture CPU-intensive queries.
Here's an example script to create such a session:
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
GO
ALTER EVENT SESSION CPUIntensiveQueries ON SERVER STATE = START;
sql
SELECT
qsqt.query_sql_text,
qsrs.avg_cpu_time,
qsrs.execution_count
FROM sys.query_store_runtime_stats qsrs
JOIN sys.query_store_plan qsp ON qsrs.plan_id = qsp.plan_id
JOIN sys.query_store_query qsq ON qsp.query_id = qsq.query_id
JOIN sys.query_store_query_text qsqt ON qsq.query_text_id =
qsqt.query_text_id
ORDER BY qsrs.avg_cpu_time DESC;
SQL Server memory pressure can slow down query execution and degrade performance.
How?
SELECT total_physical_memory_kb / 1024 AS TotalMemoryMB,
available_physical_memory_kb / 1024 AS AvailableMemoryMB
FROM sys.dm_os_sys_memory;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Deadlocks cause processes to be terminated and degrade system performance.
How?
EXEC sp_whoisactive;
This helps identify deadlocks in real time.
Detecting and resolving deadlocks in SQL Server is critical for maintaining the smooth operation
of your database. Here are several methods you can use:
sql
SELECT
r.session_id AS DeadlockSessionID,
r.blocking_session_id AS BlockingSessionID,
r.wait_type AS WaitType,
r.wait_time AS WaitTime,
r.wait_resource AS WaitResource,
s.login_name AS LoginName,
s.host_name AS HostName,
s.program_name AS ProgramName
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id
WHERE r.blocking_session_id <> 0 AND r.status = 'suspended';
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
CREATE EVENT SESSION DeadlockSession
ON SERVER
ADD EVENT sqlserver.xml_deadlock_report
ADD TARGET package0.event_file(SET filename='C:\Temp\
DeadlockSession.xel')
GO
ALTER EVENT SESSION DeadlockSession ON SERVER STATE = START;
sql
Enable Trace Flag 1222: This flag provides a more detailed deadlock
graph.
sql
You can disable these trace flags using the following commands:
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
growth * 8 / 1024 AS GrowthMB
FROM sys.master_files;
Monitoring database growth trends in SQL Server is important for capacity planning and
ensuring optimal performance. Here are a few methods you can use:
sql
o Schedule this query to run at regular intervals using SQL Server Agent to collect
data over time. You can then analyze the data to identify growth trends.
3. Using the sys.dm_db_file_space_usage DMV:
o You can use the sys.dm_db_file_space_usage DMV to monitor space usage
trends. Run the following query:
sql
SELECT
database_id,
type_desc AS FileType,
total_page_count * 8 / 1024 AS TotalSpaceMB,
used_page_count * 8 / 1024 AS UsedSpaceMB,
(total_page_count - used_page_count) * 8 / 1024 AS FreeSpaceMB
FROM sys.dm_db_file_space_usage;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
4. Using SQL Server Performance Monitor (PerfMon):
o You can use Windows Performance Monitor (PerfMon) to track disk space usage
and growth trends. Add counters for LogicalDisk or PhysicalDisk to monitor disk
usage over time.
5. Using SQL Server Data Collector:
o SQL Server Data Collector is a feature that allows you to collect and store
performance data, including database size and growth trends.
o Set up the Data Collector and configure it to collect disk usage and growth trend
data. You can then analyze the collected data to identify growth patterns.
6. Using PowerShell:
o You can use PowerShell scripts to monitor database growth trends. Here’s an
example script:
powershell
Identifying unused databases in SQL Server can help you manage resources more efficiently.
Here are a few methods you can use:
sql
SELECT
d.name AS DatabaseName,
MAX(ius.last_user_seek) AS LastUserSeek,
MAX(ius.last_user_scan) AS LastUserScan,
MAX(ius.last_user_lookup) AS LastUserLookup,
MAX(ius.last_user_update) AS LastUserUpdate
FROM sys.databases d
PERFORMANCE TUNNING
MAME TECHNOLOGIES
LEFT JOIN sys.dm_db_index_usage_stats ius ON d.database_id =
ius.database_id
WHERE d.database_id > 4 -- Exclude system databases
GROUP BY d.name
ORDER BY MAX(ius.last_user_seek) DESC;
sql
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
How?
SELECT OBJECT_NAME(ius.object_id) AS TableName,
i.name AS IndexName,
ius.user_seeks, ius.user_scans, ius.user_lookups
FROM sys.dm_db_index_usage_stats ius
JOIN sys.indexes i ON ius.object_id = i.object_id AND ius.index_id = i.index_id;
Analyzing index usage in SQL Server is important for understanding how effectively indexes are
being utilized and for identifying opportunities to optimize query performance. Here are a few
methods you can use:
sql
SELECT
DB_NAME(ius.database_id) AS DatabaseName,
OBJECT_NAME(ius.object_id, ius.database_id) AS TableName,
i.name AS IndexName,
ius.user_seeks AS UserSeeks,
ius.user_scans AS UserScans,
ius.user_lookups AS UserLookups,
ius.user_updates AS UserUpdates
FROM sys.dm_db_index_usage_stats ius
JOIN sys.indexes i ON ius.object_id = i.object_id AND ius.index_id
= i.index_id
WHERE ius.database_id = DB_ID('YourDatabaseName')
ORDER BY ius.user_seeks DESC;
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
EXEC sp_helpindex 'YourTableName';
sql
SELECT
qsqt.query_sql_text,
qsrs.avg_execution_count,
qsrs.avg_logical_io_reads,
qsrs.avg_logical_io_writes
FROM sys.query_store_runtime_stats qsrs
JOIN sys.query_store_plan qsp ON qsrs.plan_id = qsp.plan_id
JOIN sys.query_store_query qsq ON qsp.query_id = qsq.query_id
JOIN sys.query_store_query_text qsqt ON qsq.query_text_id =
qsqt.query_text_id
ORDER BY qsrs.avg_logical_io_reads DESC;
Identifying missing indexes in SQL Server can significantly improve query performance. Here
are a few methods to find missing indexes:
sql
SELECT
database_id,
OBJECT_NAME(object_id, database_id) AS TableName,
equality_columns,
inequality_columns,
included_columns,
statement
FROM sys.dm_db_missing_index_details;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o This query will return information about missing indexes, including the table
name, equality columns, inequality columns, and included columns.
2. Using SQL Server Management Studio (SSMS):
o Open SSMS and connect to the SQL Server instance.
o Navigate to the database you want to analyze, right-click the database, and select
Reports > Standard Reports > Missing Indexes.
o This report provides detailed information about missing indexes and their
potential impact on query performance.
3. Using System Stored Procedures:
o You can use the following script to identify missing indexes and generate the
CREATE INDEX statements:
sql
SELECT
dm_mid.database_id AS DatabaseID,
dm_migs.avg_user_impact * (dm_migs.user_seeks +
dm_migs.user_scans) AS Avg_Estimated_Impact,
dm_migs.last_user_seek AS Last_User_Seek,
OBJECT_NAME(dm_mid.OBJECT_ID, dm_mid.database_id) AS
TableName,
'CREATE INDEX [IX_' + OBJECT_NAME(dm_mid.OBJECT_ID,
dm_mid.database_id) + '_' +
REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.equality_columns, ''), ', ',
'_'), '[', ''), ']', '') +
CASE WHEN dm_mid.equality_columns IS NOT NULL AND
dm_mid.inequality_columns IS NOT NULL THEN '_' ELSE '' END +
REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.inequality_columns, ''),
', ', '_'), '[', ''), ']', '') + ']' +
' ON ' + dm_mid.statement + ' (' +
ISNULL(dm_mid.equality_columns, '') +
CASE WHEN dm_mid.equality_columns IS NOT NULL AND
dm_mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END +
ISNULL(dm_mid.inequality_columns, '') + ')' +
ISNULL(' INCLUDE (' + dm_mid.included_columns + ')', '') AS
Create_Statement
FROM sys.dm_db_missing_index_groups dm_mig
INNER JOIN sys.dm_db_missing_index_group_stats dm_migs ON
dm_migs.group_handle = dm_mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details dm_mid ON
dm_mig.index_handle = dm_mid.index_handle
WHERE dm_mid.database_ID = DB_ID()
ORDER BY Avg_Estimated_Impact DESC;
Unused indexes in SQL Server
Identifying unused indexes in SQL Server can help you clean up your database and improve
performance. Here are a few methods to find unused indexes:
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o You can use the sys.dm_db_index_usage_stats DMV to identify unused
indexes. Run the following query:
sql
SELECT
OBJECT_NAME(i.object_id) AS TableName,
i.name AS IndexName,
i.index_id,
i.type_desc AS IndexType,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
MAX(ius.last_user_seek) AS LastUserSeek,
MAX(ius.last_user_scan) AS LastUserScan,
MAX(ius.last_user_lookup) AS LastUserLookup,
MAX(ius.last_user_update) AS LastUserUpdate
FROM sys.indexes i
INNER JOIN sys.partitions p ON i.object_id = p.object_id AND
i.index_id = p.index_id
INNER JOIN sys.allocation_units a ON p.partition_id =
a.container_id
LEFT JOIN sys.dm_db_index_usage_stats ius ON i.object_id =
ius.object_id AND i.index_id = ius.index_id
WHERE i.is_primary_key = 0 AND i.is_unique = 0 AND i.type_desc =
'NONCLUSTERED'
GROUP BY i.object_id, i.index_id, i.name, i.type_desc, p.rows
HAVING MAX(ius.user_seeks) IS NULL AND MAX(ius.user_scans) IS NULL
AND MAX(ius.user_lookups) IS NULL
ORDER BY TotalSpaceKB DESC;
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o Run the following query to get information on index usage from Query Store:
sql
SELECT
qsqt.query_sql_text,
qsrs.avg_execution_count,
qsrs.avg_logical_io_reads,
qsrs.avg_logical_io_writes
FROM sys.query_store_runtime_stats qsrs
JOIN sys.query_store_plan qsp ON qsrs.plan_id = qsp.plan_id
JOIN sys.query_store_query qsq ON qsp.query_id = qsq.query_id
JOIN sys.query_store_query_text qsqt ON qsq.query_text_id =
qsqt.query_text_id
ORDER BY qsrs.avg_logical_io_reads DESC;
Monitoring TempDB usage in SQL Server is crucial for maintaining optimal performance and
preventing issues related to space consumption. Here are a few methods you can use:
sql
SELECT
(SUM(unallocated_extent_page_count) * 1.0 / 128) AS [Free
space (MB)],
(SUM(version_store_reserved_page_count) * 1.0 / 128) AS [Used
Space by Version Store (MB)],
(SUM(internal_object_reserved_page_count) * 1.0 / 128) AS
[Used Space by Internal Objects (MB)],
(SUM(user_object_reserved_page_count) * 1.0 / 128) AS [Used
Space by User Objects (MB)]
FROM tempdb.sys.dm_db_file_space_usage;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o Open SSMS and connect to the SQL Server instance.
o Navigate to Reports > Standard Reports > Disk Usage.
o This report provides information on the space usage of TempDB, including data
file size, log file size, and space used by log files.
3. Using System Stored Procedures:
o You can use the sp_spaceused stored procedure to get information about space
usage in TempDB. Run the following command:
sql
USE tempdb;
GO
EXEC sp_spaceused;
Temp tables in SQL Server are special types of tables that are used to store temporary data. They
are similar to regular tables, but they are created in the TempDB database and have a limited
lifespan. Temp tables can be useful for storing intermediate results, staging data, and performing
complex calculations. Here are the types of temp tables available in SQL Server:
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
SELECT * FROM #TempTable;
sql
3. Table Variables:
o Table variables are declared using the DECLARE statement and are prefixed with an
@ symbol (e.g., @TempTableVar).
o They have a limited scope and are only visible within the batch, stored procedure,
or function in which they are declared.
o Example:
sql
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
);
To check open transactions in SQL Server, you can use several methods. Here are some common
approaches:
sql
SELECT
transaction_id,
name,
transaction_state,
transaction_begin_time,
database_id
FROM sys.dm_tran_active_transactions;
sql
USE YourDatabaseName;
GO
DBCC OPENTRAN;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
3. Using SQL Server Management Studio (SSMS):
o Open SSMS and connect to the SQL Server instance.
o Navigate to the database you want to check.
o Right-click the database, select Reports > Standard Reports > All
Transactions.
o This report provides detailed information about open transactions in the database.
4. Using the sys.dm_tran_session_transactions and
sys.dm_tran_database_transactions DMVs:
o You can join these DMVs to get detailed information about open transactions,
including the session and database context. Run the following query:
sql
SELECT
st.transaction_id,
at.name,
at.transaction_begin_time,
st.session_id,
dt.database_id,
DB_NAME(dt.database_id) AS DatabaseName
FROM sys.dm_tran_session_transactions st
JOIN sys.dm_tran_active_transactions at ON st.transaction_id =
at.transaction_id
JOIN sys.dm_tran_database_transactions dt ON dt.transaction_id =
st.t
Analyzing wait statistics in SQL Server is essential for identifying performance bottlenecks and
improving query performance. Here are a few methods to analyze wait statistics:
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
SELECT
wait_type,
wait_time_ms,
max_wait_time_ms,
signal_wait_time_ms,
wait_time_ms - signal_wait_time_ms AS resource_wait_time_ms
FROM sys.dm_os_wait_stats
ORDER BY wait_time_ms DESC;
sql
SELECT
qsqt.query_sql_text,
qsrs.avg_wait_time_ms,
qsrs.execution_count
FROM sys.query_store_runtime_stats qsrs
JOIN sys.query_store_plan qsp ON qsrs.plan_id = qsp.plan_id
JOIN sys.query_store_query qsq ON qsp.query_id = qsq.query_id
JOIN sys.query_store_query_text qsqt ON qsq.query_text_id =
qsqt.query_text_id
ORDER BY qsrs.avg_wait_time_ms DESC;
Frequent wait types in SQL Server can vary depending on the workload and server
configuration, but here are some commonly encountered wait types:
PERFORMANCE TUNNING
MAME TECHNOLOGIES
1. CXPACKET:
o Occurs when a parallel query is running and there are discrepancies in the
processing speed of parallel threads.
o This wait type is common in environments with a high degree of parallelism.
2. PAGEIOLATCH_ and PAGELATCH_**:
o PAGEIOLATCH_SH, PAGEIOLATCH_UP, and PAGEIOLATCH_EX are wait
types that occur when waiting for a page to be read from disk into the buffer pool.
o PAGELATCH_SH, PAGELATCH_UP, and PAGELATCH_EX occur when
there is contention on in-memory pages.
3. LCK_M_*:
o LCK_M_X, LCK_M_S, and other LCK_M_* wait types indicate that a session is
waiting for a lock to be released by another session.
o These waits are common in scenarios with high concurrency and locking
contention.
4. ASYNC_NETWORK_IO:
o Occurs when SQL Server is waiting for the client application to process the
results of a query and acknowledge that it can receive more data.
o This wait type is common in scenarios with slow client applications or network
latency.
5. WRITELOG:
o Occurs when SQL Server is waiting for a transaction log flush to disk.
o This wait type is common in scenarios with high transactional activity and disk
latency.
6. SOS_SCHEDULER_YIELD:
o Occurs when a worker thread voluntarily yields the CPU after reaching its
quantum limit.
o This wait type is common in CPU-bound scenarios.
7. RESOURCE_SEMAPHORE:
o Occurs when a query is waiting for memory grants.
o This wait type is common in scenarios with memory-intensive queries and
insufficient available memory.
8. HADR_SYNC_COMMIT:
o Occurs in Always On Availability Groups when a transaction is waiting for
confirmation that it has been committed on the secondary replica.
o This wait type is common in environments with synchronous replication.
9. BACKUPIO:
o Occurs when waiting for I/O during a backup operation.
o This wait type is common in environments with frequent or large backup
operations.
10. NETWORK_IO:
o Occurs when waiting for network I/O.
o This wait type is common in scenarios with high network traffic or latency.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Resolving CXPACKET waits in SQL Server involves addressing issues related to parallelism.
Here are some strategies to help mitigate CXPACKET waits:
sql
o You can also set the MAXDOP value at the query level using the OPTION (MAXDOP
n) hint.
2. Optimize Query Performance:
o Ensure that your queries are well-optimized and use appropriate indexes. Poorly
optimized queries can lead to excessive parallelism and CXPACKET waits.
o Use the SQL Server Query Store or SQL Server Profiler to identify and optimize
poorly performing queries.
3. Update Statistics:
o Outdated statistics can lead to suboptimal query plans and excessive parallelism.
Regularly update statistics to ensure the query optimizer has accurate information.
o You can update statistics using the following command:
sql
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
5. Analyze and Balance Workload:
o Analyze your workload to identify queries that benefit from parallelism and those
that do not. Balance the workload to ensure that parallelism is used effectively.
o Use SQL Server Dynamic Management Views (DMVs) to monitor and analyze
query performance and parallelism.
Resolving PAGEIOLATCH_ and PAGELATCH_ waits in SQL Server involves addressing issues
related to I/O and page contention. Here are some strategies to help mitigate these waits:
PAGEIOLATCH_ waits occur when SQL Server is waiting for a page to be read from or written to
disk. Here are some steps to address these waits:
PAGELATCH_ waits occur when SQL Server is waiting for a latch on a data or index page in
memory. Here are some steps to address these waits:
1. Optimize Indexes:
o Ensure that your indexes are well-designed and appropriate for your workload.
o Avoid using sequential keys (e.g., identity columns) for clustered indexes, as they
can cause contention on the last page.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
2. Reduce Contention:
o Distribute inserts and updates across multiple pages to reduce contention.
o Use partitioning to spread the load across multiple partitions and reduce latch
contention.
3. Monitor and Tune Queries:
o Identify and optimize queries that cause excessive latch contention.
o Use SQL Server Profiler or Extended Events to monitor query performance and
identify bottlenecks.
4. Increase Concurrency:
o Increase the number of CPUs available to SQL Server to improve concurrency.
o Configure the MAXDOP setting to balance parallelism and reduce latch contention
By default, SQL Server error logs are located in the LOG folder within the SQL Server
installation directory (e.g., C:\Program Files\Microsoft SQL Server\MSSQL.n\
MSSQL\LOG\ERRORLOG).
Regular backups are essential for disaster recovery and data protection.
How?
SELECT database_name, backup_finish_date, type FROM msdb.dbo.backupset ORDER BY
backup_finish_date DESC;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Monitoring database backups in SQL Server is essential to ensure data integrity and recovery in
case of failures. Here are a few methods to monitor database backups:
sql
SELECT
d.name AS DatabaseName,
b.backup_start_date,
b.backup_finish_date,
b.backup_size / 1024 / 1024 AS BackupSizeMB,
b.type AS BackupType,
CASE
WHEN b.type = 'D' THEN 'Full'
WHEN b.type = 'I' THEN 'Differential'
WHEN b.type = 'L' THEN 'Log'
END AS BackupTypeDescription
FROM msdb.dbo.backupset b
JOIN msdb.dbo.sysdatabases d ON b.database_name = d.name
ORDER BY b.backup_finish_date DESC;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Default backup tables in SQL Server
In SQL Server, the msdb database maintains a set of tables that store information about backup
and restore operations. Here are some of the key tables related to backups:
1. backupset:
o Stores information about each backup set, including the type of backup, start and
finish times, and backup size.
o Example columns: backup_set_id, database_name, backup_start_date,
backup_finish_date, type, backup_size, etc.
2. backupmediafamily:
o Stores information about the media (e.g., files, tapes) used for each backup,
including the logical and physical device names.
o Example columns: media_set_id, media_family_id, logical_device_name,
physical_device_name, etc.
3. backupmediaset:
o Stores information about the media set used for each backup, including the media
set ID and media family count.
o Example columns: media_set_id, backup_start_date, media_family_count,
etc.
4. backupfile:
o Stores information about each file included in the backup, including the logical
and physical names of the files.
o Example columns: backup_set_id, file_id, logical_name, physical_name,
etc.
5. backupfilegroup:
o Stores information about each filegroup included in the backup.
o Example columns: backup_set_id, filegroup_id, filegroup_name, etc.
6. restorehistory:
o Stores information about each restore operation, including the restore sequence
number, restore date, and destination database name.
o Example columns: restore_history_id, restore_date,
destination_database_name, etc.
7. restorefile:
o Stores information about each file restored during a restore operation, including
the logical and physical names of the files.
o Example columns: restore_history_id, file_id, logical_name,
physical_name, etc.
8. restorefilegroup:
o Stores information about each filegroup restored during a restore operation.
o Example columns: restore_history_id, filegroup_id, filegroup_name, etc.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
18. Checking Index Fragmentation
Checking for fragmentation in SQL Server is important for maintaining optimal performance.
Fragmentation can slow down query performance and cause excessive I/O operations. Here are a
few methods to check for fragmentation:
sql
SELECT
OBJECT_NAME(ps.object_id) AS TableName,
i.name AS IndexName,
ps.index_id,
ps.index_type_desc,
ps.avg_fragmentation_in_percent,
ps.page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
'LIMITED') AS ps
JOIN sys.indexes AS i ON ps.object_id = i.object_id AND
ps.index_id = i.index_id
WHERE ps.database_id = DB_ID()
ORDER BY ps.avg_fragmentation_in_percent DESC;
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
EXEC sp_helpindex 'YourTableName';
In SQL Server, fragmentation refers to how the data is stored on disk and how it impacts
performance. There are two primary types of fragmentation to be aware of:
1. Internal Fragmentation:
o Internal fragmentation occurs when the pages within an index have excess free
space, meaning they are not filled to capacity.
o This can happen due to frequent inserts, updates, or deletes, which leave gaps
within the pages.
o Internal fragmentation reduces storage efficiency and can lead to increased I/O
operations because more pages need to be read to retrieve the same amount of
data.
o You can check internal fragmentation using the
avg_page_space_used_in_percent column from the
sys.dm_db_index_physical_stats DMV. A lower value indicates higher
internal fragmentation.
sql
SELECT
OBJECT_NAME(ps.object_id) AS TableName,
i.name AS IndexName,
ps.index_id,
ps.index_type_desc,
ps.avg_page_space_used_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
'LIMITED') AS ps
JOIN sys.indexes AS i ON ps.object_id = i.object_id AND
ps.index_id = i.index_id
WHERE ps.database_id = DB_ID()
ORDER BY ps.avg_page_space_used_in_percent ASC;
2. External Fragmentation:
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o External fragmentation occurs when the logical order of the pages does not match
the physical order on disk, causing scattered or fragmented pages.
o This type of fragmentation is common when pages are split due to inserts,
updates, or deletes, leading to non-sequential storage of data.
o External fragmentation can lead to increased disk I/O and reduced performance,
as more disk seeks are required to read the scattered pages.
o You can check external fragmentation using the
avg_fragmentation_in_percent column from the
sys.dm_db_index_physical_stats DMV. A higher value indicates higher
external fragmentation.
sql
SELECT
OBJECT_NAME(ps.object_id) AS TableName,
i.name AS IndexName,
ps.index_id,
ps.index_type_desc,
ps.avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
'LIMITED') AS ps
JOIN sys.indexes AS i ON ps.object_id = i.object_id AND
ps.index_id = i.index_id
WHERE ps.database_id = DB_ID()
ORDER BY ps.avg_fragmentation_in_percent DESC;
Rebuilding Indexes: Rebuilding indexes will create new indexes and remove both
internal and external fragmentation. Use the ALTER INDEX statement to rebuild indexes.
sql
Reorganizing Indexes: Reorganizing indexes will defragment the leaf level of the index
by physically reordering the pages. This can help reduce external fragmentation without
fully rebuilding the index.
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Unused indexes waste space and resources.
How?
SELECT * FROM sys.dm_db_index_usage_stats WHERE user_seeks = 0 AND user_scans =
0;
Checking for database corruption in SQL Server is crucial for maintaining data integrity and
ensuring smooth operations. Here are some methods to check for database corruption:
sql
o This command performs a thorough check of your database and reports any
issues, such as allocation errors or consistency problems2.
2. Reviewing SQL Server Error Logs:
o SQL Server’s error logs can provide early signs of potential corruption. Look for
messages related to I/O errors or failed reads/writes, as these could indicate
underlying hardware issues.
3. Using the Suspect Pages Table:
o SQL Server maintains logs of suspect pages in the suspect_pages table in the
msdb database. This table contains information about corrupt pages reported by
SQL queries.
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o Automate regular corruption checks by scheduling DBCC CHECKDB to run as part
of your maintenance plan. Be sure to review the results and take action if any
issues are detected.
5. Validating Backups:
o Always test your backups. A corrupt database backup is of no use in recovery. By
restoring your backups to a test environment and running DBCC CHECKDB on them,
you can ensure their reliabilit
DBCC (Database Console Commands) in SQL Server are used to check the physical and logical
consistency of databases, perform maintenance, and provide detailed information about the
database and its structure. Here are some commonly used DBCC commands:
1. DBCC CHECKDB:
o Checks the consistency of the entire database and reports any corruption.
sql
2. DBCC CHECKALLOC:
o Checks the consistency of disk space allocation structures for a specified
database.
sql
3. DBCC CHECKTABLE:
o Checks the integrity of a specific table or indexed view.
sql
4. DBCC CHECKCONSTRAINTS:
o Checks the integrity of all constraints on a specified table or an entire database.
sql
5. DBCC SQLPERF:
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o Provides transaction log space usage statistics.
sql
6. DBCC SHOWCONTIG:
o Displays fragmentation information for a specified table or index.
sql
7. DBCC INDEXDEFRAG:
o Defragments a specific index. (This command is deprecated, use ALTER
INDEX ... REORGANIZE instead.)
sql
8. DBCC SHRINKDATABASE:
o Shrinks the size of the data and log files in a specified database.
sql
9. DBCC SHRINKFILE:
o Shrinks the size of a specified data or log file.
sql
sql
DBCC FREEPROCCACHE;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
sql
DBCC DROPCLEANBUFFERS;
sql
Resolving slow-running queries in SQL Server involves identifying the root cause and applying
appropriate optimizations. Here are some steps you can take to troubleshoot and resolve slow-
running queries:
sql
SELECT
TOP 10
qs.sql_handle,
qs.execution_count,
qs.total_elapsed_time / qs.execution_count AS AvgElapsedTime,
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
query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY AvgElapsedTime DESC;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o Use SQL Server Management Studio (SSMS) to view the execution plans of
slow-running queries. Look for issues such as table scans, missing indexes, or
inefficient joins.
o You can also use the sys.dm_exec_query_plan DMV to retrieve execution
plans:
sql
SELECT
qs.sql_handle,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
ORDER BY qs.total_elapsed_time DESC;
3. Optimize Indexes:
o Ensure that your queries are using appropriate indexes. Create missing indexes
and remove unused or redundant indexes.
o Use the sys.dm_db_missing_index_details DMV to identify missing indexes:
sql
SELECT
database_id,
OBJECT_NAME(object_id, database_id) AS TableName,
equality_columns,
inequality_columns,
included_columns,
statement
FROM sys.dm_db_missing_index_details;
4. Update Statistics:
o Outdated statistics can lead to suboptimal query plans. Regularly update statistics
to ensure the query optimizer has accurate information:
sql
sql
EXEC sp_who2;
PERFORMANCE TUNNING
MAME TECHNOLOGIES
6. Check for Resource Bottlenecks:
o Use Performance Monitor (PerfMon) to monitor CPU, memory, and disk usage.
High resource utilization can impact query performance.
o Use the sys.dm_os_wait_stats DMV to identify wait types and their impact on
query performance:
sql
SELECT
wait_type,
wait_time_ms,
max_wait_time_ms,
signal_wait_time_ms,
wait_time_ms - signal_wait_time_ms AS resource_wait_time_ms
FROM sys.dm_os_wait_stats
ORDER BY wait_time_ms DESC;
When the transaction log file in SQL Server becomes full, it can prevent further transactions
from being processed. Here are some steps to resolve this issue:
sql
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
3. Change the Recovery Model:
o If you do not need point-in-time recovery, consider changing the recovery model
to SIMPLE. This will automatically truncate the log after each transaction:
sql
sql
sql
sql
SELECT
database_id,
total_log_size_in_bytes / 1024 / 1024 AS TotalLogSizeMB,
used_log_space_in_bytes / 1024 / 1024 AS UsedLogSpaceMB,
(total_log_size_in_bytes - used_log_space_in_bytes) / 1024 /
1024 AS FreeLogSpaceMB
FROM
PERFORMANCE TUNNING
MAME TECHNOLOGIES
1. Free Up Disk Space:
o Delete Unnecessary Files: Remove old backup files, log files, and other
unnecessary files from the disk.
o Move Files to Another Disk: Move large files, such as backups, to another disk
with more space.
o Empty the Recycle Bin: Ensure that the Recycle Bin is emptied to free up space.
2. Shrink Database Files:
o Shrink Data Files: Use the DBCC SHRINKFILE command to shrink data files and
reclaim space.
sql
o Shrink Log Files: Use the DBCC SHRINKFILE command to shrink log files.
sql
sql
sql
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
sql
sql
SELECT
database_id,
total_log_size_in_bytes / 1024 / 1024 AS TotalLogSizeMB,
used_log_space_in_bytes / 1024 / 1024 AS UsedLogSpaceMB,
(total_log_size_in_bytes - used_log_space_in_bytes) / 1024 /
1024 AS FreeLogSpaceMB
FROM
SQL Server is not respoding , reasons and resolutions
When SQL Server is not responding, it can be due to various reasons. Here are some common
causes and their resolutions:
Common Causes
1. Deadlocks:
o Deadlocks occur when two or more processes are waiting for each other to release
resources, causing a standstill.
o Resolution: Use the sys.dm_tran_locks DMV to identify deadlocks and resolve
them by optimizing queries and adjusting locking strategies.
2. TempDB Issues:
o TempDB can become full or experience contention, leading to performance
issues.
o Resolution: Monitor TempDB usage and add additional TempDB files if
necessary. Ensure that TempDB is on fast storage.
3. Blocking:
o Blocking occurs when one session holds a lock on a resource that another session
is trying to access.
o Resolution: Use the sp_who2 stored procedure to identify blocking sessions and
resolve them by optimizing queries or killing blocking sessions.
4. High CPU or Memory Usage:
o High CPU or memory usage can cause SQL Server to become unresponsive.
o Resolution: Monitor CPU and memory usage using Performance Monitor
(PerfMon) and identify resource-intensive queries. Optimize queries and consider
adding more hardware resources.
PERFORMANCE TUNNING
MAME TECHNOLOGIES
5. Disk I/O Bottlenecks:
o Slow disk I/O can cause SQL Server to become unresponsive.
o Resolution: Monitor disk I/O using PerfMon and ensure that data and log files are
on fast storage. Consider using SSDs for better performance.
6. Rogue OS-Level Processes:
o OS-level processes can consume hardware resources, affecting SQL Server
performance.
o Resolution: Use Task Manager to identify and kill rogue processes. Ensure that
SQL Server has sufficient resources.
7. Hardware Issues:
o Hardware failures or limitations can cause SQL Server to become unresponsive.
o Resolution: Check hardware components such as memory, CPU, and storage.
Upgrade hardware if necessary.
Troubleshooting Steps
Dealing with database corruption in SQL Server can be challenging, but there are steps you can
take to identify and resolve the issue. Here are some methods to address database corruption:
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
o This command will report any corruption found in the database.
2. Review the Error Logs:
o Check the SQL Server error logs for any messages related to database corruption.
These logs can provide additional information about the nature and extent of the
corruption.
3. Put the Database in Emergency Mode:
o If the database is severely corrupted and you cannot access it, you can put it in
emergency mode to perform repairs:
sql
sql
sql
sql
When a SQL Server database is marked as "suspect," it means that SQL Server has detected a
problem with the database and has taken it offline to prevent further damage. Here are the steps
to resolve a suspect database:
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Steps to Resolve a Suspect Database
sql
sql
sql
sql
sql
sql
PERFORMANCE TUNNING
MAME TECHNOLOGIES
Monitoring and optimizing query performance in SQL Server is crucial for maintaining efficient
and responsive databases. Here are some methods and tools to help you achieve this:
sql
SELECT
TOP 10
qs.sql_handle,
qs.execution_count,
qs.total_elapsed_time / qs.execution_count AS AvgElapsedTime,
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
query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY AvgElapsedTime DESC;
3. Extended Events:
o Extended Events is a lightweight performance monitoring system that uses
minimal resources. It allows you to create, modify, display, and analyze session
data.
4. Performance Monitor (PerfMon):
o Use Windows Performance Monitor to track SQL Server performance counters,
such as CPU usage, memory usage, and disk I/O.
1. Index Optimization:
o Ensure that your queries are using appropriate indexes. Create missing indexes
and remove unused or redundant indexes.
o Use the sys.dm_db_missing_index_details DMV to identify missing indexes:
PERFORMANCE TUNNING
MAME TECHNOLOGIES
sql
SELECT
database_id,
OBJECT_NAME(object_id, database_id) AS TableName,
equality_columns,
inequality_columns,
included_columns,
statement
FROM sys.dm_db_missing_index_details;
2. Query Tuning:
o Analyze execution plans to identify inefficiencies, such as table scans or
inefficient joins.
o Use the Database Engine Tuning Advisor (DTA) to analyze the performance
effects of Transact-SQL statements and provide recommendations.
3. Update Statistics:
o Regularly update statistics to ensure the query optimizer has accurate information:
sql
As a SQL Server DBA, you're constantly tasked with keeping your databases running at
peak performance. But with so many moving parts in the SQL Server ecosystem, it can
be tough to know where to start. That's why I've put together this list of the top 5 SQL
Server performance tuning techniques every DBA should know. By focusing on these
areas, you can make sure your databases are running smoothly and your users are
happy.
One of the most important things you can do as a DBA is to monitor and optimize query
performance. This involves identifying slow-running queries and finding ways to
improve their performance. There are a few different tools you can use to do this,
including SQL Server's built-in query store and third-party tools like SentryOne and
Redgate's SQL Monitor. By monitoring query performance and making adjustments
PERFORMANCE TUNNING
MAME TECHNOLOGIES
where necessary, you can ensure that your databases are running as efficiently as
possible.
Another key area to focus on is server hardware. Even the best-tuned database won't
perform well if it's running on outdated or insufficient hardware. Make sure you're
keeping an eye on CPU, memory, and disk usage, and upgrade your hardware as
necessary to keep up with demand. You can also use tools like SQLIOSim to simulate I/O
loads and test the performance of your storage subsystem.
Indexing is another crucial area for performance tuning. By creating and maintaining
indexes on your tables, you can help SQL Server find data more quickly and efficiently.
However, it's important to make sure you're not over-indexing, as this can actually hurt
performance. Use tools like SQL Server's Database Engine Tuning Advisor to help you
identify and implement the best indexing strategies for your databases.
Blocking and deadlocks are common performance issues in SQL Server, and they can be
difficult to diagnose and resolve. That's why it's important to monitor for them
proactively. SQL Server's built-in Activity Monitor can help you identify blocking and
deadlocks, and there are also third-party tools like Quest's Spotlight and SolarWinds'
Database Performance Analyzer that can provide more detailed information and
recommendations for resolving these issues.
Finally, make sure you're regularly updating and maintaining statistics on your
databases. Statistics help SQL Server make informed decisions about how to execute
queries, and outdated statistics can lead to poor performance. Use tools like the
sp_updatestats stored procedure and SQL Server's Maintenance Plan Wizard to
automate the process of updating and maintaining statistics.
PERFORMANCE TUNNING