Code & computing / QUICK REFERENCE

psql terminal workflows: inspect and export PostgreSQL data

Use PostgreSQL psql safely: inspect connection and relations, format query output, export client-side CSV and run scripts with clear error handling.

62 entries

Identify context and connection

Show client version
psql --version

The psql client version can differ from the connected PostgreSQL server version. [1]

Open database as named user
psql -X -d csa_test -U csa_reader

In the local-only fixture, client defaults use the private PGHOST and PGPORT values. [1]

Show current connection
\conninfo

Displays database, connected user, server/socket and transport information. [1]

Inspect current database
SELECT current_database();

Identifies the active SQL database in the current session. [1]

Inspect current SQL user
SELECT current_user;

Identifies the active privilege context, which matters for read-only access. [1]

Inspect server version
SHOW server_version;

Reports actual PostgreSQL server version, not the psql executable version. [1]

Show connected user privileges
\du csa_reader

Displays attributes for the named fixture role; avoid exposing real-account metadata. [1]

List databases
\l

Lists databases visible to this role, not only the one connected. [1]

List database names
\l+

Requests the longer database list with additional metadata. [1]

Reconnect to same database
\c

Opens another connection using the previous parameters. [1]

Reconnect to named database
\c csa_test

Switches the database name without restarting the psql client. [1]

Inspect search path
SHOW search_path;

The relation lookup path influences unqualified table names. [1]

Set search path for session
SET search_path TO public;

Session configuration changes SQL name resolution without changing other sessions. [1]

Disable personal startup config
psql -X -d csa_test

Avoids hidden .psqlrc startup customizations during reproducible scripted work. [1]

Use error-stop for scripts
psql -X -v ON_ERROR_STOP=1 -d csa_test -f script.sql

Stops reading a script when a statement fails, rather than continuing silently. [1]

Explore schemas, relations and help

List visible tables
\dt

Lists ordinary user tables on the current search path. [1]

List tables in public
\dt public.*

Includes matching public schema tables regardless of current search path. [1]

Show table columns
\d demo_orders

Displays types, defaults, indexes and constraints for the named relation. [1]

Show expanded relation info
\d+ demo_orders

Adds details such as access methods, sizes and descriptions when available. [1]

List visible views
\dv

Lists views available on the current search path. [1]

List public views
\dv public.*

Identifies views in the public schema with an explicit pattern. [1]

List indexes
\di

Lists indexes visible on the configured search path. [1]

List schemas
\dn

Displays schema names accessible to the connected role. [1]

List functions
\df

Shows functions visible on the search path. [1]

Describe relation permissions
\dp demo_orders

Lists privileges for a particular relation where available. [1]

List large relations
\dt+

Includes additional relation information such as sizes and descriptions. [1]

Get psql command help
\?

Lists available backslash meta-commands for the installed client. [1]

Get SQL statement syntax help
\h SELECT

Shows syntax reference for SELECT within the terminal. [1]

Show last pending query buffer
\p

Displays the current unfinished SQL query before sending it. [1]

Clear pending query buffer
\r

Resets unfinished SQL text without modifying server data. [1]

Change display, not SQL results

Table output expanded on demand
\x auto

Displays long rows vertically when normal table output does not fit. [1][2]

Always expanded result view
\x on

Displays one row at a time with column labels. [1][2]

Return to regular results
\x off

Disables expanded record presentation. [1][2]

Enable CSV output format
\pset format csv

Formats subsequent SQL output as CSV-like records. [1][2]

Enable aligned output
\pset format aligned

Returns to the standard human-readable tabular results. [1][2]

Use unaligned output
\a

Toggles aligned/unaligned formatting for subsequent results. [1][2]

Hide result column names
\t on

Useful when feeding a known single value into another local tool. [1][2]

Restore headers and footers
\t off

Restores the normal tuples-only setting to off. [1][2]

Render missing values clearly
\pset null '<NULL>'

Replaces default blank display for SQL nulls in subsequent output. [1][2]

Disable interactive pager
\pset pager off

Prevents a terminal pager from interrupting automated inspection. [1][2]

Time statement execution
\timing on

Reports approximate client-observed execution duration per SQL command. [1][2]

Disable timing text
\timing off

Turns timing display off to keep copied output deterministic. [1][2]

Render line borders
\pset border 1

Changes how aligned results are displayed; it does not change the data. [1][2]

Show extra footer rows
\pset footer on

Restores query row counts when current output mode supports footers. [1][2]

Print plain values
psql -X -A -t -d csa_test -c 'SELECT count(*) FROM demo_orders;'

Produces a script-friendly count without decorative borders. [1][2]

Local files, safe queries and failures

Run read-only SQL from shell
psql -X -d csa_test -c 'SELECT city, amount FROM demo_orders ORDER BY id;'

Executes exactly one known SELECT command and exits. [1][3][2]

Run an SQL script
psql -X -v ON_ERROR_STOP=1 -d csa_test -f report.sql

Reads a local script file; only run scripts you have inspected. [1][3][2]

Execute SQL from an open session
\i ./report.sql

Includes and executes local file content in the current connection. [1][3][2]

Include file relative to script
\ir ./part.sql

Resolves include paths relative to the currently running script directory. [1][3][2]

Store query results locally
\o ./result.txt

Redirects subsequent psql command output to a local client-side file until \o resets it. [1][3][2]

Restore terminal output
\o

Resets psql output after writing an inspection file. [1][3][2]

Run buffered query
\g

Sends a prepared SQL buffer to the server, like a statement terminator. [1][3][2]

Save one SQL result to a variable
SELECT 42 AS answer \gset

Defines :answer from a single-row result, not a persistent database column. [1][3][2]

Print the stored value
\echo :answer

Reads a psql client-side variable previously created by \gset or \set. [1][3][2]

Export a read-only query as CSV
\copy (SELECT id,city,amount FROM demo_orders ORDER BY id) TO './orders.csv' WITH (FORMAT csv, HEADER true)

Writes the local client file; unlike SQL COPY TO a server path, it uses the client's permissions. [1][3][2]

Import CSV to an authorized scratch table
\copy scratch_orders FROM './orders.csv' WITH (FORMAT csv, HEADER true)

Reads client file into a scratch database table and **modifies** its rows; never target live tables without authorization. [1][3][2]

Show table totals
SELECT city, SUM(amount) FROM demo_orders GROUP BY city ORDER BY city;

In the fixture NY totals 43 and LA totals 17. [1][3][2]

Return only a known fixture row
SELECT city,amount FROM demo_orders WHERE id=2;

Demonstrated output is LA and 17 in the disposable test database. [1][3][2]

Test a file in one transaction
psql -X -v ON_ERROR_STOP=1 -1 -d csa_test -f script.sql

Runs supported statements in one transaction and rolls back on failure; transactional restrictions still apply. [1][3][2]

Check one-off SQL script status
echo $?

Immediately after psql, checks whether it succeeded; exit meanings depend on invocation and ON_ERROR_STOP. [1][3][2]

Exit interactive psql
\q

Leaves the terminal client without stopping the PostgreSQL server. [1][3][2]

Avoid executing shell in psql
\! and \copy ... PROGRAM invoke client shell commands

These are not needed for a read-only cheatsheet and can execute untrusted programs. [1][3][2]

Reserved placement, separate from reference controls. No ad network is active.

Updated PostgreSQL 18.6 (local tested client + isolated server)

Sources

  1. psql interactive terminal documentation (PostgreSQL 18) ↗
  2. SQL SELECT documentation (PostgreSQL 18) ↗
  3. SQL COPY documentation (PostgreSQL 18) ↗