0% found this document useful (0 votes)
33 views50 pages

SQL DBA Performance Tunning Book 1740934042

The document provides a comprehensive guide on various SQL Server management tasks, including checking the SQL Server version, monitoring uptime, database sizes, disk space usage, long-running queries, active user sessions, blocked processes, CPU-intensive queries, memory usage, and deadlocks. It includes SQL queries and methods using SQL Server Management Studio (SSMS), Dynamic Management Views (DMVs), and other tools for performance tuning and monitoring. The information is essential for maintaining optimal SQL Server performance and addressing potential issues.

Uploaded by

lalkundan958
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views50 pages

SQL DBA Performance Tunning Book 1740934042

The document provides a comprehensive guide on various SQL Server management tasks, including checking the SQL Server version, monitoring uptime, database sizes, disk space usage, long-running queries, active user sessions, blocked processes, CPU-intensive queries, memory usage, and deadlocks. It includes SQL queries and methods using SQL Server Management Studio (SSMS), Dynamic Management Views (DMVs), and other tools for performance tuning and monitoring. The information is essential for maintaining optimal SQL Server performance and addressing potential issues.

Uploaded by

lalkundan958
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

MAME TECHNOLOGIES

1. Checking SQL Server Version and Edition


Understanding the SQL Server version and edition is crucial for compatibility, feature
availability, and patch management. Running an outdated version can expose security
vulnerabilities and performance issues.
SELECT @@VERSION AS SQLServerVersion, SERVERPROPERTY('Edition') AS Edition;
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'),
SERVERPROPERTY('edition')
SELECT @@VERSION

 Using SQL Server Management Studio (SSMS):

 Connect to the server using Object Explorer in SSMS.


 Once connected, the version information will be displayed in parentheses, along with the
username used to connect to the specific instance of SQL Server.

 Using a T-SQL Query:

 Connect to the instance of SQL Server and run the following query:

sql

SELECT @@VERSION

 This will display the version and edition of SQL Server.

 Using the SERVERPROPERTY Function:

 Connect to the instance of SQL Server and run the following query in SSMS:

sql

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY('productlevel'),


SERVERPROPERTY('edition')

 This will return the product version, product level, and edition of SQL Server.

 Checking the Error Log:

 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.

2. Monitoring SQL Server Uptime

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.

 Querying SQL Server Dynamic Management Views (DMVs):

 You can use the sys.dm_os_sys_info DMV to get the SQL Server instance uptime. Run
the following query:

sql

SELECT sqlserver_start_time AS [SQL Server Instance Uptime]


FROM sys.dm_os_sys_info;

 This will return the SQL Server startup time.

 Using the sys.sysprocesses DMV:

 Another way to check uptime is by querying the sys.sysprocesses DMV. Run the
following query:

sql

SELECT login_time AS [SQL Server Instance Uptime]


FROM sys.sysprocesses
WHERE spid = 1;

 This will show the instance startup time.

 Checking the SQL Server Error Log:

 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.

 Using SQL Server Management Studio (SSMS) Dashboard:

3. Checking Database Sizes

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.

4. Monitoring Disk Space Usage

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.

5. Identifying Long-Running Queries

Long-running queries can degrade performance and cause resource contention.


How?
SELECT text AS QueryText,
total_elapsed_time / 1000 AS DurationMs
FROM sys.dm_exec_requests r

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:

1. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o Navigate to Management > Activity Monitor.
o In the Activity Monitor, expand the Processes pane. Here, you can see the
currently running queries and their duration.
2. Using SQL Server Dynamic Management Views (DMVs):
o You can use the sys.dm_exec_requests DMV to identify long-running queries.
Run the following query:

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;

3. Using SQL Server Profiler:


o SQL Server Profiler allows you to trace and monitor the execution of SQL
queries. You can set up a trace to capture long-running queries.
o Open SQL Server Profiler and create a new trace.
o Choose the appropriate events (e.g., RPC:Completed and SQL:BatchCompleted)
and set filters to capture queries that exceed a specific duration.
4. Using Extended Events:
o Extended Events offer a lightweight way to capture and monitor SQL Server
events, including long-running queries.
o You can create an Extended Events session to capture queries that exceed a
specific duration. Here's an example script to create such a session:

sql

CREATE EVENT SESSION LongRunningQueries


ON SERVER
ADD EVENT sqlserver.sql_batch_completed(
WHERE duration > 10000000) -- Duration in microseconds
ADD TARGET package0.event_file(SET filename='C:\Temp\
LongRunningQueries.xel')
GO
ALTER EVENT SESSION LongRunningQueries ON SERVER STATE = START;

5. Using SQL Server Query Store:


o The Query Store feature in SQL Server helps you monitor query performance.
Enable Query Store for your database and use it to identify long-running queries.
o Run the following query to get information on long-running queries from Query
Store:

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;

6. Checking Active User Sessions

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:

1. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o Navigate to Management > Activity Monitor.
o In the Activity Monitor, expand the Processes pane. Here, you can see the
currently active user sessions, including details like session IDs, user names, and
the application names.
2. Using SQL Server Dynamic Management Views (DMVs):
o You can use the sys.dm_exec_sessions and sys.dm_exec_connections
DMVs to get information about active user sessions. Run the following query:

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;

3. Using System Stored Procedures:


o You can use the sp_who or sp_who2 stored procedures to list active user sessions.
Run the following command:

sql

EXEC sp_who;

o Or, for more detailed information:

sql

EXEC sp_who2;

4. Using SQL Server Profiler:


o SQL Server Profiler allows you to trace and monitor the activity of user sessions.
o Open SQL Server Profiler and create a new trace.
o Choose the appropriate events (e.g., RPC:Completed and SQL:BatchCompleted)
to capture details about active user sessions.
5. Using Extended Events:
o Extended Events offer a lightweight way to capture and monitor user session
activity.
o You can create an Extended Events session to capture relevant information. Here's
an example script to create a session that captures login events:

sql

CREATE EVENT SESSION UserLoginSession


ON SERVER
ADD EVENT sqlserver.login(
ACTION(sqlserver.client_hostname, sqlserver.username)
WHERE [sqlserver].[is_user_process] = 1)
ADD TARGET package0.event_file(SET filename='C:\Temp\
UserLoginSession.xel')
GO
ALTER EVENT SESSION UserLoginSession ON SERVER STATE = START;

7. Finding Blocked Processes

Blocked processes can cause performance slowdowns and deadlocks.

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:

1. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o Navigate to Management > Activity Monitor.
o In the Activity Monitor, expand the Processes pane. Look for processes with a
status of "Suspended" and a non-zero value in the Blocked By column.
2. Using SQL Server Dynamic Management Views (DMVs):
o You can use the sys.dm_exec_requests and sys.dm_exec_sessions DMVs to
identify blocked processes. Run the following query:

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;

3. Using System Stored Procedures:


o You can use the sp_who2 stored procedure to list blocked processes. Run the
following command:

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

CREATE EVENT SESSION BlockingSession


ON SERVER
ADD EVENT sqlserver.blocked_process_report(
ACTION(sqlserver.client_hostname, sqlserver.username)
WHERE [sqlserver].[is_user_process] = 1)
ADD TARGET package0.event_file(SET filename='C:\Temp\
BlockingSession.xel')
GO
ALTER EVENT SESSION BlockingSession ON SERVER STATE = START;

6. Using SQL Server Agent Jobs:


o You can set up a SQL Server Agent job to monitor blocking and alert you when
blocking occurs. Create a job that runs a T-SQL script similar to the ones above
and sends an alert if blocking is detected.

8. Identifying CPU-Intensive Queries

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:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can use the sys.dm_exec_query_stats DMV to identify CPU-intensive
queries. Run the following query:

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

CREATE EVENT SESSION CPUIntensiveQueries


ON SERVER
ADD EVENT sqlserver.rpc_completed(
ACTION(sqlserver.client_app_name, sqlserver.database_id,
sqlserver.query_hash)
WHERE total_worker_time > 10000000) -- Adjust the threshold as
needed
ADD TARGET package0.event_file(SET filename='C:\Temp\
CPUIntensiveQueries.xel')

PERFORMANCE TUNNING
MAME TECHNOLOGIES
GO
ALTER EVENT SESSION CPUIntensiveQueries ON SERVER STATE = START;

4. Using SQL Server Query Store:


o The Query Store feature in SQL Server helps you monitor query performance.
o Enable Query Store for your database and use it to identify CPU-intensive
queries.
o Run the following query to get information on CPU-intensive queries from Query
Store:

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;

5. Using SQL Server Performance Monitor (PerfMon):


o You can use Windows Performance Monitor (PerfMon) to monitor CPU usage
and identify CPU-intensive queries.
o Add counters for Processor and SQL Server:SQL Statistics to track CPU usage
and query execution.

9. Analyzing Memory Usage

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;

10. Detecting Deadlocks

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:

1. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o Navigate to Management > Activity Monitor.
o In the Activity Monitor, expand the Processes pane and look for processes with a
status of "Suspended" and a reason of "Deadlock."
2. Using SQL Server Dynamic Management Views (DMVs):
o You can use the sys.dm_tran_locks, sys.dm_exec_requests, and
sys.dm_exec_sessions DMVs to identify deadlocks. Run the following query:

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';

3. Using SQL Server Profiler:


o SQL Server Profiler allows you to trace and monitor deadlock events.
o Open SQL Server Profiler and create a new trace.
o Choose the events Lock:Deadlock, Lock:Deadlock Chain, and Lock:Timeout
to capture details about deadlocks.
o You can save the trace results for further analysis.
4. Using Extended Events:
o Extended Events offer a lightweight way to capture and monitor deadlock events.
o You can create an Extended Events session to capture deadlock information.
Here's an example script to create a session that captures deadlocks:

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;

5. Using SQL Server Error Logs:


o Deadlock information is also recorded in the SQL Server error logs. You can
check the error logs for deadlock reports.
o By default, the error logs are located at Program Files\Microsoft SQL
Server\MSSQL.n\MSSQL\LOG\ERRORLOG.
6. Enabling Trace Flags:
o You can enable trace flags to capture deadlock information in the error logs.
 Enable Trace Flag 1204: This flag provides information about the nodes
involved in the deadlock.

sql

DBCC TRACEON(1204, -1);

 Enable Trace Flag 1222: This flag provides a more detailed deadlock
graph.

sql

DBCC TRACEON(1222, -1);

 You can disable these trace flags using the following commands:

sql

DBCC TRACEOFF(1204, -1);


DBCC TRACEOFF(1222, -1);

11. Checking Database Growth Trends

Monitoring database growth helps plan for storage expansion.


How?
SELECT name AS DatabaseName,
size * 8 / 1024 AS SizeMB,

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:

1. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o Navigate to Reports > Standard Reports > Disk Usage.
o The Disk Usage report provides information on the database size, space usage,
and growth trends.
2. Using T-SQL Queries:
o Run the following query to get the size of each database and track its growth over
time:

sql

CREATE TABLE DatabaseGrowthHistory (


LogDate DATETIME,
DatabaseName NVARCHAR(128),
SizeMB DECIMAL(18, 2)
);

INSERT INTO DatabaseGrowthHistory (LogDate, DatabaseName, SizeMB)


SELECT
GETDATE() AS LogDate,
name AS DatabaseName,
SUM(size * 8 / 1024) AS SizeMB
FROM sys.master_files
GROUP BY name;

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

Import-Module SQLPS -DisableNameChecking


Get-SqlDatabase -ServerInstance "YourServerInstance" |
ForEach-Object {
$size = $_.Size / 1MB
[PSCustomObject]@{
DatabaseName = $_.Name
SizeMB = [math]::round($size, 2)
LogDate = Get-Date
}
} | Export-Csv -Path "C:\Temp\DatabaseGrowth.csv" -
NoTypeInformation

Finding unused DB's in SQL Server

Identifying unused databases in SQL Server can help you manage resources more efficiently.
Here are a few methods you can use:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can query the sys.databases and sys.dm_db_index_usage_stats DMVs
to find databases that have not been accessed recently. Run the following query:

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;

2. Using SQL Server Agent Jobs:


o Create a SQL Server Agent job to log database connections over time. You can
use the following script to create a table to store connection information:

sql

CREATE TABLE dbo.DatabaseConnectionLog (


LogDate DATETIME,
DatabaseName NVARCHAR(128),
ConnectionCount INT
);

o Schedule a job to run periodically and log the connection counts:

sql

INSERT INTO dbo.DatabaseConnectionLog (LogDate, DatabaseName,


ConnectionCount)
SELECT
GETDATE() AS LogDate,
d.name AS DatabaseName,
COUNT(s.session_id) AS ConnectionCount
FROM sys.databases d
LEFT JOIN sys.dm_exec_sessions s ON d.database_id = s.database_id
WHERE d.database_id > 4 -- Exclude system databases
GROUP BY d.name;

3. Using SQL Server Profiler:


o SQL Server Profiler allows you to trace and monitor database activity. You can
set up a trace to capture database connections and analyze the results to identify
unused databases.
4. Using Extended Events:
o Extended Events offer a lightweight way to capture and monitor database activity.
You can create an Extended Events session to log database connections and
analyze the results.

12. Analyzing Index Usage

Unused indexes consume resources without improving performance.

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:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can use the sys.dm_db_index_usage_stats DMV to analyze index usage.
Run the following query to get information about index usage for all databases:

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;

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 > Index Usage Statistics.
o This report provides detailed information about index usage, including seeks,
scans, lookups, and updates.
3. Using System Stored Procedures:
o You can use the sp_helpindex stored procedure to get information about indexes
on a specific table. Run the following command:

sql

PERFORMANCE TUNNING
MAME TECHNOLOGIES
EXEC sp_helpindex 'YourTableName';

4. Using SQL Server Performance Monitor (PerfMon):


o You can use Windows Performance Monitor (PerfMon) to track index usage and
related performance metrics. Add counters for SQL Server: Access Methods and
SQL Server: Buffer Manager to monitor index seeks, scans, and lookups.
5. Using SQL Server Query Store:
o The Query Store feature in SQL Server helps you monitor query performance and
analyze index usage.
o Enable Query Store for your database and use it to identify queries that benefit
from specific indexes.
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;

Missing indexes in SQL Sever?

Identifying missing indexes in SQL Server can significantly improve query performance. Here
are a few methods to find missing indexes:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can use the sys.dm_db_missing_index_details DMV to get detailed
information about missing indexes. Run the following query:

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:

1. Using SQL Server Dynamic Management Views (DMVs):

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;

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 > Index Usage Statistics.
o This report provides detailed information about index usage, and you can identify
indexes with no seeks, scans, or lookups.
3. Using System Stored Procedures:
o You can use the sp_helpindex stored procedure to get information about indexes
on a specific table and check for unused indexes. Run the following command:

sql

EXEC sp_helpindex 'YourTableName';

4. Using SQL Server Query Store:


o The Query Store feature in SQL Server helps you monitor query performance and
analyze index usage.
o Enable Query Store for your database and use it to identify indexes that are not
being utilized by queries.

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;

13. Monitoring TempDB Usage

TempDB is a shared resource; excessive usage can impact overall performance.


How?
SELECT name, size * 8 / 1024 AS SizeMB,
state_desc FROM sys.master_files WHERE database_id = 2;

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:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can use the sys.dm_db_file_space_usage DMV to monitor space usage in
TempDB. Run the following query:

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;

2. Using SQL Server Management Studio (SSMS):

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;

4. Using SQL Server Performance Monitor (PerfMon):


o You can use Windows Performance Monitor (PerfMon) to track TempDB space
usage and related performance metrics. Add counters for LogicalDisk or
PhysicalDisk to monitor disk usage over time.
5. Using SQL Server Agent Jobs:
o You can set up a SQL Server Agent job to monitor TempDB space usage and
alert you when space is running low. Create a job that runs a T-SQL script similar
to the ones above and sends an alert if the free space drops below a certain
threshold.

What are the Temp tables in SQL Server

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:

1. Local Temporary Tables:


o Local temp tables are created with a single # symbol (e.g., #TempTable).
o They are only visible to the session that created them and are automatically
dropped when the session ends.
o Example:

sql

CREATE TABLE #TempTable (


ID INT,
Name NVARCHAR(50)
);

INSERT INTO #TempTable (ID, Name)


VALUES (1, 'John Doe');

PERFORMANCE TUNNING
MAME TECHNOLOGIES
SELECT * FROM #TempTable;

2. Global Temporary Tables:


o Global temp tables are created with two ## symbols (e.g., ##GlobalTempTable).
o They are visible to all sessions and are dropped automatically when the session
that created them ends and all other sessions referencing the table have finished.
o Example:

sql

CREATE TABLE ##GlobalTempTable (


ID INT,
Name NVARCHAR(50)
);

INSERT INTO ##GlobalTempTable (ID, Name)


VALUES (1, 'Jane Smith');

SELECT * FROM ##GlobalTempTable;

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

DECLARE @TempTableVar TABLE (


ID INT,
Name NVARCHAR(50)
);

INSERT INTO @TempTableVar (ID, Name)


VALUES (1, 'Alice Brown');

SELECT * FROM @TempTableVar;

4. Temporary Table Types:


o You can also define a table type and use it as a temp table by declaring a variable
of that type.
o Example:

sql

CREATE TYPE TempTableType AS TABLE (


ID INT,
Name NVARCHAR(50)

PERFORMANCE TUNNING
MAME TECHNOLOGIES
);

DECLARE @TempTableOfType TempTableType;

INSERT INTO @TempTableOfType (ID, Name)


VALUES (1, 'Chris Green');

SELECT * FROM @TempTableOfType;

14. Checking Open Transactions

Long-running open transactions can lead to blocking and locking issues.


How?
DBCC OPENTRAN;

To check open transactions in SQL Server, you can use several methods. Here are some common
approaches:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can use the sys.dm_tran_active_transactions DMV to get information
about active transactions. Run the following query:

sql

SELECT
transaction_id,
name,
transaction_state,
transaction_begin_time,
database_id
FROM sys.dm_tran_active_transactions;

2. Using the DBCC OPENTRAN Command:


o The DBCC OPENTRAN command displays information about the oldest active
transaction in the specified database. Run the following command:

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

15. Analyzing Wait Statistics

Wait statistics provide insight into bottlenecks.


How?
SELECT wait_type, wait_time_ms FROM sys.dm_os_wait_stats ORDER BY wait_time_ms
DESC;

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:

1. Using SQL Server Dynamic Management Views (DMVs):


o You can use the sys.dm_os_wait_stats DMV to get information about wait
types and their associated statistics. Run the following query:

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;

2. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o Navigate to Reports > Standard Reports > Server Dashboard.
o The Server Dashboard report provides information about wait statistics and other
performance metrics.
3. Using Performance Monitor (PerfMon):
o You can use Windows Performance Monitor (PerfMon) to track wait statistics
and related performance metrics. Add counters for SQL Server: Wait Statistics to
monitor different wait types.
4. Using SQL Server Query Store:
o The Query Store feature in SQL Server helps you monitor query performance and
analyze wait statistics.
o Enable Query Store for your database and use it to identify queries that are
experiencing waits.
o Run the following query to get information on wait statistics from Query Store:

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;

5. Using SQL Server Profiler:


o SQL Server Profiler allows you to trace and monitor wait events.
o Open SQL Server Profiler and create a new trace.
o Choose the appropriate events (e.g., WaitInfo, WaitInfoExternal) to capture
details about wait types and durations.

Frequenlty using wait types in SQL Server?

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.

how to resolve CXPACKET in SQL Server

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:

1. Adjust the MAXDOP Setting:


o The MAXDOP (Maximum Degree of Parallelism) setting controls the number of
processors used for parallel query execution. Reducing the MAXDOP value can help
reduce CXPACKET waits.
o You can set the MAXDOP value at the server level using the following command:

sql

EXEC sp_configure 'show advanced options', 1;


RECONFIGURE;
EXEC sp_configure 'max degree of parallelism', 4; -- Adjust the
value as needed
RECONFIGURE;

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

UPDATE STATISTICS YourTableName;

4. Monitor and Adjust Cost Threshold for Parallelism:


o The cost threshold for parallelism setting determines the threshold at
which SQL Server considers parallel execution for a query. Increasing this value
can help reduce unnecessary parallelism.
o You can adjust the cost threshold for parallelism setting using the
following command:

sql

EXEC sp_configure 'show advanced options', 1;


RECONFIGURE;
EXEC sp_configure 'cost threshold for parallelism', 50; -- Adjust
the value as needed
RECONFIGURE;

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.

How to resolve PAGEIOLATCH_ and PAGELATCH_**: in SQL Server

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:

Resolving PAGEIOLATCH_ 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:

1. Optimize I/O Subsystem:


o Ensure that your disk subsystem is properly configured and optimized for SQL
Server workloads.
o Use fast storage solutions like SSDs to reduce I/O latency.
o Distribute data files across multiple disks to balance the I/O load.
2. Improve Indexing:
o Ensure that your queries are using appropriate indexes to minimize full table
scans.
o Regularly rebuild or reorganize fragmented indexes to improve query
performance.
3. Increase Memory:
o Increase the amount of memory available to SQL Server to reduce the need for
disk I/O.
o Configure the buffer pool appropriately to ensure efficient use of memory.
4. Monitor and Tune Queries:
o Identify and optimize long-running queries that cause excessive I/O.
o Use SQL Server Profiler or Extended Events to monitor query performance and
identify bottlenecks.

Resolving PAGELATCH_ 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

16. Checking SQL Server Error Logs

Error logs contain critical information for troubleshooting issues.


How?
EXEC sp_readerrorlog;
EXEC xp_readerrorlog 0, 1, N'';

hecking the Log Files Directly:

 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).

17. Monitoring Database Backups

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:

1. Using SQL Server Management Studio (SSMS):


o Open SSMS and connect to the SQL Server instance.
o In Object Explorer, right-click the database you want to monitor.
o Navigate to Reports > Standard Reports > Backup and Restore Events.
o This report provides detailed information about backup and restore events,
including the type of backup, start and end times, and backup size.
2. Using SQL Server Dynamic Management Views (DMVs):
o You can query the msdb database to get information about backup history. Run
the following query to get recent backup history for all databases:

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;

3. Using SQL Server Agent Jobs:


o You can set up SQL Server Agent jobs to monitor and log backup events. Create a
job that runs the query above or a similar one and sends an alert or logs the
information to a table or file.
4. Using SQL Server Maintenance Plans:
o You can create a maintenance plan that includes backup tasks and monitoring
steps.
o In SSMS, go to Management > Maintenance Plans.
o Create a new maintenance plan and add a Back Up Database Task.
o You can include additional tasks to log backup information and send notifications.
5. Using SQL Server Alerts:
o You can configure SQL Server alerts to monitor backup events and send
notifications.
o In SSMS, go to SQL Server Agent > Alerts.
o Create a new alert and configure it to trigger based on specific backup-related
events.

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

Fragmented indexes can slow down query performance.


How?
SELECT * FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED');

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:

1. 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 Tasks > Generate Scripts.
o In the Script Wizard, choose Script entire database and all database objects.
o Once the script is generated, look for the index definitions to analyze their
fragmentation.
2. Using Dynamic Management Views (DMVs):
o You can use the sys.dm_db_index_physical_stats DMV to analyze
fragmentation. Here’s a query to get fragmentation information for all indexes in
a specific database:

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;

3. Using System Stored Procedures:


o You can use the sp_helpindex stored procedure to get information about indexes
on a specific table and check for fragmentation. Run the following command:

sql

PERFORMANCE TUNNING
MAME TECHNOLOGIES
EXEC sp_helpindex 'YourTableName';

4. Using SQL Server Maintenance Plans:


o You can create a maintenance plan to check and reduce fragmentation.
o In SSMS, go to Management > Maintenance Plans.
o Create a new maintenance plan and add an Index Rebuild Task or an Index
Reorganize Task to reduce fragmentation.
5. Using SQL Server Profiler:
o SQL Server Profiler allows you to trace and monitor database activity, including
fragmentation.
o Open SQL Server Profiler and create a new trace.
o

Fragmentaion types in SQLserver

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;

Steps to Resolve Fragmentation

 Rebuilding Indexes: Rebuilding indexes will create new indexes and remove both
internal and external fragmentation. Use the ALTER INDEX statement to rebuild indexes.

sql

ALTER INDEX ALL ON YourTableName REBUILD;

 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

ALTER INDEX ALL ON YourTableName REORGANIZE;

19. Identifying Unused Indexes

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;

20. Checking Database Corruption

Detecting corruption early prevents data loss.


How?
DBCC CHECKDB;

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:

1. Using DBCC CHECKDB:


o The most reliable way to check for corruption is by running the DBCC CHECKDB
command. This built-in utility scans your database for corruption in both system
and user data.

sql

DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

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

SELECT * FROM msdb.dbo.suspect_pages;

4. Scheduled Maintenance Jobs:

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

BCC Commands in SQL Server

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

DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

2. DBCC CHECKALLOC:
o Checks the consistency of disk space allocation structures for a specified
database.

sql

DBCC CHECKALLOC ('YourDatabaseName') WITH NO_INFOMSGS,


ALL_ERRORMSGS;

3. DBCC CHECKTABLE:
o Checks the integrity of a specific table or indexed view.

sql

DBCC CHECKTABLE ('YourDatabaseName.dbo.YourTableName') WITH


NO_INFOMSGS, ALL_ERRORMSGS;

4. DBCC CHECKCONSTRAINTS:
o Checks the integrity of all constraints on a specified table or an entire database.

sql

DBCC CHECKCONSTRAINTS ('YourDatabaseName.dbo.YourTableName');

5. DBCC SQLPERF:

PERFORMANCE TUNNING
MAME TECHNOLOGIES
o Provides transaction log space usage statistics.

sql

DBCC SQLPERF (LOGSPACE);

6. DBCC SHOWCONTIG:
o Displays fragmentation information for a specified table or index.

sql

DBCC SHOWCONTIG ('YourDatabaseName.dbo.YourTableName') WITH


ALL_INDEXES;

7. DBCC INDEXDEFRAG:
o Defragments a specific index. (This command is deprecated, use ALTER
INDEX ... REORGANIZE instead.)

sql

DBCC INDEXDEFRAG ('YourDatabaseName', 'YourTableName',


'YourIndexName');

8. DBCC SHRINKDATABASE:
o Shrinks the size of the data and log files in a specified database.

sql

DBCC SHRINKDATABASE ('YourDatabaseName');

9. DBCC SHRINKFILE:
o Shrinks the size of a specified data or log file.

sql

DBCC SHRINKFILE (YourFileID, TargetSize);

10. DBCC FREEPROCCACHE:


o Clears the procedure cache to free up memory.

sql

DBCC FREEPROCCACHE;

11. DBCC DROPCLEANBUFFERS:


o Clears the buffer cache to test performance with a cold buffer cache.

PERFORMANCE TUNNING
MAME TECHNOLOGIES
sql

DBCC DROPCLEANBUFFERS;

12. DBCC TRACEON and DBCC TRACEOFF:


o Enables or disables specific trace flags for troubleshooting.

sql

DBCC TRACEON (TraceFlag, -1); -- Enable


DBCC TRACEOFF (TraceFlag, -1);

Slow-running queries Resolution

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:

1. Identify Slow Queries:


o Use Dynamic Management Views (DMVs) to identify slow-running queries. For
example, you can use the sys.dm_exec_query_stats DMV to find queries with
high execution times:

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;

2. Analyze Execution Plans:

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

UPDATE STATISTICS YourTableName;

5. Monitor and Resolve Blocking:


o Blocking can cause queries to run slowly. Use the sp_who2 stored procedure to
identify blocking sessions:

sql

EXEC sp_who2;

o Resolve blocking by identifying and optimizing the blocking queries.

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;

7. Optimize Query Design:


o Review and optimize the design of your queries. Avoid using cursors, and use set-
based operations instead of row-by-row processing.
o Simplify complex queries and break them into smaller, more manageable parts if
necessary.

Logfile full in SQL Server

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:

1. Backup the Transaction Log:


o Regularly backing up the transaction log will free up space. Run the following
command to back up the transaction log:

sql

BACKUP LOG YourDatabaseName TO DISK = 'C:\Backup\


YourDatabaseName_LogBackup.trn';

2. Truncate the Transaction Log:


o Truncating the transaction log can free up space, but it should be done with
caution as it can result in data loss. Use the following command to truncate the
log:

sql

BACKUP LOG YourDatabaseName WITH TRUNCATE_ONLY;

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

ALTER DATABASE YourDatabaseName SET RECOVERY SIMPLE;

4. Add or Enlarge a Log File:


o If the current log file is too small, you can add a new log file or enlarge the
existing one:

sql

ALTER DATABASE YourDatabaseName


ADD LOG FILE (NAME = YourDatabaseName_Log2, FILENAME = 'C:\
SQLData\YourDatabaseName_Log2.ldf', SIZE = 100MB, MAXSIZE = 1GB,
FILEGROWTH = 10MB);

5. Shrink the Log File:


o After backing up or truncating the log, you can shrink the log file to reclaim
space:

sql

DBCC SHRINKFILE (YourDatabaseName_Log, 100); -- Shrink to 100MB

6. Monitor Log Space Usage:


o Use the sys.dm_db_log_space_usage DMV to monitor log space usage and
identify when the log needs truncation:

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

Disk Space full in SQL Server


When disk space is full in SQL Server, it can cause significant issues, including preventing new
data from being written. Here are some steps to resolve this issue:

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

DBCC SHRINKFILE (YourDataFile, TargetSize);

o Shrink Log Files: Use the DBCC SHRINKFILE command to shrink log files.

sql

DBCC SHRINKFILE (YourLogFile, TargetSize);

3. Backup and Truncate Transaction Logs:


o Backup Transaction Logs: Regularly back up transaction logs to free up space.

sql

BACKUP LOG YourDatabaseName TO DISK = 'C:\Backup\


YourDatabaseName_LogBackup.trn';

o Truncate Transaction Logs: Truncate the transaction logs to free up space.

sql

BACKUP LOG YourDatabaseName WITH TRUNCATE_ONLY;

4. Change Recovery Model:


o Simple Recovery Model: If point-in-time recovery is not required, change the
recovery model to SIMPLE to automatically truncate the log after each
transaction.

sql

ALTER DATABASE YourDatabaseName SET RECOVERY SIMPLE;

5. Add or Enlarge a Log File:


o Add a New Log File: Add a new log file to the database on a different disk.

PERFORMANCE TUNNING
MAME TECHNOLOGIES
sql

ALTER DATABASE YourDatabaseName


ADD LOG FILE (NAME = YourDatabaseName_Log2, FILENAME = 'D:\
SQLData\YourDatabaseName_Log2.ldf', SIZE = 100MB, MAXSIZE = 1GB,
FILEGROWTH = 10MB);

6. Monitor Disk Space Usage:


o Use DMVs: Monitor disk space usage using Dynamic Management Views
(DMVs).

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

1. Check SQL Server Error Logs:


o Review SQL Server error logs for any error messages or warnings that could
indicate the cause of the issue.
2. Use Dynamic Management Views (DMVs):
o Use DMVs such as sys.dm_exec_requests, sys.dm_exec_sessions, and
sys.dm_os_wait_stats to identify and diagnose performance issues.
3. Restart SQL Server:
o If SQL Server is completely unresponsive, consider restarting the SQL Server
service. However, this should be done as a last resort.
4. Review Recent Changes:
o Check for any recent changes to the database or server configuration that could
have caused the issue.

Database is corrupted in SQL Server

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:

Steps to Identify and Resolve Database Corruption

1. Run DBCC CHECKDB:


o The DBCC CHECKDB command checks the physical and logical integrity of all the
objects in the specified database. Run the following command to identify
corruption:

sql

DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

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

ALTER DATABASE YourDatabaseName SET EMERGENCY;

4. Set the Database to SINGLE_USER Mode:


o Before attempting repairs, set the database to SINGLE_USER mode to ensure no
other connections interfere with the process:

sql

ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK


IMMEDIATE;

5. Repair the Database:


o Use DBCC CHECKDB with repair options to fix the corruption. The
REPAIR_ALLOW_DATA_LOSS option can be used, but it may result in data loss:

sql

DBCC CHECKDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS);

o After the repair, set the database back to MULTI_USER mode:

sql

ALTER DATABASE YourDatabaseName SET MULTI_USER;

6. Restore from Backup:


o If the corruption cannot be repaired or if data loss is unacceptable, restore the
database from a known good backup. Ensure that you have regular backups to
minimize data loss in such scenarios.

Database is suspect in SQL Server

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

1. Set the Database to EMERGENCY Mode:


o This mode allows you to access the database in a limited capacity.

sql

ALTER DATABASE YourDatabaseName SET EMERGENCY;

2. Set the Database to SINGLE_USER Mode:


o This ensures that no other connections interfere with the repair process.

sql

ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK


IMMEDIATE;

3. Run DBCC CHECKDB:


o This command checks the integrity of the database and reports any corruption.

sql

DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

4. Attempt to Repair the Database:


o Use DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS option to attempt to
repair the database. Note that this option may result in data loss.

sql

DBCC CHECKDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS);

5. Set the Database Back to MULTI_USER Mode:


o Once the repair is complete, set the database back to MULTI_USER mode.

sql

ALTER DATABASE YourDatabaseName SET MULTI_USER;

6. Check the Database Status:


o Verify that the database is no longer in suspect mode.

sql

SELECT DATABASEPROPERTYEX('YourDatabaseName', 'STATUS') AS


Monitor and Optimize Query Performance in SQL Server

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:

Monitoring Query Performance

1. SQL Server Management Studio (SSMS):


o Use the Activity Monitor to view real-time information about active processes,
resource usage, and performance metrics.
o Use the Query Store to capture and analyze query performance over time. It
provides insights into query plan changes and performance regressions.
2. Dynamic Management Views (DMVs):
o DMVs provide detailed information about the internal state of SQL Server. For
example, you can use sys.dm_exec_query_stats to find queries with high
execution times:

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.

Optimizing Query Performance

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

UPDATE STATISTICS YourTableName;

4. Optimize TempDB Usage:


o Monitor and optimize TempDB usage to prevent contention and improve
performance. Add additional TempDB files if necessary.
5. Monitor and Resolve Blocking:
o Identify and resolve blocking issues by using the sp_who2 stored procedure or
DMVs to identify blocking sessions.

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.

1. Monitor and Optimize Query Performance

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.

2. Keep an Eye on Server Hardware

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.

3. Implement Indexing Strategies

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.

4. Monitor for Blocking and Deadlocks

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.

5. Regularly Update and Maintain Statistics

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

You might also like