brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: \e in psql opens your last PostgreSQL query in an editor

Postgresql
~/tips/tip-postgresql-psql-edit-query

appdb=# \e

Edits a long query in your own editor and runs it when you save and quit.

Fixing one typo in a 20-line query at the psql prompt means arrowing through the whole thing. psql can hand the query to a real editor.

appdb=# \e

With an empty query buffer, \e takes the query you ran last and opens it in your editor. Fix it, save and quit, and psql runs the result right away if it ends with a semicolon. Without a semicolon it waits in the buffer, so you can still check it before you send it with ; or \g.

If you started typing and got lost, \e takes the unfinished query instead. \e migrate.sql opens a file, and \ef my_function opens a function’s full definition for editing in the same way.

The editor comes from PSQL_EDITOR, then EDITOR, then VISUAL, and falls back to vi on Unix. If vi surprises you, set one of them in your shell profile:

export PSQL_EDITOR=nano

One behavior I find surprising: quitting without saving clears the query buffer instead of keeping the old query, and the docs describe it that way. Psql reads the whole edited buffer as one line, so a meta-command such as \x in the middle of it takes the rest as its arguments. Keep backslash commands out of what you edit, and use \i file.sql for scripts with them.

Further reading: psql (\e and environment)

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link