Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Created April 25, 2025 14:21
Show Gist options
  • Save ststeiger/d41c4028840892a7bcea44f786ed21d7 to your computer and use it in GitHub Desktop.
Save ststeiger/d41c4028840892a7bcea44f786ed21d7 to your computer and use it in GitHub Desktop.
Get the last executed sql queries on MS-SQL
SELECT TOP 100
qt.text AS sql_query
,qs.last_execution_time
,qs.execution_count
,sd.name AS db
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
OUTER APPLY
(
SELECT CAST(pa.value AS int) AS db_identifier
FROM sys.dm_exec_plan_attributes(qs.plan_handle) AS pa
WHERE pa.attribute = 'dbid'
-- Each execution plan has many attributes (like dbid, object_id, set_options, etc.)
-- The DMV returns them as rows, not columns
) AS plan_attributes
LEFT JOIN sys.databases AS sd ON sd.database_id = plan_attributes.db_identifier
WHERE (1=1)
AND sd.database_id > 4 -- Filter out system DBs (IDs 1-4)
-- AND qs.last_execution_time >= DATEADD(week, -1, CURRENT_TIMESTAMP)
AND sd.name = 'YOUR_DB_NAME_HERE'
ORDER BY qs.last_execution_time DESC
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment