Can I get query history in SQL Server?
Solved Email & Outlook
BA
Barry Allen
June 8, 2020
2 replies
12,470 views
Reviewed by moderators

Something updated rows it should not have last night and I need to know what ran. Is there a query history hiding in SQL Server somewhere?

SQL Server 2017, no auditing was configured in advance, which I suspect is the answer already.

Accepted Answer
Verified by David Taylor, Database Expert ยท Reviewed June 2020

Your suspicion is half right: there is no complete history without prior setup, but SQL Server keeps more residue than people expect. 2017 also puts one genuinely good option on the table for the future.

The residue, check it before it fades: the plan cache holds recently executed statements with their stats, queryable through sys.dm_exec_query_stats cross applied to sys.dm_exec_sql_text, ordered by last_execution_time. It survives since the last service restart only, evicts under memory pressure and shows statements rather than who ran them, but a distinctive UPDATE from last night frequently still sits in it. The default trace is the second residue, catching object alterations rather than data changes, relevant if the mystery includes schema.

The who question needs the transaction log while it lasts: an undocumented fn_dblog read is rough archaeology, and log reading tools reconstruct operations with session details from the log and its backups. Practical only while the relevant log records still exist, so if this is serious, secure the current log backups now before the chain rolls over.

The future, ten minutes of setup: enable Query Store on the database, ALTER DATABASE yours SET QUERY_STORE = ON, native since 2016, which persists query text, plans and runtime stats across restarts with SSMS reports on top. Pair it with a server audit or a lightweight Extended Events session capturing statements with session context if who matters as much as what, and the next mystery update investigates itself in minutes instead of forensics.

The UPDATE was still in the plan cache, matched its text to a scheduled task nobody remembered writing. Query Store is on as of this morning and log backups secured for the record. Thorough answer, saved a bad week.