You can get a deleted query back in PostgreSQL only if a copy of its text still exists somewhere outside the database. PostgreSQL does not keep a built-in history of executed statements. Once a query finishes and its session ends, the server retains no text you can query later. Your real options are the client-side history file, server logs with statement logging enabled, a saved script or migration file, or a backup that captured one of those artifacts. If none of those exist, the statement text is gone, and you will need to reconstruct it from its effects on data.

That boundary matters because most people asking this question picture an undo button for SQL. There isn't one. What follows is the practical search order, how each source behaves, and how to improve your odds permanently.

Fixed write-ahead log or rolling back a transaction won't recover query text

Two recovery routes get suggested constantly and both fail for this specific goal. Understand why, so you don't waste an afternoon.

The write-ahead log (WAL) records page-level changes: which bytes in which block were modified. It does not store the SQL you typed. Point-in-time recovery replays those changes to rebuild a consistent database state, but it cannot hand you back a SELECT you ran last Tuesday. A SELECT that changed nothing leaves no WAL trace at all.

ROLLBACK works only before you commit. Once COMMIT returns, the transaction is durable, and rolling back is no longer on the table. For an uncommitted statement still inside an open transaction, rollback or a SAVEPOINT is your recovery method, and the query text never left memory anyway.

The distinction to hold onto: PostgreSQL helps you recover data states, not the text of statements.

Read the history file from psql first

psql, the standard command-line client, writes every completed statement to a history file by default. This is the single most likely place your query still lives.

The file is typically at ~/.psql_history on Linux and macOS. On Windows it usually sits under %APPDATA%\postgresql\psql_history. The path can be overridden with the PSQL_HISTORY environment variable or the \set HISTFILE command, so if the default location is empty, check whether a custom path was configured.

Requirements before you look: the statement must have been typed into an interactive psql session, and it must have completed successfully. Abandoned input at the prompt is normally not saved on exit.

Steps to retrieve it:

1: Open a terminal as the same operating-system user who ran the original session. The file is per-user. 2: List the file and check its modification time, for example ls -l ~/.psql_history. 3: Search it with context using grep -n -i "keyword" ~/.psql_history, where the keyword is a table name, column, or fragment you remember. 4: Open the surrounding lines with sed -n 'START,ENDp' ~/.psql_history using the line numbers grep returned, or open the file in an editor and jump to that line. 5: If the file doesn't exist, confirm psql actually wrote it: run psql, execute one harmless statement such as SELECT 1;, exit with \q, and check the file again.

Success check: the full statement text appears, and you can paste it back into a session. If the search finds nothing, the statement may have been run in a different client, by a different user, or with history disabled through HISTCONTROL or an unset HISTFILE.

One caveat: psql history is appended per session, and there's no built-in timestamp per entry, so ordering across sessions depends on file position only.

If history is empty, check server logs for logged statements

The PostgreSQL server can log every statement it receives, but this is off by default because the volume is heavy. If your installation had it enabled, the log is a durable, timestamped record that survives long after the client closes.

The relevant settings live in postgresql.conf and can be inspected with SHOW log_statement;. Values are none (the default), ddl, mod, and all. Only all captures SELECT statements; mod captures data-modifying statements and ddl captures schema changes. A related setting, log_min_duration_statement, logs any statement running longer than a threshold in milliseconds, which can capture a slow query even when log_statement is none.

Steps:

1: Connect and run SHOW log_statement; and SHOW log_min_duration_statement; to learn whether logging was even possible. 2: Find the log destination with SHOW log_destination; and SHOW logging_collector;. If the collector is on, logs land in the directory named by SHOW log_directory;, relative to the data directory. 3: Search the log files for your fragment, for example grep -n -i "fragment" /var/log/postgresql/*.log, adjusting the path to your distribution. 4: Read the statement as the server received it, including the timestamp and session details.

Success check: the log entry shows the statement text with a time that matches when you ran it. Failure handling: if log_statement shows none and log_min_duration_statement shows -1, no statement logging happened, and there's nothing to find in the log for that period.

One practical limit: log files rotate and are frequently purged by retention policies, so this route is time-sensitive. If retention keeps 7 days of logs, a query from three weeks ago is already gone.

Recover from saved scripts, migrations, and client artifacts

Sometimes the query was never purely ephemeral. Check these places before concluding it's lost:

Version control. A .sql file, a migration in Flyway or Liquibase, or a notebook committed to Git may contain the exact text. Search the repository history, including deleted-file history, with git log -S "fragment" --all to find commits that added or removed the string. GUI client history. Tools like pgAdmin, DBeaver, and DataGrip keep their own query histories and open-editor recovery. pgAdmin stores query history in its configuration database; DBeaver and DataGrip keep history in per-user config directories. Open the tool's query history panel or its own history viewer. Application logs. An ORM or application framework may log the SQL it generated, often at debug level. This is your best hope for a query the application issued rather than you. Shell history. If you piped a query into psql -c "..." from a shell, ~/.bash_history or ~/.zsh_history may hold the whole command.

Success check: you locate text you can verify, such as matching table and column names. Beware that application-generated SQL often differs from what you'd type by hand, so treat it as a reconstruction source rather than an exact match.

When nothing was recorded, reconstruct the query from evidence

If no text source exists, the statement is unrecoverable as text. You can still rebuild an equivalent query from its observable footprint, and this is where PostgreSQL's own catalogs help.

If the query was a SELECT, look for indirect records: pg_stat_statements (when the extension is installed) stores normalized query text with execution counts, and pg_stat_activity shows currently running statements. Both are imperfect. pg_stat_statements normalizes literals into placeholders, so you get the query shape, not your exact parameters. If the statement is still running, pg_stat_activity gives you the live text. Neither recovers a finished statement that was never logged.

If the query modified data, examine the tables it touched. Constraints, updated_at columns, audit triggers, or a change-data-capture tool may show when and how rows changed, which lets you infer the filter conditions. Compare current values against a backup taken before the event to see the delta.

For a schema change, query information_schema or pg_catalog for the affected objects' definitions and reconstruct the DDL from the current structure. For example, \d+ table_name in psql shows columns, types, defaults, and constraints you can express as a fresh CREATE or ALTER.

This is reconstruction, not recovery. Label it as such to yourself and anyone relying on the output, and check the rebuilt query against the data before trusting it.

Reach for a backup only when it captures a query source

A database backup helps here only indirectly. A logical dump holds schema and data, not the history of statements you typed. Selecting the dump cannot give you back a SELECT.

The exception is when a backup image includes the whole server filesystem or a volume that held ~/.psql_history, application logs, or saved scripts. In that case, restoring or mounting that backup can recover the file that holds the text. For a managed database service, check whether the provider's backup or export includes client-side artifacts; usually it does not, because backups capture the database, not your workstation.

Boundary condition: if the only surviving copy is inside a busy production backup and you must extract a single file, this becomes a recovery-engineer task. Stop and involve your DBA or platform team rather than experimenting on production data.

Prevent the next loss by turning on a record before you need it

The real fix is to make the query text durable going forward. These measures cost little and remove the panic.

Keep psql history enabled and back the file up. Ensure HISTFILE is set, and consider a periodic copy of ~/.psql_history into your notes or version control. Purge old entries rarely, and never in the middle of debugging. Enable statement logging selectively. Setting log_statement = 'ddl' or 'mod' captures schema and data changes without the volume of 'all'. Use log_min_duration_statement to capture only slow queries. Confirm the change with SHOW log_statement; after applying it. Put important queries in files. A queries/ directory under version control turns one-off checks into reproducible artifacts. Run them with psql -f path/to/file.sql so the file is the record. Use an editor-integrated client that persists history. DBeaver, DataGrip, and pgAdmin each keep searchable histories; enable the feature and know where it lives. Install pg_stat_statements on servers you administer. It won't give exact parameters, but it preserves the shape of every statement, which is often enough to rebuild it.

Success check for the first measure: close your client, reopen it, and confirm the prior statement reappears in history.

A quick decision table for where to look

Source Holds exact text Survives session end Default state Best for
.psql_history Yes Yes On Interactive psql statements
Server log_statement Yes Yes, until log rotation Off (none) Timestamped audit of executed SQL
log_min_duration_statement Yes Until rotation Off (-1) Recovering slow queries
GUI client history Yes Yes Usually on pgAdmin, DBeaver, DataGrip users
Saved script or migration Yes Indefinitely Depends on practice Planned or repeated queries
pg_stat_statements Normalized shape Yes, if retained Off until installed Rebuilding a query's structure
pg_stat_activity Yes No On Running statements only
Database backup No (data and schema only) Yes N/A Recovering data, not query text

Read the "holds exact text" column as the gate. Any row marked No cannot answer the question, no matter how recent the backup.

What to tell a colleague when recovery fails

If a query is gone, say so plainly and shift to impact. Ask what the query changed. If it was read-only, the risk is low. If it modified data, compare the current table against a pre-event backup, and if the change was wrong, restore or reverse it. That's a data-recovery problem with known tools and real stakes, and it deserves a documented plan rather than ad-hoc experimentation on production.

If the missing query needs to be reproduced exactly, gather everything you remember about it and rebuild from the catalogs and evidence described above. Then save the rebuilt version to a file so it can't vanish twice.

If neither you nor a DBA can confirm the statement's effect on production data, stop and escalate to your data team before touching recovery options.

This article provides general educational information about PostgreSQL behavior and does not constitute a data-recovery guarantee or professional advice. Settings and file locations differ across PostgreSQL versions, operating systems, and managed services, so confirm them against your own installation and the official PostgreSQL documentation. For production data loss, consult your database administrator or the database vendor's support team. If you face an active outage or data-corruption emergency, contact your on-call platform or emergency support service immediately.