DBCC, DMVs and PT Q&A
DBCC, DMVs and PT Q&A
DBCC, DMVs and PT Q&A
I think SQL Server Profiler is one of the must have tools while dealing with performance issues. This
tool is available with SQL Server since a long time. SQL Server Profiler can perform various
significant functions such as tracing what is running and finding out how queries are resolved
internally. The major functions this tool can perform have been listed below:
Creating trace
Watching trace
Storing trace
Replaying trace
2. Should you always leave a profiler trace running on a production server? If yes, then why?
One should never leave profiler trace running on a production server. Profiler adds too much
overhead to production server. And Profiler collects surplus of data making it extremely complex to
analyze them afterwards.
3. Will you advise to leave a profiler trace running on forever from Server A to B?
No, one should never leave profiler trace running on forever on server. It hardly matters if a profiler
trace is running from A to B or directly on B.
4. What is server side trace?
Any time you open SQL Server Profiler and run a trace, you’re running a client-side trace. To run a
server-side trace, one needs to create a script. Server side trace sometimes provides more flexibility
as compared to profiler trace. These four procedures can be used to create Server side traces.
sp_trace_create
sp_trace_setevent
sp_trace_setfilter
sp_trace_setstatus
5. How can DMVs help with performance tuning?
Helps to find out the queries that are causing memory or CPU pressure on your system
Helps to investigate caching, and query plan reuse
Helps to identify index usage patterns
Helps to track fragmentation in clustered indexes and heaps
Gives full details on blocking and blocked transactions
6. Can you please name three DMVs that you have used recently with respect to Performance Tunning?
dm_exec_query_stats
dm_exec_sql_text
dm_exec_query_plan
7. Why is it important to avoid functions in the WHERE clause?
The outcome of any function is evaluated at the run time, so the SQL Server Query engine has to scan
the whole table to get necessary data.
8. What are indexes?
An index is used to speed up the performance of queries. It does this by reducing the number of
database data pages that have to be visited/scanned.
9. What are the different types of indexes in SQL Server 2012 Version?
Clustered
Nonclustered
Unique
Columnstore
Index with included columns
Index on computed columns
Filtered
Spatial
XML
Full-text
10. What is Index with included columns?
A nonclustered index that is extended to include nonkey columns in addition to the key columns.
11. Can you create a Non cluster index on primary key?
Yes, by default a clustered index is created on primary key. However, a noncluster index can be
created on Primary Key.
12. What is index Seek?
Index seek is an operation that only touches rows that qualify and pages that contain these qualifying
rows.
13. What is index Scan?
Index scan is an operation that touches every row in the table whether or not it qualifies.
14. What is Caching Mechanisms?
SQL Server avoids compilations of previously executed queries by using these four mechanisms to
make plan caching accessible:
Adhoc query caching
Autoparameterization
Prepared queries
Stored procedures or other compiled objects
15. How can you clear plan cache?
Executing DBCC FREESYSTEMCACHE clears the plan cache for the instance of SQL Server.
16. Give some examples of DBCCs related to SQL Server Cache?
DBCC FREESYSTEMCACHE
DBCC FREESESSIONCACHE
DBCC FREEPROCCACHE
17. What is Max Degree of Parallelism or MAXDOP?
If there are more than one processor or CPUs on a server where SQL server is running, SQL server
detects the best degree of parallelism, that is, the number of processors employed to run a single
statement, for each parallel plan execution.
18. How do I configure the Max Degree of Parallelism at the server level?
MAXDOP Setting can be configured at server level properties
And using exec dbo.sp_configure
19. How can I specify the Max Degree of Parallelism at the query level?
Use a MAXDOP hint to override the default server MAXDOP setting
CREATE NONCLUSTERED INDEX [IX_Address_StateID]
ON [Person].[Address] ([StateID] ASC)
WITH (MAXDOP=0)
GO
20. True or False – It is possible to correlate the Performance Monitor metrics with Profiler data in a single
SQL Server native product?
True – This functionality is possible with SQL Server Profiler.
21. What is a query plan and what is the value from a performance tuning perspective?
A query plan is the physical break down of the code being passed to the SQL Server optimizer. The
value from a performance tuning perspective is that each component of the query can be understood
and the percentage of resource utilization can be determined at a micro level. As query tuning is
being conducted, the detailed metrics can be reviewed to compare the individual coding techniques
to determine the best alternative.
22. True or False – It is always beneficial to configure TempDB with an equal number of fixed sized files as
the number of CPU cores.
False, this is just a myth.
23. Explain the NOLOCK optimizer hint and some pros\cons of using the hint?
The NOLOCK query hint allows SQL Server to ignore the normal locks that are placed and held for a
transaction allowing the query to complete without having to wait for the first transaction to finish
and therefore release the locks. This is one short term fix to help prevent locking, blocking or
deadlocks. However, when the NOLOCK hint is used, dirty data is read which can compromise the
results returned to the user.
24. Can you please name different approaches to capture a query plan.
SHOWPLAN_TEXT
SHOWPLAN_ALL
Graphical Query Plan
dm_exec_query_optimizer_info
dm_exec_query_plan
25. Name three different options to capture the input (code) for a query in SQL Server.
DBCC INPUTBUFFER
fn_get_sql
dm_exec_sql_text
26. Explain a SQL Server deadlock
A deadlock is a situation where 2 spids have data locked and cannot release their lock until the
opposing spid releases their lock. Depending on the severity of the deadlock, meaning the amount of
data that is locked and the number of spids that are trying to access the same data, an entire chain of
spids can have locks and cause a number of deadlocks, resulting in a performance issue.
27. How a deadlock can be identified?
Deadlocks can be identified by Profiler in either textual, graphical or XML format.
28. How deadlock is a performance problem and some techniques to correct deadlocks?
Majorly Deadlocks are Database Design problem but they are a performance problem as well
because they can prevent 2 or more processes from being able to process data. A deadlock chain can
occur and impact hundreds of spids based on the data access patterns, number of users, object
dependencies, etc. Deadlocks could require a database design change, T-SQL coding change to access
the objects in the same order, separating reporting and OLTP applications, including NOLOCK
statements in SELECT queries that can accept dirty data, etc.
29. Please explain why SQL Server does not select the same query plan every time for the same code (with
different parameters) and
The query plan is chosen based on the parameters and code being issued to the SQL Server
optimizer. Unfortunately, a slightly different query plan can cause the query to execute much longer
and use more resources than another query with exactly the same code and only parameter
differences.
30. How SQL Server can be forced to use a specific query plan.
The OPTIMIZE FOR hint can be used to specify what parameter value we want SQL Server to use
when creating the execution plan.
Dynamic management views and functions return internal, implementation-specific state data. Their
schemas and the data they return may change in future releases of SQL Server. Therefore, dynamic
management views and functions in future releases may not be compatible with the dynamic
management views and functions in this release. For example, in future releases of SQL Server, Microsoft
may augment the definition of any dynamic management view by adding columns to the end of the
column list. We recommend against using the syntax SELECT * FROM dynamic_management_view_name
in production code because the number of columns returned might change and break your application.
When you execute one of these DBCC commands, the Database Engine creates a database snapshot and
brings it to a transactionally consistent state. The DBCC command then runs the checks against this
snapshot. After the DBCC command is completed, this snapshot is dropped.
Sometimes an internal database snapshot is not required or cannot be created. When this occurs, the
DBCC command executes against the actual database. If the database is online, the DBCC command uses
table-locking to ensure the consistency of the objects that it is checking. This behavior is the same as if
the WITH TABLOCK option were specified.
An internal database snapshot is not created when a DBCC command is executed:
• Against master, and the instance of SQL Server is running in single-user mode.
• Against a database other than master, but the database has been put in single-user mode by using the
ALTER DATABASE statement.
• Against a read-only database.
• Against a database that has been set in emergency mode by using the ALTER DATABASE statement.
• Against tempdb. In this case, a database snapshot cannot be created because of internal restrictions.
4) Can you explain DBCC CheckDB?
1. Object Integrity
2. Linkages for text, ntext, and image pages
3. Index and data pages are correctly linked.
4. Indexes are in their proper sort order.
5. Pointers are consistent.
6. The data on each page is reasonable (Allocation Checks).
7. Page offsets are reasonable.
DMVs can be used in the gathering of baseline information and for diagnosing performance problems.
Few important dmvs are:
1. sys.dm_os_performance_counters
2. sys.dm_db_index_physical_stats
3. sys.dm_db_index_usage_stats
6) Please explain DMV Categories?
Category Prefix
Common Language
Runtime (CLR) Sys.dm_clr_*
Database Sys.dm_db_*
Indexing Sys.dm_db_index_*
Execution Sys.dm_exec_*
I/O Sys.dm_io_*
Replication Sys.dm_repl_*
Transactions Sys.dm_tran_*
Sys.dm_xe_*
SQL Server Extended
Events Sys.dm_cryptographic_*
Sys.dm_provider_*
Security Sys.dm_audit_*
7) What are all the SQL Server Dynamic Management Views(DMV) and Dynamic management
functions(DMF) available in SQL Server?
Use below query to list out all available DMVs present in a SQL Installation :-
SELECT name, type, type_desc FROM sys.system_objects WHERE name LIKE ‘dm[_]%’
ORDER BY name
11) While viewing activity on SQL Server , for example, sp_who2 – the status column displays
different states – RUNNABLE – SUSPENDED – RUNNING. Could you explain the difference?
Some background information on the SQL Schedulers , will make understanding the RUNNABLE –
SUSPENDED – RUNNING model clearer.
Schedulers are made up of three parts . A thread cycles though these three parts
1) Processor
2) Waiter list – threads waiting for resources. Use Sys.dm_os_waiting_tasks to view resource waits for the
resources
3) Runnable – thread has all the resources and waiting for the processor. Explore runnable status with
the sys.dm_os_schedulers and sys.dm_exec_requests DMVs
This leads us into the RUNNABLE – SUSPENDED – RUNNING
1) RUNNING – thread is executing on the server
2) SUSPENDED – thread is waiting for resources to become available.
3) RUNNABLE – the thread is waiting to execute on the processor
18) Which DBCC command is used to store the Procedure cache related information?
DBCC PROCCACHE – This command will show you information about the procedure cache and how much
is being used.
20) How can you check if any transaction is running on a database or not?
We can use DBCC OPENTRAN to check any running transaction on the database. It is one of the most
commonly used DBCC command along with DBCC CHECKDB, DBCC SHRINKFILE, DBCC
SQLPERF(logspace) etc.
21) Can anyone predict how long DBCC Checkdb will run on any database?
As far as estimating how long DBCC CHECKDB will take to run on a given database, it’s very difficult to tell
because there are so many variables involved. The following are some factors that affect DBCC
CHECKDB’s run time:
• The size of the database. This one’s not so obvious—it’s not the size of the database that matters, it’s
the amount of data that’s in it.
• The load on the system. DBCC CHECKDB is extremely resource hungry—I like to say it’s the most
resource-intensive operation you can run on SQL Server. Therefore, if the server is already heavily
loaded, DBCC CHECKDB will be competing for resources and will take a lot longer to run.
• The capabilities of the system. If the database being consistency checked is very large and structurally
complicated, but the server and/or I/O subsystem are heavily underpowered, this will have a knock-on
effect on the ability of the server to provide the resources DBCC CHECKDB needs, slowing it down.
• The options specified. If the WITH PHYSICAL_ONLY option is specified, the amount of processing that
DBCC CHECKDB does is drastically cut down, which usually leads to a significant reduction in run time.
• The complexity of the database schema. The more features that you use in the database, the more
structures there are to be consistency checked, so DBCC CHECKDB will take longer to run.
• The corruptions that are found. Some corruptions require deeper reprocessing of data to figure out
exactly where the corruption is. This can lead to a much longer run time for DBCC CHECKDB.
• The tempdb configuration. DBCC CHECKDB uses a lot of memory to store intermediate consistency
checking data, and that storage usually spills out to the tempdb database. If tempdb isn’t configured well,
it can be a bottleneck for DBCC CHECKDB and slow it down.
As you can see, there are too many factors involved to be able to make a good guess. The best way to
know how long DBCC CHECKDB will take is to run it.
22) What is the effect of DBCC CHECKDB and DBCC DBREINDEX on the Transaction log?
DBCC DBREINDEX is an offline operation is used to rebuild the indexes of a table dynamically. This
operation requires enough space in the data files. If the space is not enough DBCC DBREINDEX may be
unable to rebuild the indexes.
DBCC CHECKDB is used to produce a consistent view of the data by performing a physical consistency
check on indexed views, validating integrity of the indexes, objects etc. in earlier versions of SQL, this
required locking. Newer versions involve reading the transaction log of the oldest active transaction.
REDO and UNDO of the transactions affect the volatile changes to available free space.
Helps to find out the queries that are causing memory or CPU pressure on your system
25) How are DMV’s and DMF’s changing the memory consumptions of SQL Server? consider the
dm_exec_* which store the results of the current workload.
DMV’s are in-memory structures and are anyway’s used by SQL Server internally. It is with SQL Server
2005 that we started exposing them in an official manner rather than doing bit-manipulations with some
DBCC commands. Hence there is nothing to be worried about the load or memory consumptions. It is not
as alarming as you think.
26) Which DMV give me query plan or I will use old method to find query plan?
Below DMVs can be used to provide query plan related information :-
sys.dm_exec_query_stats
sys.dm_exec_sql_text
sys.dm_exec_query_plan
sys.dm_db_file_space_usage
sys.dm_db_partition_stats
sys.dm_db_session_space_usage
sys.dm_db_task_space_usage
30) Which DMVs are useful to gather information about database mirroring :-
sys.dm_db_mirroring_connections
sys.dm_db_mirroring_auto_page_repair
31) What are the most important DMVs\DMFs from a DBA perspective.
Execution Related
• sys.dm_exec_connections
• sys.dm_exec_sessions
• sys.dm_exec_requests
• sys.dm_exec_cached_plans
• sys.dm_exec_query_plans
• sys.dm_exec_sql_text
• sys.dm_exec_query_stats
Index Related
• sys.dm_db_index_physical_stats
• sys.dm_db_index_usage_stats
SQL Server Operating System
• sys.dm_os_performance_counters
• sys.dm_os_schedulers
• sys.dm_os_nodes
• sys.dm_os_waiting_tasks
• sys.dm_os_wait_stats
I/O Related
• sys.dm_io_virtual_file_stats
One of the most underrated commands, one can find in SQL is DBCC PAGE command. We are saying this
not because, the command is not worthy enough to be used, but because it is an undocumented internal
command of SQL Server. You will not be able to find much info about this command in online books as
well. Therefore, due to lack of information, most SQL users do not use this command.
In this write-up, we will enlighten the users about the use of DBCC PAGE command and the process to
analyze SQL Server Table and index data with this command.
As discussed earlier, since DBCC PAGE is an undocumented command, if the users want to get the results
of this command in their query output window, traceflag 3604 needs to be turned on.
1- used for printing page header, per-row hex dumps and page slot array dump
The output obtained after the DBCC PAGE command is run, is divided into 4 sections-
Buffer: The buffer section displays the information about the buffer that manages a page.
Page Header
Data
Offset Table
DBCC PAGE displays the data in rows and in the group of 4 bytes at a particular time. Within every group,
the bytes are arranged in a reverse order. Therefore, the first group will be something like byte 3, byte 2,
byte 1, and byte 0.
For accessing the rows of data by using the DBCC PAGE command, the users require a page address for
the data page. This can be done by taking a value from the column that is called from the sysindexes table.
If a row of a table has a value 0, then it means that the table is a heap and if the value is 1, then the table
possesses a clustered index.
The output of the above query will be a hexadecimal value, which when converted will give the file and
the page address. It is to be noted that SQL Server 7.0 does not guarantee that the first column of
sysindexes will identify the first page of the table in an accurate manner.
Conclusion
The DBCC PAGE is an internal command in SQL Server that is not documented. It enables the users to
analyze and know about the table and index data of SQL Server database in an effectual manner.