Advanced psql Features
1. Writing Output to File
\o /tmp/result.txt
SELECT * FROM orders;
\o -- back to stdout
2. Reading Commands from File
\i script.sql
\ir relative_script.sql
3. Executing Shell Commands
4. Conditional Execution
\if :{?prod}
\echo 'in production'
\elif :debug
\echo 'debug'
\else
\echo 'default'
\endif
5. Using Expressions in Conditionals
SELECT count(*) AS n FROM orders \gset
\if :n
\echo 'orders exist'
\endif
6. Showing Previous Query
\p -- print current query buffer
\g -- re-execute query buffer
\r -- reset query buffer
7. Displaying Query Buffer
\p
\w buffer.sql -- write buffer to file
8. Executing from Buffer
\g -- execute current buffer
\gx -- execute with \x toggle
9. Using psqlrc Configuration
# ~/.psqlrc
\set QUIET 1
\set HISTSIZE 10000
\pset null '(null)'
\timing on
\set PROMPT1 '%n@%/%R%# '
\unset QUIET
10. Setting Prompt
| Token | Expands To |
| %n | User |
| %/ | Database |
| %R | =, *, !, etc. |
| %x | TX state ('*' active, '!' aborted) |
| %M | Host |
11. Setting Null Display
12. Using Watch
SELECT count(*) FROM orders WHERE status='new';
\watch 5 -- re-run every 5 seconds
13. Exiting psql
\q
exit
quit -- all work in PG 11+