Friday, July 19, 2013

Query to find Costly Queries in sql server

Today i found one script which shows top 50 costly queries. It takes those queries who consumes most CPU.

SELECT TOP 50
 [Average CPU used] = total_worker_time / qs.execution_count,
 [Total CPU used] = total_worker_time,
 [Execution count] = qs.execution_count,
 [Individual Query] = SUBSTRING (qt.text,qs.statement_start_offset/2,
         (CASE WHEN qs.statement_end_offset = -1
            THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
          ELSE qs.statement_end_offset END -
qs.statement_start_offset)/2)
,[Parent Query] = qt.text
,DatabaseName = DB_NAME(qt.dbid)
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
ORDER BY [Average CPU used] DESC;


Wednesday, July 10, 2013

Script to get the number of rows in all tables

Here is the script to get the list of tables with number or rows in each table [SQL Server 2008]. This will help you when you want to know which tables are heavy. When it comes to performance issue this query is very helpful. Recently I find this query from here thanks to Jeremy Jameson. I added this query in this post as i want to make it handy.


SELECT sysobjects.Name , sysindexes.Rows 
FROM 
sysobjects 
INNER JOIN sysindexes 
ON sysobjects.id = sysindexes.id 
WHERE 
type = 'U' 
AND sysindexes.IndId <
ORDER BY 
 2 desc


It will produce the result as shown below.

Table1 50000

Table2 45000

Table3 40000

Table4 10000