Databases · Beginner · 18 min
Get around PostgreSQL quickly with psql meta-commands and a .psqlrc
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7
You will connect to PostgreSQL 18 with a connection string and a private ~/.pgpass, find your way around with psql's backslash commands, export a query to CSV, write scripts that stop at the first error, and finish with a .psqlrc that gives you a clear prompt and history per database.
On this page
psql is the command-line client that ships with PostgreSQL, and it is the tool you will reach for every day: to check what is in a database, run a quick query, load a script or pull a report into a spreadsheet. Besides SQL, it understands its own commands that start with a backslash, called meta-commands. \dt lists tables, \d orders describes one, \x turns wide rows on their side. psql handles these itself; they never reach the server.
In this tutorial you create a small practice database for a delivery business with customers in five Nigerian cities, connect to it the way an application would, and work through the meta-commands that save the most time. You end with two files you keep: a private ~/.pgpass so you stop typing passwords, and a ~/.psqlrc that sets up every session the way you like it.
You need PostgreSQL 18 on Ubuntu 26.04, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19.0 was released on 19 November 2026; the commands here are expected to work the same in its psql, but this tutorial was checked on 18.
Step 1 · Create a role and a database to practise on
Create a login role called tour and a database called shop that it owns. --pwprompt asks for the new role's password twice, so the password never appears in your shell history or the process list. Pick a strong one and keep it to hand for the next step.
sudo -u postgres createuser --pwprompt toursudo -u postgres createdb -O tour shoptour is an ordinary role, not a superuser. Owning shop gives it everything it needs inside that one database, which is the right shape for an application account too.
Check it worked
sudo -u postgres psql -c "SELECT datname, pg_get_userbyid(datdba) AS owner FROM pg_database WHERE datname = 'shop';"One row comes back: shop owned by tour.
Step 2 · Connect with a connection string and a ~/.pgpass
Applications and tools describe a database with a connection string, a URI of the form postgresql://user@host:port/database. psql accepts the same string, so the way you connect by hand matches how your code connects. You can put the password in the URI, but then it sits in your shell history. A password file is the better home for it.
libpq, the library under psql, reads ~/.pgpass and uses the first line that matches the host, port, database and user. It ignores the file if anyone other than you can read it, so create it private before anything goes in.
The command below empties any ~/.pgpass you already have. Run ls -l ~/.pgpass first, and if a file is there, skip the install command and add the new line to the existing file instead:
install -m 600 /dev/null ~/.pgpassOpen the file in an editor:
nano ~/.pgpassAdd one line, replacing your-password-here with the password you chose for tour:
localhost:5432:*:tour:your-password-hereThe fields are host, port, database, user and password, separated by colons. The * matches any database, so the same line works when you switch databases later. Save and close the file.
Keep the connection string in a shell variable so the commands below stay short. It holds no secret, only the user, host, port and database:
DB="postgresql://tour@localhost:5432/shop"
psql "$DB" -c "SELECT current_user, current_database();"The variable lasts until you close the terminal. In a new one, run the DB= line again.
Check it worked
The query prints tour and shop without asking for a password. If psql prompts for one, check the line in ~/.pgpass for a typo. If it prints a warning that the password file has group or world access, run chmod 600 ~/.pgpass.
Step 3 · Load a practice schema with psql -f
Work in a throwaway folder. Write a SQL file that creates two tables and a function, and fills the tables with 50 customers and 400 orders built from generate_series. The rows come from a fixed pattern, so your counts will match the ones below.
mkdir -p ~/psql-tour-demo
cat > ~/psql-tour-demo/shop.sql <<'SQL'
DROP FUNCTION IF EXISTS orders_in_city(text);
DROP TABLE IF EXISTS orders, customers;
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
city text NOT NULL,
phone text NOT NULL,
email text NOT NULL,
joined_on date NOT NULL
);
INSERT INTO customers
SELECT g,
(ARRAY['Adaeze', 'Bello', 'Chinedu', 'Ngozi', 'Tunde', 'Zainab', 'Ifeoma'])[1 + g % 7]
|| ' ' || (ARRAY['Okafor', 'Abubakar', 'Adeyemi', 'Eze', 'Lawal'])[1 + g % 5],
(ARRAY['Lagos', 'Abuja', 'Kano', 'Ibadan', 'Port Harcourt'])[1 + g % 5],
'+234 80' || lpad((g * 7919 % 100000000)::text, 8, '0'),
'customer' || g || '@example.com',
date '2026-01-01' + g * 6
FROM generate_series(1, 50) AS g;
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (id),
placed_at timestamptz NOT NULL,
amount integer NOT NULL -- in naira
);
INSERT INTO orders
SELECT g,
1 + (g * 17 + g / 7) % 50,
timestamptz '2026-11-01 08:00+01' + g * interval '90 minutes',
1500 + ((g * 37) % 40) * 250
FROM generate_series(1, 400) AS g;
CREATE FUNCTION orders_in_city(p_city text) RETURNS bigint
LANGUAGE sql STABLE
RETURN (SELECT count(*)
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE c.city = p_city);
SQLRun the file with -f. psql reads it one statement at a time and prints the result tag of each, such as CREATE TABLE and INSERT 0 50:
psql "$DB" -f ~/psql-tour-demo/shop.sqlThe first run also prints notices that the table and function did not exist yet. That is the DROP ... IF EXISTS lines doing their job. The function is dropped first because PostgreSQL records that its body depends on both tables, and would refuse to drop them while it exists. Together they mean you can run the file again at any time to get a fresh copy of the data.
Check it worked
psql "$DB" -c "SELECT (SELECT count(*) FROM customers) AS customers, (SELECT count(*) FROM orders) AS orders;"You see 50 customers and 400 orders.
Step 4 · Look around with \l, \c, \dt, \d+, \df and \du
Day to day you will type these in an interactive session. Start one:
psql "$DB"The prompt shows the database name, shop=>. The > means you are not a superuser; a superuser sees #. Type \? for the full list of meta-commands, \h CREATE TABLE for help on any SQL statement, and \q to leave. Meta-commands do not need a semicolon.
Every command in this step also runs from the shell with -c, which is how they are shown here. Inside the session, type the part in quotes.
List the databases on the server, with owners and encodings:
psql "$DB" -c '\l'Switch to another database without leaving psql. \c takes a database name, and optionally a user. Several -c options run in order in one session, so you can see the switch happen:
psql "$DB" -c '\c postgres' -c 'SELECT current_database();'psql prints You are now connected to database "postgres" as user "tour"., then the query result. In an interactive session, the prompt changes to postgres=>. Run \c shop to go back.
List the tables in the current database, then describe one:
psql "$DB" -c '\dt'
psql "$DB" -c '\d+ orders'\d orders shows the columns, their types, the primary key index and the foreign key to customers. The + adds the storage, compression, statistics target and description of each column, and the table's access method. The same + works on most listing commands: \dt+ adds a size column, which is the quickest way to find what is taking up space.
List your own functions and the roles on the server:
psql "$DB" -c '\df'
psql "$DB" -c '\du'\df shows orders_in_city with its argument and result types. \du lists each role and its attributes, such as Superuser or Create DB. tour has none, which is what you want for an everyday account.
Most listing commands accept a pattern. \dt cust* lists tables whose names start with cust, and \df *city* finds functions with city in the name.
Check it worked
\dt lists exactly two tables, customers and orders, both owned by tour. \d+ orders mentions customers(id) under foreign-key constraints.
Step 5 · Read wide rows with \x and time queries with \timing
A row with many columns wraps across the screen and becomes hard to read. Expanded display prints each row as a list of column | value pairs instead. \x on turns it on, \x off turns it off, and \x auto switches only when a result is too wide for your terminal, which is the setting most people keep.
psql measures the width of your terminal for \x auto. When output goes to a pipe or a file there is no terminal, so the example below sets a width of 60 characters with \pset columns to show the effect:
psql "$DB" -c '\pset columns 60' -c '\x auto' -c 'SELECT * FROM customers WHERE id IN (5, 6);'The output starts with -[ RECORD 1 ] and lists one field per line. Run the same query in your interactive session with \x auto and a narrow window, then widen the window and run it again to see psql switch back to a table.
\timing on makes psql print how long each statement took, measured from the client, so it includes the trip over the network:
psql "$DB" -c '\timing on' -c "SELECT orders_in_city('Lagos');"The result is 57, followed by a line like Time: 1.234 ms. Your time will differ. For a breakdown of where the time goes inside the server, use EXPLAIN ANALYZE, as in /tutorials/speed-up-slow-postgres-queries-with-explain.
Check it worked
You saw two records laid out vertically, and a Time: line under the Lagos count of 57.
Step 6 · Reuse queries with variables, \i and \e
psql variables let one saved query answer many questions. Set one with \set name value, or from the shell with -v name=value, and use it in three ways:
:citypastes the value as it is.:'city'pastes it as a quoted SQL string, with any quotes inside escaped. Use this for values.:"city"pastes it as a quoted identifier, for a table or column name.
Write a report that takes a city and falls back to Lagos when none is given. \if :{?city} tests whether the variable is set:
cat > ~/psql-tour-demo/city-report.sql <<'SQL'
\if :{?city}
\else
\set city Lagos
\endif
\echo Orders for :city
SELECT count(*) AS orders, sum(o.amount) AS total_naira
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.city = :'city';
SQL
psql "$DB" -f ~/psql-tour-demo/city-report.sql
psql "$DB" -v city=Ibadan -f ~/psql-tour-demo/city-report.sqlThe first run prints Orders for Lagos with 57 orders and 361000 naira. The second prints Orders for Ibadan with 115 orders and 735250 naira. A city with a space or an apostrophe in it still works, because :'city' quotes it: try -v city='Port Harcourt'.
Variables are expanded only in what psql reads as a script or types at the prompt, not in a plain SQL string passed with -c. A single backslash command passed with -c, such as -c '\echo :HISTFILE' later on, is parsed by psql itself, so its variables are expanded. That is why the report lives in a file.
Inside an interactive session, \i runs a file as if you had typed it, and the variables you set at the prompt carry into it:
shop=> \set city Kano
shop=> \i ~/psql-tour-demo/city-report.sqlThe same works from the shell:
psql "$DB" -c "\i $HOME/psql-tour-demo/city-report.sql"\e opens your last query in a text editor. Fix it, save and quit, and psql runs the edited query as soon as the editor closes. It uses the editor named in the PSQL_EDITOR or EDITOR environment variable, and vi if neither is set. Add export EDITOR=nano to ~/.bashrc if you prefer nano. \e with a file name opens that file instead and runs it when you close the editor, but psql reads the edited text as a single line, so this only suits files of plain SQL. A file with meta-commands in it, such as city-report.sql, belongs with \i.
Check it worked
Lagos shows 57 orders and Ibadan 115. Port Harcourt shows 57 orders and 365500 naira.
Step 7 · Export to CSV with \copy and repeat a query with \watch
\copy runs a query and writes the result to a file on your machine, the one running psql. The SQL COPY ... TO 'file' command looks similar but writes the file on the database server, as the postgres system user, and needs extra privileges. When the database is on another machine, \copy is the one you want.
Export Lagos orders with a header row:
psql "$DB" -c "\copy (SELECT o.id, c.name, c.phone, o.placed_at, o.amount FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.city = 'Lagos' ORDER BY o.placed_at) TO '$HOME/psql-tour-demo/lagos-orders.csv' WITH (FORMAT csv, HEADER)"
head -n 3 ~/psql-tour-demo/lagos-orders.csvpsql prints COPY 57, the number of rows written. For loading CSV files into tables, handling bad rows and the other COPY options, see /tutorials/load-and-export-csv-data-with-postgresql-copy. The file is UTF-8, so names with accents or in other scripts arrive intact in LibreOffice or Google Sheets. Excel sometimes needs to be told the file is UTF-8 when you import it.
\copy must fit on one line, because psql reads everything up to the end of the line as part of the command. For a long query, create a view first and copy from the view.
If you reach a remote database over a mobile data bundle, export a filtered query like this rather than a whole table. Only the rows you ask for cross the connection.
\watch re-runs a query every few seconds, which is handy while a data load or a migration runs. i= sets the interval in seconds and count= stops after that many runs. Without count, it runs until you press Ctrl+C. Here it runs three times, two seconds apart:
psql "$DB" <<'SQL'
SELECT now()::time(0) AS checked_at, count(*) AS orders FROM orders
\watch i=2 count=3
SQLNote there is no semicolon after the query: \watch sends whatever is in the query buffer. In an interactive session you can also run a query normally, then type \watch 5 on its own to repeat the last query every five seconds.
Check it worked
lagos-orders.csv has 58 lines, a header and 57 orders. The \watch output shows three blocks, each with 400 orders and a checked_at time two seconds after the one before.
Step 8 · Make scripts stop at the first error
By default psql reports an error in a script and carries on with the next statement. In a migration or a nightly job that is dangerous: half the script runs, the rest fails, and the exit code still says all is well. See it with a script that has a typo in the middle:
cat > ~/psql-tour-demo/broken.sql <<'SQL'
CREATE TABLE IF NOT EXISTS run_log (note text);
INSERT INTO run_log VALUES ('before the typo');
SELEC 1;
INSERT INTO run_log VALUES ('after the typo');
SQL
psql "$DB" -f ~/psql-tour-demo/broken.sql
echo "psql exit code: $?"
psql "$DB" -c "SELECT note FROM run_log;"psql prints an error like psql:/home/you/psql-tour-demo/broken.sql:3: ERROR: syntax error at or near "SELEC", then the exit code 0. Both rows are in run_log, including the one after the error.
Set ON_ERROR_STOP and run it again on an empty log:
psql "$DB" -c "TRUNCATE run_log;"
psql "$DB" -v ON_ERROR_STOP=1 -f ~/psql-tour-demo/broken.sql || echo "psql stopped with exit code $?"
psql "$DB" -c "SELECT note FROM run_log;"This time psql stops at line 3 and exits with code 3, which a shell script, cron job or CI step treats as a failure. Only before the typo is in the log. Add --single-transaction (or -1) as well, and the rows written before the error are rolled back too, so the script either runs completely or changes nothing.
For scripts you run unattended, also pass -X. It skips your ~/.psqlrc, so personal display settings from the next step cannot change a script's output.
Check it worked
The first run printed psql exit code: 0 and two rows. The second printed psql stopped with exit code 3 and one row.
Step 9 · Set up a .psqlrc with a useful prompt and per-database history
psql runs ~/.psqlrc at the start of every session. Put the settings you would otherwise type each time there. The command below replaces the file, so first keep a copy of any ~/.psqlrc you already have:
if [ -e ~/.psqlrc ]; then cp ~/.psqlrc ~/.psqlrc.bak; fi
cat > ~/.psqlrc <<'PSQLRC'
-- Hide the confirmation messages while these settings load.
\set QUIET 1
-- Prompt: user@host database, then * inside a transaction, ! after an error in one.
\set PROMPT1 '%n@%m %/%R%x%# '
\set PROMPT2 '%R%x%# '
-- Show NULL so it is not mistaken for an empty string.
\pset null '(null)'
-- Turn wide rows on their side only when they do not fit.
\x auto
-- Report how long each statement takes.
\timing on
-- In an interactive session, an error does not abort the open transaction.
\set ON_ERROR_ROLLBACK interactive
-- One history file per database, without repeated lines.
\set HISTFILE ~/.psql_history-:DBNAME
\set HISTCONTROL ignoredups
\set QUIET 0
PSQLRCWhat the prompt codes mean: %n is your user name, %m the server host ([local] when you connect through the local socket), %/ the database, %R is = normally and changes when psql waits for more input, %x shows * inside a transaction and ! in a failed one, and %# is # for a superuser and > for everyone else.
The history line keeps the queries you run against shop apart from those you run against other databases, so the up arrow brings back commands that make sense where you are.
ON_ERROR_ROLLBACK interactive protects you from a common annoyance. Without it, one typo inside BEGIN ... COMMIT fails the whole transaction and you start again. With it, only the bad statement is undone. It only applies at the prompt, so scripts keep the strict behaviour from the previous step.
Check it worked
psql "$DB" -c '\echo :HISTFILE'The output is ~/.psql_history-shop. Start an interactive session with psql "$DB" and the prompt now reads tour@localhost shop=> `. Type `BEGIN; and it changes to tour@localhost shop=*> `; type `ROLLBACK; to leave the transaction. Run SELECT NULL; and the result shows (null) with a Time: line underneath.
Clean up
Keep ~/.psqlrc; it is the useful part. Remove the practice database, the role and the folder:
sudo -u postgres dropdb shop
sudo -u postgres dropuser tour
rm -r ~/psql-tour-demo
rm -f ~/.psql_history-shop ~/.psql_history-postgresThen open ~/.pgpass with nano ~/.pgpass and delete the tour line. If it was the only line, delete the file with rm ~/.pgpass.
Next steps
- Ask better questions of a table with the queries in
/tutorials/query-a-table-with-select-where-and-order-by. - Use the same connection string and
~/.pgpassto take a backup:/tutorials/back-up-and-restore-postgresql-with-pg-dump. - Combine
\timingwith query plans to find slow queries:/tutorials/speed-up-slow-postgres-queries-with-explain. - The full list of meta-commands, variables and prompt codes is in the psql reference page of the PostgreSQL 18 manual, at postgresql.org/docs/18/app-psql.html.
Related tutorials
- How to Install PostgreSQL 18 on Ubuntu 26.04 and Create Your First DatabaseYou will install PostgreSQL 18 from the official PostgreSQL apt repository, create a database and a user for your app, and connect to it with a password.
- Query a table in SQL with SELECT, WHERE and ORDER BYYou will load 500 market stall sales into PostgreSQL 18 and answer ten questions about them with SELECT, WHERE, ORDER BY, LIMIT, DISTINCT and CASE, saved in a .sql file you can run again with psql -f.
- How to Back Up and Restore a PostgreSQL Database with pg_dumpYou will back up a PostgreSQL 18 database in three formats, restore it into a fresh database, check the copy matches, and schedule a nightly backup that deletes old files.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials