Sub topic 10
Customizing psql with a psqlrc File
Prerequisites and purpose
This chapter assumes that you can use a terminal, connect to PostgreSQL with psql, and write basic SQL. You should also know the difference between a database, schema, table, and column.
psqlrc is a configuration file that psql reads when it starts. It can apply your preferred display settings, prompt format, and error behavior to every interactive session. This avoids typing the same meta-commands repeatedly.
The usual location is:
- Linux and macOS:
~/.psqlrc - Windows:
%APPDATA%\postgresql\psqlrc.conf
The file is read for interactive and script sessions unless you start psql with -X. The -X option skips the startup file.
A practical psqlrc
Create or edit the file with your normal text editor:
\set ON_ERROR_ROLLBACK interactive
\x auto
\timing on
\pset null '(null)'
\pset pager on
\set PROMPT1 '%n@%/%R%# 'These settings have different purposes:
| Setting | Effect |
|---|---|
| `\set ON_ERROR_ROLLBACK interactive` | Rolls back only the current transaction after an error during interactive work |
| `\x auto` | Uses expanded display when a row is too wide |
| `\timing on` | Shows how long each SQL statement took |
| `\pset null '(null)'` | Displays SQL `NULL` values clearly |
| `\pset pager on` | Sends long output to a pager such as `less` |
| `\set PROMPT1 ...` | Shows the current user, database, prompt state, and transaction status |
After saving the file, start a new session and verify the settings:
psql -d mydbThen run:
\set
\pset
\conninfo\set lists psql variables. \pset displays output settings. \conninfo confirms which server and database you are using.
A startup file can contain SQL as well as psql meta-commands, but keep it focused on session behavior. Avoid queries that change data, create objects, or depend on one particular database. A query in psqlrc runs every time you connect, which can make scripts slow or fail on another server.
> callout warning > Do not place passwords, access tokens, or other secrets in psqlrc. Use a secure password file such as .pgpass with the required file permissions.
Making scripts predictable
Interactive preferences are not always suitable for automation. A script should produce stable output and stop when an important statement fails. Use -X to avoid a developer's personal settings:
psql -X -d mydb -f inspect.sqlYou can still set script-specific options inside inspect.sql:
\pset pager off
\pset format unaligned
\pset tuples_only on
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;Exercise
Exercise
Why might a deployment script use psql -X instead of relying on the user's normal psqlrc?
Show answer
The script should not depend on personal settings that could change its output, enable a pager, or alter its error behavior.