How to Find Recent Executed Queries in SQL Server? – Interview Question of the Week #087

Interviews can surprise both sides. I was helping an organization hire when a candidate challenged the interviewer over a question about recently executed SQL Server queries. The interviewer expected a DMV query. The candidate knew it, but also knew its limit.

Recent impressions remain in wet clay while older marks have been smoothed away

Can a DMV show every query that ran?

No. The following query is a useful look at recently executed statements with cached plans. It is a starting point for diagnosis, not a complete execution history.

SELECT TOP (50) txt.text AS BatchText,
       qs.execution_count,
       qs.creation_time,
       qs.last_execution_time
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS txt
ORDER BY qs.last_execution_time DESC;

The DMV reports completed query executions whose plans remain in cache, not every currently running request. On SQL Server 2022 and later, the query generally requires VIEW SERVER PERFORMANCE STATE; older versions use VIEW SERVER STATE. The interviewer’s original script used the same sys.dm_exec_query_stats and sys.dm_exec_sql_text pair. The candidate’s objection was correct: the statistics belong to cached plans. A plan can be evicted, recompiled, or removed when SQL Server restarts. Its count begins with that cached entry, not at the birth of the database. A row here indicates useful recent activity; an absent row does not prove the query never ran.

Also notice that txt.text is the batch text. One batch can contain several statements, so use statement offsets or the execution plan when you need to attribute cost to a particular statement.

If you need a history that survives a plan leaving cache, set up the appropriate collection before the incident. Query Store, where enabled and retained, can help with statement history. An Extended Events session can record events chosen for a specific investigation. Neither should be described as a record of everything without checking its configuration and retention.

I agreed with the candidate. The DMV query was a good answer only after stating what it could and could not prove. That distinction matters more in a performance investigation than memorizing the view’s name.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Cache, SQL DMV, SQL Scripts, SQL Server
Previous Post
How to Get Started with SQL Server 2016? – Interview Question of the Week #086
Next Post
How to Hide Stored Procedure’s Code? – WITH ENCRYPTION – Interview Question of the Week #088

Related Posts

4 Comments. Leave new

  • How to find out recently executed queries with login user and system name (Client Name) ?

    Reply
  • Is there a way to do this on sql server 8.0.2039 // Ms Sql Server Standard // on MS Win NT 5.2 (those are the stats of the sql server I’m running on) That server does not like Cross Apply pretty much EVER and it also does not like and MAX when using other types of these “get last executed query” / “find all the queries I ran in the last 24 hours” code snippets.

    The other sql server (where i do NOT need to run this / where it works is) is 11.0.5388 // ms sql server standard // windows nt 6.3 – but like i said these types of queries WORK there but that is NOT where I’m needing this.

    Thanks!

    Reply
    • have you considered upgrading? I think 8 is 2000 the cross apply was introduced later than that its already too late to be an early adopter of sql 2017, but if you at least upgraded to at least 2014, you would be able to run the query and benefit from the new cardinality estimator and more.

      Reply
  • Hi
    Please let me know how we add user name in the below query,I want user name as well in the below query.
    (which user run by which query),am not able to find the user name.

    select db_name(qp.dbid)as databasename,
    sql_text.text as query
    ,st.last_execution_time
    from sys.dm_exec_query_stats st
    cross apply sys.dm_exec_sql_text(st.sql_handle)as sql_text
    inner join sys.dm_exec_cached_plans cp
    on cp.plan_handle=st.plan_handle
    cross apply sys.dm_exec_query_plan(cp.plan_handle) as qp
    where st.last_execution_time >=dateadd(month,-1,getdate())
    order by st.last_execution_time desc;

    Thanks,
    Suma

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.