Skip to content
shellhacks.dev
Databases

Dump one table

Dump one table with pg_dump -t name. The option takes a pattern, so -t orders does not match orders_archive but -t 'orders*' does, and quoting rules apply.

2 min read
Summarize in AI

A backup of one table should contain that table, and you want to be sure which other tables a pattern pulls in.

Shell
createdb shop
psql shop -q -c 'CREATE TABLE orders (id int PRIMARY KEY)' -c 'CREATE TABLE orders_archive (id int)' -c 'CREATE TABLE "Customers" (id int)'
echo "-t orders:"; pg_dump -t orders --schema-only shop | grep '^CREATE TABLE'
echo "-t 'orders*':"; pg_dump -t 'orders*' --schema-only shop | grep '^CREATE TABLE'
echo "-t Customers:"; pg_dump -t Customers --schema-only shop 2>&1 | grep -E '^(CREATE TABLE|pg_dump)'
echo "-t '\"Customers\"':"; pg_dump -t '"Customers"' --schema-only shop | grep '^CREATE TABLE'
dropdb shop
Text
-t orders:
CREATE TABLE public.orders (
-t 'orders*':
CREATE TABLE public.orders (
CREATE TABLE public.orders_archive (
-t Customers:
pg_dump: error: no matching tables were found
-t '"Customers"':
CREATE TABLE public."Customers" (

-t takes a pattern in the style of psql, where * and ? are wildcards and the name is folded to lowercase unless it is double-quoted. A plain orders therefore matches exactly one table, a star pulls in the archive too, and Customers is looked up as customers and not found, while the double-quoted form, wrapped in single quotes for the shell, finds it. See the pg_dump reference. The option can be repeated, and -T excludes tables.

Only that table is dumped: the tables it references through foreign keys, and views or functions that depend on it, are not, so a restore into an empty database can fail on the constraint. A pattern that matches nothing is an error, as the third command shows, so a typo cannot quietly produce an empty dump. Sequences owned by the table's columns are included.

Share

More snippets

Databases

Describe a table

Show a table's columns, indexes and foreign keys with the psql meta-command backslash d, and add a plus sign for storage and comments.

2 min read
Databases

Run a SQL statement from the shell

Run a statement from the shell with psql -c. One -c string with several statements is a single transaction, so an error undoes all of them, unlike repeated -c.

2 min read
Databases

Run SQL from a file

Run SQL from a file with psql -f. An error in the middle does not stop the file and the exit status stays 0, unless ON_ERROR_STOP is set to 1.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.