psql and a real server
installing postgres 18, the backslash commands worth knowing, and \x for rows too wide to read.
- address
- everything.start.psql
- part
- part 1, start here
- chapter
- chapter 5 of 7
- reading time
- 9 min
psql is postgres's own terminal client. you type SQL, it sends it to a server and prints the table that comes back. lines that start with a backslash (\d, \x, \timing) are psql's own commands: they never reach the server as typed.
this page can't run psql (it's a program in your terminal, not SQL), so every session below is a real one, pasted whole: psql 18.6 talking to a throwaway postgres 18.6 server loaded with the book's shop data.
the picture
you know how the run buttons on this site just work, and you never see a server? at some point you'll want your own, and psql is how you'll talk to it.
think of a phone call. the server is the person on the other end: it only understands SQL. psql is the phone: it dials (connects), carries your words over the line, and shows you what came back. the backslash commands are the phone's own menu (contacts, speaker, call history). the person you're calling never hears you press those buttons.
hover a stage.
installing postgres 18
pick your system. each of these installs the server and psql together.
Postgres.app is a menu-bar app: open it and a server is running. it's what made the transcripts on this page. or use Homebrew, where the formula is named for the major version and isn't put on your PATH for you (it's "keg-only"):
brew install postgresql@18
brew services start postgresql@18on debian and ubuntu, postgres's own apt repository (PGDG) has every current version. this is the setup from postgresql.org's download page:
sudo apt install -y postgresql-common
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt update
sudo apt install postgresql-18the installer from EDB, linked from postgresql.org/download/windows, sets up the server as a service and puts psql in its bin folder.
the official image. from 18 on, mount volumes at /var/lib/postgresql (the image now keeps its data in a version-specific folder under it):
docker run --name pg18 -e POSTGRES_PASSWORD=secret -p 5432:5432 \
-v pgdata:/var/lib/postgresql -d postgres:18
docker exec -it pg18 psql -U postgrescheck what you got:
$ psql --version
psql (PostgreSQL) 18.6 (Postgres.app)then load the book's shop data, so you can follow along with the same rows. the datasets are plain SQL files in the book's repository. from a checkout of it:
$ createdb shop
$ psql -d shop -1 -v ON_ERROR_STOP=1 -f datasets/shop/schema.sql -f datasets/shop/data.sql
CREATE TABLE
CREATE TABLE
...
INSERT 0 2000
...
INSERT 0 24942
ALTER TABLE
ALTER TABLE
ALTER TABLE
psql:datasets/shop/data.sql:212: NOTICE: drop cascades to 6 other objects
...
DROP SCHEMA
$ psql -d shop -c 'VACUUM (ANALYZE);'
VACUUM-1 wraps both files in one transaction, and ON_ERROR_STOP makes psql quit (and roll everything back) at the first error, so you never end up with half a dataset. the ... lines are mine; the rest is psql's own output.
your first session
$ psql -d shop
psql (18.6 (Postgres.app))
Type "help" for help.
shop=# SELECT name, city FROM customers WHERE id = 42;
name | city
--------------+--------
Ada Lovelace | London
(1 row)
shop=# \qshop=# is the prompt, and it's not decoration. it tells you which database you're in, whether psql is waiting for the rest of a statement, and whether a transaction is open or broken:
- shop=# SELECT name, city FROM customers WHERE id = 42;
- name | city
- --------------+--------
- Ada Lovelace | London
- (1 row)
the resting state. psql is connected to shop, nothing is half-typed, no transaction is open, and you can do anything (you're the superuser, postgres).
the backslash commands worth knowing
\? lists all of them (there are a lot). these are the ones you'll actually type:
| command | what it does |
|---|---|
\l | list databases |
\c shop | connect to another database |
\dt | list tables |
\d customers | describe a table: columns, types, indexes, foreign keys |
\dn, \df, \du | list schemas, functions, roles |
\x | expanded display: one column per line. \x auto decides for you |
\timing | print how long each statement took |
\pset null '(null)' | show NULL as something you can see |
\e | edit the last query in your $EDITOR |
\i file.sql | run a file of SQL |
\copy | COPY to or from a file on your machine, not the server's |
\h SELECT | SQL syntax help for a command |
\q | quit |
the two you'll use most, on the shop database:
shop=# \dt
List of tables
Schema | Name | Type | Owner
--------+-------------+-------+----------
public | customers | table | postgres
public | order_items | table | postgres
public | orders | table | postgres
public | products | table | postgres
(4 rows)
shop=# \d customers
Table "public.customers"
Column | Type | Collation | Nullable | Default
------------+--------------------------+-----------+----------+----------------------------------
id | integer | | not null | generated by default as identity
name | text | | not null |
email | text | | |
city | text | | |
country | character(2) | | not null |
created_at | timestamp with time zone | | not null |
Indexes:
"customers_pkey" PRIMARY KEY, btree (id)
"customers_email_key" UNIQUE CONSTRAINT, btree (email)
Referenced by:
TABLE "orders" CONSTRAINT "orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)\d is the fastest way to learn a schema: every column with its type and default, the indexes (here the two that PRIMARY KEY and UNIQUE made), and every foreign key pointing in.
\x for rows too wide
a table with many columns, or long values, prints lines wider than your terminal, and the terminal wraps them into soup. \x turns each row on its side:
\x. recorded in an 80-column terminal, which is why the first one runs off the edge.put \x auto in a file called ~/.psqlrc and psql runs it every time it starts. (\gx instead of ; does the same for one query only.)
NULL looks like nothing
what \dt really sends
the server doesn't know \dt. psql translates it into an ordinary query on the system catalog, and \set ECHO_HIDDEN on makes it show you:
shop=# \set ECHO_HIDDEN on
shop=# \dt
/******** QUERY *********/
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 't' THEN 'TOAST table' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'partitioned table' WHEN 'I' THEN 'partitioned index' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_catalog.pg_am am ON am.oid = c.relam
WHERE c.relkind IN ('r','p','')
AND n.nspname <> 'pg_catalog'
AND n.nspname !~ '^pg_toast'
AND n.nspname <> 'information_schema'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
/************************/and since that's plain SQL, the browser engine can run it, even though it can't run \dt:
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 't' THEN 'TOAST table' WHEN 'f' THEN 'foreign table' WHEN 'p' THEN 'partitioned table' WHEN 'I' THEN 'partitioned index' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
LEFT JOIN pg_catalog.pg_am am ON am.oid = c.relam
WHERE c.relkind IN ('r','p','')
AND n.nspname <> 'pg_catalog'
AND n.nspname !~ '^pg_toast'
AND n.nspname <> 'information_schema'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;| Schemaname | Namename | Typetext | Ownername |
|---|---|---|---|
| public | customers | table | postgres |
| public | order_items | table | postgres |
| public | orders | table | postgres |
| public | products | table | postgres |
same four tables. reading the queries psql sends is a good way to learn the catalog, which gets its own chapter: the system catalog.
three more you'll want
\timing prints the time for every statement. that's the client's wall clock, round trip included (this was on a laptop, and your number will differ):
shop=# \timing on
Timing is on.
shop=# SELECT count(*) FROM order_items;
count
-------
24942
(1 row)
Time: 4.914 ms\copy reads or writes a file on your machine (plain COPY reads and writes the server's disk, which usually isn't where you are):
shop=# \copy (SELECT id, name, city FROM customers WHERE id = 42) TO 'ada.csv' WITH (FORMAT csv, HEADER)
COPY 1
shop=# \! cat ada.csv
id,name,city
42,Ada Lovelace,Londonand \h is the syntax reference for any SQL command, with a link to its page in the manual:
shop=# \h DELETE
Command: DELETE
Description: delete rows of a table
Syntax:
[ WITH [ RECURSIVE ] with_query [, ...] ]
DELETE FROM [ ONLY ] table_name [ * ] [ [ AS ] alias ]
[ USING from_item [, ...] ]
[ WHERE condition | WHERE CURRENT OF cursor_name ]
[ RETURNING [ WITH ( { OLD | NEW } AS output_alias [, ...] ) ]
{ * | output_expression [ [ AS ] output_name ] } [, ...] ]
URL: https://www.postgresql.org/docs/18/sql-delete.htmlthat RETURNING WITH (OLD ... NEW ...) line is new in 18. it gets its own chapter: RETURNING, with OLD and NEW.
keylines
- psql is a client: it sends SQL to a server and prints what comes back.
- backslash commands are psql's own. the server never sees them, only the SQL some of them turn into.
- the prompt tells you the database, whether a statement is unfinished, and whether a transaction is open or failed.
- \d describes a table, \x turns wide rows on their side, \pset null makes NULL visible.
- psql sends nothing until it sees a semicolon.