SQL
query history
database management
SQL commands
database queries

SQL command to display history of queries

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

There is no single portable SQL command that shows query history across all databases. Query history depends on the database engine, its logging configuration, and whether you want currently running statements, aggregated statistics, or a full audit trail of past queries.

First Decide What "History" Means

People use the phrase query history for several different things:

  • queries running right now
  • recently executed queries with timing and text
  • aggregated statement statistics over time
  • full audit logs for compliance

Those are different data sources. A system view that shows active sessions is not the same as a durable log of past statements.

PostgreSQL: Current Activity and Aggregated History

For currently active queries in PostgreSQL, pg_stat_activity is the first place to look.

sql
1SELECT pid,
2       usename,
3       state,
4       query_start,
5       query
6FROM pg_stat_activity
7WHERE state <> 'idle'
8ORDER BY query_start DESC;

This shows what is running now, not a permanent history.

For repeated historical analysis, PostgreSQL commonly uses pg_stat_statements.

sql
1SELECT query,
2       calls,
3       total_exec_time,
4       mean_exec_time
5FROM pg_stat_statements
6ORDER BY total_exec_time DESC
7LIMIT 20;

That view gives aggregated statistics by normalized statement. It is extremely useful for performance tuning, but it is still not a line-by-line log of every query ever executed.

MySQL: Logs Matter More Than a Built-In History Table

In MySQL, full query history usually comes from logs, not from a universal history SQL view.

The general query log can be enabled and directed to a table:

sql
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';

Then inspect it:

sql
1SELECT event_time,
2       user_host,
3       command_type,
4       argument
5FROM mysql.general_log
6ORDER BY event_time DESC
7LIMIT 50;

This gives a real statement history, but enabling the general log adds overhead. It is better for short-term troubleshooting than continuous high-volume production use.

MySQL also has the slow query log, which is more practical when your goal is performance investigation rather than every statement.

SQL Server: Use Dynamic Management Views

SQL Server exposes useful query information through dynamic management views.

For recent cached statements:

sql
1SELECT TOP 20
2       qs.execution_count,
3       qs.total_worker_time,
4       qs.total_elapsed_time,
5       st.text
6FROM sys.dm_exec_query_stats qs
7CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
8ORDER BY qs.total_elapsed_time DESC;

This is valuable for performance work, but it reflects cached query information, not a guaranteed durable history. Cache eviction can remove entries.

For currently running requests:

sql
1SELECT session_id,
2       status,
3       start_time,
4       command
5FROM sys.dm_exec_requests;

Again, that is current activity, not a full historical log.

SQLite and Smaller Engines Often Have No Built-In History

Some databases, especially embedded engines like SQLite, do not maintain a server-side query history at all. In those systems, history usually comes from:

  • application logging
  • ORM logging
  • shell history in a client tool
  • custom audit tables

So if you are looking for a pure SQL command in SQLite, the real answer is usually that no such built-in command exists.

Client History Is Not Server History

Some tools such as psql, MySQL shells, or GUI clients remember your previous commands locally. That is helpful for convenience, but it is not the same as database query history.

A local client history can tell you what one operator typed. It cannot tell you what other applications or users executed on the server.

Use the Right Source for the Question

If you want to know what is slow, use performance views or slow-query tooling.

If you want to know what is running now, use activity views.

If you need a full audit trail, turn on appropriate logging or auditing features before the event happens.

This distinction matters because many teams discover too late that the database cannot show past statements it was never configured to record.

Example: Build a Lightweight Audit Table

If your use case is narrow, an application-side audit table can be enough.

sql
1CREATE TABLE query_audit (
2    id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
3    executed_at TIMESTAMP NOT NULL,
4    executed_by VARCHAR(100) NOT NULL,
5    statement_text TEXT NOT NULL
6);

Then the application records key administrative statements explicitly. This is not a replacement for database-native auditing, but it is useful for controlled workflows.

Performance and Security Considerations

Full statement logging can expose sensitive data and increase storage and runtime cost. Before enabling it, decide:

  • how long logs should be retained
  • who can read them
  • whether parameters or literals may contain secrets
  • whether you need all statements or only slow and failed ones

A logging strategy that is too broad often becomes unusable noise.

Common Pitfalls

Expecting one universal SQL command to work across PostgreSQL, MySQL, SQL Server, and SQLite. Query history is engine-specific.

Confusing active-session views with durable historical logs. They answer different questions.

Assuming history exists even though logging was never enabled. Many systems do not store past queries by default.

Using general logging permanently in a high-volume system without considering overhead and sensitive data exposure.

Relying on client shell history when the real question is server-side activity.

Summary

  • There is no single cross-database SQL command for query history.
  • PostgreSQL, MySQL, and SQL Server expose different views and logs for activity and past queries.
  • Some tools show current activity, while others show aggregated or logged history.
  • Full historical visibility usually requires logging or auditing to be enabled ahead of time.
  • Choose the source based on whether you need current sessions, performance stats, or a real audit trail.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.