in Databases

Postgres \e Command

One of the things I struggled with when I started using Postgres is writing queries on the psql command line utility. Once I went to the next line with an enter press I couldn’t go back and change something without ensuring there is an error in my SQL, and then pressing the up arrow to get everything back as a single string that I could then edit. Even dealing with queries in a single string means you have to move around without the tools of your typical favorite editor.

The “\e” command will open the last statement run, or the current statement in the systems default editor. For me, this is Vim, and that works out great as that is my editor of choice. If you prefer another editor, you should be able to set an environment variable as shown below in your .bashrc file. Obviously, replace the path with the path to your editor of choice. This will ensure it is run on every login. For your current session you can just run the below export one time and it will use that editor choice until you log out.

export PSQL_EDITOR=/usr/bin/vim

After you type \e and hit enter you are launched into the editor with the current query, or if entering it when not in a current query you will open the last query. You can make whatever changes you want, and when you write and quit (“:wq” when using vim) you will leave the editor and be returned to the Postgres CLI and your query will have been executed.

Information about \e from the help command:

Query Buffer \e [FILE] [LINE] edit the query buffer (or file) with external editor

Write a Comment

Comment