psql Basics
7 examples for daily psql usage - 5 basic and 2 intermediate.
Search across all documentation pages
7 examples for daily psql usage - 5 basic and 2 intermediate.
psql --version # match major to server when possiblepostgresql-client-18 (or your target major) on admin workstations.~/.pgpass or a secrets manager - not shell history.psql "postgresql://app_ro:****@db.internal:5432/myapp?sslmode=require"
# or
psql -h db.internal -p 5432 -U app_ro -d myappsslmode=require enforces TLS on the wire.\c)\c myapp
\c myapp app_ro
\conninfo\c dbname [username] opens a new connection in the same psql session.\conninfo prints host, port, user - verify before destructive work.search_path unless set per-role.Related: psql Scripting - non-interactive runs
\dt, \d)\dt public.*
\d+ orders
\dn
\df public.*\d+ adds storage size and description comments.\dn lists schemas - critical in multi-tenant layouts.search_path.\timing)\timing on
SELECT count(*) FROM orders WHERE created_at > now() - interval '7 days';EXPLAIN (ANALYZE, BUFFERS) for plan-level detail.Related: Index & Query Rules - EXPLAIN before merge
LIMIT Habits-- Always bound exploratory SELECTs on large tables
SELECT id, status, created_at
FROM orders
ORDER BY created_at DESC
LIMIT 50;
-- Avoid accidental full scans
SELECT * FROM events LIMIT 100; -- still reads if no index-friendly planLIMIT without ORDER BY returns an arbitrary slice.SELECT * on wide JSONB rows transfers megabytes per row.\x on
SELECT * FROM pg_stat_activity WHERE pid = pg_backend_pid();
\a
\t
SELECT setting FROM pg_settings WHERE name = 'max_connections';\x) helps wide catalog queries.\a aligned off + \t tuples only = script-friendly TSV.\pset footer off removes row counts for machine parsing.BEGIN READ ONLY;
SELECT sum(amount) FROM payments WHERE paid_at >= current_date;
ROLLBACK;# Connect explicitly as read-only role
psql -U app_ro -d myapp -c "SELECT 1"BEGIN READ ONLY blocks accidental UPDATE in the same transaction.INSERT/UPDATE/DELETE on production.psql_prod='psql -U app_ro ...' in approved jump boxes only.Stack versions: This page was written for PostgreSQL 18.4 (stable 18, maintenance 17), pgvector 0.8+, PgBouncer 1.x, Patroni 3.x, and PostGIS 3.5+.
Reviewed by Chris St. John·Last updated Jul 19, 2026