Data Types & PostgreSQL-specific SQL
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
PostgreSQL implements most of standard SQL, which this site documents once in the SQL Reference: DDL, queries and joins, data modification, aggregate and window functions and functions. This page does not repeat that material. It covers what is particular to PostgreSQL: the richer type system and the statements and clauses that only exist, or work differently, here.
All outputs were produced on PostgreSQL 18.6 with the shop seed from
Getting Started. Scratch objects live in a separate schema, lab;
the search path in these examples is lab, shop, public, so the shop tables are used without a prefix.
Numeric types
| Type | Storage and range | Use for |
|---|---|---|
|
2, 4 and 8 bytes; |
Counters, keys; prefer |
|
Exact decimal, variable length, up to 131072 digits before the point |
Money and anything that must not round unexpectedly. |
|
4 and 8 byte IEEE floating point |
Measurements and scientific values; never for money. |
There is a money type, but it is tied to a locale setting and is rarely the right choice; use numeric with an
explicit scale. Binary floating point cannot represent most decimal fractions exactly, and integer arithmetic
overflows instead of widening:
SELECT 0.1::float8 + 0.2::float8 AS float8_sum, 0.1::numeric + 0.2::numeric AS numeric_sum;
SELECT 7 / 2 AS int_div, 7 / 2.0 AS numeric_div, 7 % 2 AS modulo;
SELECT 2147483647 + 1;
SELECT 2147483647::bigint + 1 AS bigint_sum;
float8_sum | numeric_sum
---------------------+-------------
0.30000000000000004 | 0.3
(1 row)
int_div | numeric_div | modulo
---------+--------------------+--------
3 | 3.5000000000000000 | 1
(1 row)
ERROR: integer out of range
bigint_sum
------------
2147483648
(1 row)
Integer division truncates, so 7 / 2 is 3; one numeric operand makes the division exact. The literal
0.1 + 0.2 is numeric too, which is why it prints 0.3.
Text and character types
text is the unbounded string type and is as fast as any other; varchar(n) is the same type plus a length check, and
char(n) pads with blanks and is almost never what you want. In PostgreSQL there is no performance reason to prefer
varchar(n) over text; use a CHECK constraint or a domain when a limit is a real rule. Strings are compared
using the collation of the column (database default en_US.utf8 in the container); pattern operators are LIKE,
case-insensitive ILIKE, and POSIX regular expressions with ~ and ~*.
SELECT name FROM customers WHERE name ILIKE 'a%' ORDER BY name;
SELECT email FROM customers WHERE email ~ '^(ada|grace)@' ORDER BY email;
SELECT upper(name) AS upper_name, length(name) AS chars, left(email, strpos(email, '@') - 1) AS handle, name || ' <' || email || '>' AS full_address FROM customers WHERE id = 'c-1';
SELECT format('%s paid %L for %I', 'Ada', 'it''s', 'my table') AS formatted;
SELECT string_agg(name, ', ' ORDER BY name) AS everyone FROM customers;
SELECT regexp_replace('order-1001', '\D', '', 'g')::int AS order_number;
name
--------------
Ada Lovelace
Alan Turing
(2 rows)
email
-------------------
ada@example.com
grace@example.com
(2 rows)
upper_name | chars | handle | full_address
--------------+-------+--------+--------------------------------
ADA LOVELACE | 12 | ada | Ada Lovelace <ada@example.com>
(1 row)
formatted
---------------------------------
Ada paid 'it''s' for "my table"
(1 row)
everyone
---------------------------------------------------------
Ada Lovelace, Alan Turing, Grace Hopper, Linus Torvalds
(1 row)
order_number
--------------
1001
(1 row)
format with %I (identifier) and %L (literal) is the safe way to build dynamic SQL strings, used again with
\gexec at the end of this page.
Timestamps, time zones and intervals
Use timestamptz (timestamp with time zone) for points in time. Despite the name it does not store a zone: it stores
a UTC instant, and converts to and from the session’s TimeZone setting on input and output. timestamp (without
time zone) stores a wall-clock reading and ignores the zone entirely, which is right only for things like "a recurring
09:00 alarm". date, time and interval complete the family.
SELECT current_setting('TimeZone') AS session_tz;
SELECT '2026-03-29 01:30:00+00'::timestamptz AS stored_utc;
SET TIME ZONE 'Europe/Madrid';
SELECT '2026-03-29 01:30:00+00'::timestamptz AS in_madrid;
SELECT '2026-07-01 12:00:00'::timestamp AS plain_ts, '2026-07-01 12:00:00'::timestamptz AS tstz;
SELECT '2026-07-01 12:00:00+00'::timestamptz AT TIME ZONE 'America/New_York' AS new_york_wall_clock;
RESET TIME ZONE;
session_tz
------------
Etc/UTC
(1 row)
stored_utc
------------------------
2026-03-29 01:30:00+00
(1 row)
in_madrid
------------------------
2026-03-29 03:30:00+02
(1 row)
plain_ts | tstz
---------------------+------------------------
2026-07-01 12:00:00 | 2026-07-01 12:00:00+02
(1 row)
new_york_wall_clock
---------------------
2026-07-01 08:00:00
(1 row)
The same instant is displayed as 01:30+00 and 03:30+02 depending on the session; an input without an offset is
interpreted in the session zone (the second tstz column). AT TIME ZONE converts an instant to a wall clock in
another zone (and the reverse for a plain timestamp). Arithmetic with interval is calendar-aware:
SELECT date_trunc('month', order_date) AS month, count(*) FROM orders GROUP BY 1 ORDER BY 1;
SELECT order_date, order_date + interval '1 month' AS plus_month, age(timestamptz '2026-04-01', order_date) AS age FROM orders WHERE id IN (1001, 1006);
SELECT extract(isodow FROM order_date) AS dow, to_char(order_date, 'YYYY-MM-DD HH24:MI TZ') AS formatted FROM orders WHERE id = 1001;
SELECT d::date FROM generate_series('2026-02-27'::date, '2026-03-02'::date, interval '1 day') AS d;
month | count
------------------------+-------
2026-01-01 00:00:00+00 | 1
2026-02-01 00:00:00+00 | 3
2026-03-01 00:00:00+00 | 4
(3 rows)
order_date | plus_month | age
------------------------+------------------------+-------------------------
2026-01-05 10:00:00+00 | 2026-02-05 10:00:00+00 | 2 mons 26 days 14:00:00
2026-03-15 14:00:00+00 | 2026-04-15 14:00:00+00 | 16 days 10:00:00
(2 rows)
dow | formatted
-----+----------------------
1 | 2026-01-05 10:00 UTC
(1 row)
d
------------
2026-02-27
2026-02-28
2026-03-01
2026-03-02
(4 rows)
generate_series works on timestamps and dates as well as integers and is the standard way to fabricate calendars and
test data; the later pages use it for bulk rows. Other types worth knowing: uuid (with gen_random_uuid() built in
and uuidv7() from PostgreSQL 18, which is time-ordered and friendlier to B-tree indexes), boolean, bytea,
inet and cidr for network addresses, and xml. json and jsonb have their own page,
JSON & JSONB.
Arrays
Any type has an array form: text[], integer[], numeric[][]. The shop’s products.tags is a text[]. Arrays are
1-based, and have operators for membership (= ANY), containment (@>, <@) and overlap (&&), which GIN indexes
can serve (see Indexing).
SELECT sku, tags FROM products ORDER BY sku;
SELECT sku FROM products WHERE 'sale' = ANY (tags) ORDER BY sku;
SELECT sku FROM products WHERE tags @> ARRAY['office','ergonomic'] ORDER BY sku;
SELECT sku FROM products WHERE tags && ARRAY['usb','led'] ORDER BY sku;
SELECT sku, array_length(tags, 1) AS n, tags[1] AS first_tag FROM products ORDER BY sku;
SELECT sku, unnest(tags) AS tag FROM products WHERE sku = 'B-7';
SELECT tag, array_agg(sku ORDER BY sku) AS skus FROM products, unnest(tags) AS tag GROUP BY tag ORDER BY tag;
sku | tags
-----+-------------------------
A-1 | {office,ergonomic}
A-2 | {office,ergonomic,sale}
B-7 | {office,led}
C-3 | {usb,sale}
C-9 | {display,office}
(5 rows)
sku
-----
A-2
C-3
(2 rows)
sku
-----
A-1
A-2
(2 rows)
sku
-----
B-7
C-3
(2 rows)
sku | n | first_tag
-----+---+-----------
A-1 | 2 | office
A-2 | 3 | office
B-7 | 2 | office
C-3 | 2 | usb
C-9 | 2 | display
(5 rows)
sku | tag
-----+--------
B-7 | office
B-7 | led
(2 rows)
tag | skus
-----------+-------------------
display | {C-9}
ergonomic | {A-1,A-2}
led | {B-7}
office | {A-1,A-2,B-7,C-9}
sale | {A-2,C-3}
usb | {C-3}
(6 rows)
unnest turns an array into rows and array_agg folds rows back into an array. Arrays are convenient for small,
unordered attributes that are always read and written together; when elements need their own constraints,
foreign keys or independent updates, use a child table instead (see
Normalization).
Enums
An enum is an ordered set of labels stored as four bytes. Comparison and ORDER BY follow the declaration order, not
alphabetical order, and a bad label is rejected:
CREATE TYPE priority AS ENUM ('low', 'normal', 'urgent');
CREATE TABLE tickets (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, prio priority NOT NULL DEFAULT 'normal');
INSERT INTO tickets (title, prio) VALUES ('printer jam', 'low'), ('outage', 'urgent'), ('new laptop', DEFAULT);
SELECT title, prio FROM tickets ORDER BY prio DESC;
ALTER TYPE priority ADD VALUE 'critical' AFTER 'urgent';
SELECT enum_range(NULL::priority);
INSERT INTO tickets (title, prio) VALUES ('bad', 'nope');
title | prio
-------------+--------
outage | urgent
new laptop | normal
printer jam | low
(3 rows)
enum_range
------------------------------
{low,normal,urgent,critical}
(1 row)
ERROR: invalid input value for enum priority: "nope"
LINE 1: INSERT INTO tickets (title, prio) VALUES ('bad', 'nope');
^
Labels can be added (even in the middle) but not removed or reordered, so a value set that is likely to change is
better modelled as a lookup table or a CHECK (status IN (...)), as the shop schema does for orders.status.
Range and multirange types
A range holds a lower and an upper bound of one subtype, written [lower, upper) where [ and ( mean inclusive and
exclusive. Built-in ranges are int4range, int8range, numrange, daterange, tsrange and tstzrange; each has a
multirange counterpart since PostgreSQL 14. Ranges replace pairs of start/end columns and make overlap logic
trivial. Together with an exclusion constraint (see Indexing) they can
make double-booking impossible.
CREATE TABLE room_bookings (room text NOT NULL, during tstzrange NOT NULL);
INSERT INTO room_bookings VALUES
('blue', '[2026-05-01 09:00+00, 2026-05-01 11:00+00)'),
('blue', '[2026-05-01 11:00+00, 2026-05-01 12:30+00)'),
('green', '[2026-05-01 10:00+00, 2026-05-01 10:45+00)');
SELECT room, during, upper(during) - lower(during) AS length FROM room_bookings ORDER BY room, lower(during);
SELECT room FROM room_bookings WHERE during @> timestamptz '2026-05-01 10:30+00' ORDER BY room;
SELECT room FROM room_bookings WHERE during && tstzrange('2026-05-01 10:30+00', '2026-05-01 11:30+00') ORDER BY room;
SELECT int4range(1, 5) * int4range(3, 9) AS intersection, int4range(1, 5, '[]') AS closed, numrange(1.5, 2.5) @> 2.0 AS has_two;
SELECT range_agg(during) FROM room_bookings WHERE room = 'blue';
room | during | length
-------+-----------------------------------------------------+----------
blue | ["2026-05-01 09:00:00+00","2026-05-01 11:00:00+00") | 02:00:00
blue | ["2026-05-01 11:00:00+00","2026-05-01 12:30:00+00") | 01:30:00
green | ["2026-05-01 10:00:00+00","2026-05-01 10:45:00+00") | 00:45:00
(3 rows)
room
-------
blue
green
(2 rows)
room
-------
blue
blue
green
(3 rows)
intersection | closed | has_two
--------------+--------+---------
[3,5) | [1,6) | t
(1 row)
range_agg
-------------------------------------------------------
{["2026-05-01 09:00:00+00","2026-05-01 12:30:00+00")}
(1 row)
@> tests containment of a point or a range, && tests overlap, * intersects. Discrete ranges such as int4range
are normalised to the half-open form ([1,5] became [1,6)), and the two adjacent blue bookings merge into one
multirange in range_agg.
Domains
A domain is a base type with a default and constraints, defined once and reused by name. It is the right place for rules such as "an e-mail address looks like this":
CREATE DOMAIN email_address AS text
CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$');
CREATE TABLE subscribers (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email email_address NOT NULL);
INSERT INTO subscribers (email) VALUES ('ada@example.com');
INSERT INTO subscribers (email) VALUES ('not-an-email');
SELECT * FROM subscribers;
\dD
ERROR: value for domain email_address violates check constraint "email_address_check"
id | email
----+-----------------
1 | ada@example.com
(1 row)
List of domains
Schema | Name | Type | Collation | Nullable | Default | Check
--------+---------------+------+-----------+----------+---------+----------------------------------------------------
lab | email_address | text | | | | CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$'::text)
(1 row)
Identity and generated columns
GENERATED ... AS IDENTITY is the standard replacement for the older serial pseudo-type: the column is backed by an
owned sequence, and ALWAYS forbids supplying a value unless the statement says OVERRIDING SYSTEM VALUE
(BY DEFAULT allows it). Use identity columns in new schemas.
GENERATED ALWAYS AS (expr) STORED computes a column from others at write time and stores it. PostgreSQL 18 adds
VIRTUAL generated columns, computed on read and taking no space; the virtual form is the default when STORED is
omitted.
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
net numeric(10,2) NOT NULL,
vat_rate numeric(4,2) NOT NULL DEFAULT 0.21,
gross numeric(10,2) GENERATED ALWAYS AS (round(net * (1 + vat_rate), 2)) STORED,
net_cents bigint GENERATED ALWAYS AS ((net * 100)::bigint) VIRTUAL
);
INSERT INTO invoices (net) VALUES (100.00), (19.99);
SELECT * FROM invoices;
INSERT INTO invoices (id, net) VALUES (99, 1);
INSERT INTO invoices (net, gross) VALUES (1, 1);
INSERT INTO invoices (id, net) OVERRIDING SYSTEM VALUE VALUES (500, 5) RETURNING id, gross;
SELECT pg_get_serial_sequence('invoices', 'id') AS owned_sequence;
\d invoices
id | net | vat_rate | gross | net_cents
----+--------+----------+--------+-----------
1 | 100.00 | 0.21 | 121.00 | 10000
2 | 19.99 | 0.21 | 24.19 | 1999
(2 rows)
ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.
ERROR: cannot insert a non-DEFAULT value into column "gross"
DETAIL: Column "gross" is a generated column.
id | gross
-----+-------
500 | 6.05
(1 row)
owned_sequence
---------------------
lab.invoices_id_seq
(1 row)
Table "lab.invoices"
Column | Type | Collation | Nullable | Default
-----------+---------------+-----------+----------+----------------------------------------------------------------------
id | bigint | | not null | generated always as identity
net | numeric(10,2) | | not null |
vat_rate | numeric(4,2) | | not null | 0.21
gross | numeric(10,2) | | | generated always as (round(net * (1::numeric + vat_rate), 2)) stored
net_cents | bigint | | | generated always as ((net * 100::numeric)::bigint)
Indexes:
"invoices_pkey" PRIMARY KEY, btree (id)
A generated column cannot be written directly. Identity sequences are not rolled back with a transaction, so gaps in
the numbering are normal; they are also not reset by DELETE.
RETURNING
INSERT, UPDATE, DELETE and MERGE can return the affected rows, saving a second query and giving the
generated values (identity, defaults, computed columns) back to the caller in the same round trip. From PostgreSQL 18
the RETURNING list can refer to old and new row versions explicitly:
INSERT INTO invoices (net) VALUES (7) RETURNING id, gross;
BEGIN;
UPDATE products SET stock = stock - 2 WHERE sku = 'B-7' RETURNING sku, stock AS new_stock;
UPDATE products SET price = price * 1.10 WHERE sku = 'C-3' RETURNING sku, old.price AS before, new.price AS after;
ROLLBACK;
BEGIN;
DELETE FROM order_items WHERE order_id = 1008 RETURNING *;
ROLLBACK;
id | gross
----+-------
3 | 8.47
(1 row)
sku | new_stock
-----+-----------
B-7 | 148
(1 row)
sku | before | after
-----+--------+-------
C-3 | 39.00 | 42.90
(1 row)
order_id | sku | qty | price
----------+-----+-----+-------
1008 | B-7 | 5 | 24.99
(1 row)
The three changes were rolled back, so the shop data is untouched; the RETURNING output came from the statements
before the rollback. (Before PostgreSQL 18, RETURNING could only see the new row for INSERT and UPDATE and the old
row for DELETE.) Data-modifying statements can also be placed inside a WITH query, shown below.
Upserts with INSERT … ON CONFLICT
INSERT ... ON CONFLICT inserts a row or, if it would violate a unique index, does something else atomically,
without a race between a SELECT and an INSERT. The conflict target names the unique columns or constraint; the
alternative action is DO NOTHING or DO UPDATE, where the pseudo-table EXCLUDED holds the row that was proposed.
CREATE TABLE stock_levels (sku text PRIMARY KEY, qty int NOT NULL, updated_at timestamptz NOT NULL DEFAULT now());
INSERT INTO stock_levels (sku, qty) SELECT sku, stock FROM products;
INSERT INTO stock_levels (sku, qty) VALUES ('A-1', 5), ('Z-9', 7)
ON CONFLICT (sku) DO UPDATE SET qty = stock_levels.qty + EXCLUDED.qty, updated_at = now()
RETURNING sku, qty, (xmax = 0) AS inserted;
INSERT INTO stock_levels (sku, qty) VALUES ('A-1', 1), ('Q-1', 1) ON CONFLICT (sku) DO NOTHING RETURNING sku;
SELECT sku, qty FROM stock_levels ORDER BY sku;
sku | qty | inserted
-----+-----+----------
A-1 | 17 | f
Z-9 | 7 | t
(2 rows)
sku
-----
Q-1
(1 row)
sku | qty
-----+-----
A-1 | 17
A-2 | 30
B-7 | 150
C-3 | 80
C-9 | 25
Q-1 | 1
Z-9 | 7
(7 rows)
A-1 existed, so its quantity was incremented (12 + 5 = 17); Z-9 was inserted. The (xmax = 0) AS inserted trick
distinguishes the two cases, because an updated row version carries a non-zero xmax (see
Architecture). In the second statement A-1 conflicted and was
skipped, while Q-1 was inserted; note that DO NOTHING returns only the rows actually inserted. The same upsert
pattern also works for concurrent writers, which is the reason it exists; see
Transactions, Isolation & MVCC.
MERGE
MERGE (PostgreSQL 15) joins a source to a target and applies different actions to the rows that match and to those
that do not, in one statement: WHEN MATCHED (update or delete) and WHEN NOT MATCHED (insert), with extra
conditions. PostgreSQL 17 added RETURNING and the merge_action() function. Unlike ON CONFLICT, MERGE does not need
a unique index, but it can fail with a unique violation under concurrency if two sessions insert the same key, so
ON CONFLICT remains the choice for a pure insert-or-update on a key.
MERGE INTO stock_levels AS t
USING (VALUES ('A-1', 3), ('C-3', 0), ('N-1', 9)) AS s(sku, qty)
ON t.sku = s.sku
WHEN MATCHED AND s.qty = 0 THEN DELETE
WHEN MATCHED THEN UPDATE SET qty = s.qty, updated_at = now()
WHEN NOT MATCHED THEN INSERT (sku, qty) VALUES (s.sku, s.qty)
RETURNING merge_action(), t.sku, t.qty;
merge_action | sku | qty
--------------+-----+-----
UPDATE | A-1 | 3
DELETE | C-3 | 80
INSERT | N-1 | 9
(3 rows)
Each source row took exactly one action: A-1 was updated, C-3 deleted (its source quantity was zero) and N-1
inserted.
DISTINCT ON, LATERAL and FILTER
Three clauses that remove a lot of subquery code.
DISTINCT ON (expr) keeps the first row of each group of equal expr, in the order given by ORDER BY (whose
leading columns must match). It is the idiomatic "latest row per group":
SELECT DISTINCT ON (customer_id) customer_id, id AS latest_order, order_date
FROM orders
ORDER BY customer_id, order_date DESC;
customer_id | latest_order | order_date
-------------+--------------+------------------------
c-1 | 1007 | 2026-03-18 08:30:00+00
c-2 | 1008 | 2026-03-25 19:00:00+00
c-3 | 1005 | 2026-03-02 11:11:00+00
c-4 | 1006 | 2026-03-15 14:00:00+00
(4 rows)
LATERAL lets a subquery in FROM refer to columns of the tables to its left, so it runs once per outer row: a
"top N per group" without window functions. With an index on (customer_id, order_date) each iteration is a short
index scan.
SELECT c.name, o.id AS order_id, o.order_date
FROM customers c
CROSS JOIN LATERAL (
SELECT id, order_date FROM orders WHERE customer_id = c.id ORDER BY order_date DESC LIMIT 2
) o
ORDER BY c.name, o.order_date DESC;
name | order_id | order_date
----------------+----------+------------------------
Ada Lovelace | 1007 | 2026-03-18 08:30:00+00
Ada Lovelace | 1002 | 2026-02-11 15:20:00+00
Alan Turing | 1008 | 2026-03-25 19:00:00+00
Alan Turing | 1003 | 2026-02-12 09:05:00+00
Grace Hopper | 1005 | 2026-03-02 11:11:00+00
Grace Hopper | 1004 | 2026-02-20 18:45:00+00
Linus Torvalds | 1006 | 2026-03-15 14:00:00+00
(7 rows)
FILTER (WHERE ...) restricts which rows an aggregate sees, replacing CASE expressions inside the aggregate and
producing pivot-like summaries in one pass:
SELECT count(*) AS orders,
count(*) FILTER (WHERE status = 'shipped') AS shipped,
count(*) FILTER (WHERE status = 'open') AS open,
count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders;
orders | shipped | open | cancelled
--------+---------+------+-----------
8 | 4 | 3 | 1
(1 row)
Window functions, GROUPING SETS, ROLLUP and CUBE are standard and are covered in
Aggregate & Window Functions. For pagination patterns that
use these see Pagination Strategies.
Common table expressions
WITH names a subquery so that it can be read top to bottom or referenced more than once; WITH RECURSIVE walks
hierarchies (see queries). PostgreSQL-specific points:
-
Since PostgreSQL 12 a side-effect-free, non-recursive CTE that is referenced once is inlined, so the planner can push predicates into it.
MATERIALIZEDforces it to be evaluated once and stored (an optimization barrier, useful when the CTE is expensive and reused);NOT MATERIALIZEDasks for inlining even when it is referenced several times. -
A CTE may contain
INSERT,UPDATEorDELETE ... RETURNING; the outer query then consumes the returned rows.
EXPLAIN (COSTS OFF)
WITH big AS MATERIALIZED (SELECT * FROM orders WHERE status = 'open')
SELECT * FROM big WHERE id = 1002;
EXPLAIN (COSTS OFF)
WITH big AS NOT MATERIALIZED (SELECT * FROM orders WHERE status = 'open')
SELECT * FROM big WHERE id = 1002;
QUERY PLAN
-------------------------------------------
CTE Scan on big
Filter: (id = 1002)
CTE big
-> Seq Scan on orders
Filter: (status = 'open'::text)
(5 rows)
QUERY PLAN
-----------------------------------------------------
Seq Scan on orders
Filter: ((status = 'open'::text) AND (id = 1002))
(2 rows)
In the first plan the whole status = 'open' set is built (CTE Scan) and id = 1002 filters it afterwards; in the
second the predicates are merged and the primary key is used. A data-modifying CTE moves rows between tables atomically:
CREATE TABLE open_orders_snapshot (LIKE orders);
BEGIN;
WITH moved AS (
UPDATE orders SET status = 'cancelled' WHERE status = 'open' AND order_date < '2026-03-01' RETURNING *
)
INSERT INTO open_orders_snapshot SELECT * FROM moved;
SELECT id, status FROM open_orders_snapshot;
ROLLBACK;
id | status
------+-----------
1002 | cancelled
(1 row)
The ROLLBACK undid both the update and the copy. The same shape (DELETE ... RETURNING feeding an INSERT) moves rows from a queue table to an archive in one
atomic statement, a common pattern for batch jobs.
COPY: bulk import and export
COPY moves data between tables and files or streams at a speed no row-by-row INSERT matches. The server-side
COPY reads or writes files on the server and needs elevated privileges; the psql meta-command \copy does the same through the
client and so reads and writes files on the machine where psql runs. COPY ... TO STDOUT and COPY ... FROM STDIN
work from any driver.
\copy (SELECT sku, name, price FROM products ORDER BY sku) TO '/tmp/products.csv' WITH (FORMAT csv, HEADER)
\! cat /tmp/products.csv
COPY (SELECT id, status FROM orders WHERE id < 1004 ORDER BY id) TO STDOUT WITH (FORMAT csv, HEADER);
CREATE TABLE products_import (sku text, name text, price numeric(10,2));
\copy products_import FROM '/tmp/products.csv' WITH (FORMAT csv, HEADER)
SELECT count(*) FROM products_import;
COPY products_import FROM STDIN WITH (FORMAT csv);
Z-1,Extra item,1.50
Z-2,Another item,2.50
\.
SELECT count(*) FROM products_import;
sku,name,price
A-1,Standing Desk,349.00
A-2,Office Chair,189.50
B-7,Desk Lamp,24.99
C-3,USB-C Hub,39.00
C-9,Monitor 27in,279.00
id,status
1001,shipped
1002,open
1003,shipped
count
-------
5
(1 row)
count
-------
7
(1 row)
Formats are text (the default, tab separated), csv and binary. Options include HEADER, DELIMITER, NULL,
QUOTE, ON_ERROR ignore (to skip malformed rows, new in PostgreSQL 17) and FREEZE. Strategies for loading large
volumes quickly (dropping indexes first, COPY instead of INSERT, UNLOGGED tables) are in
Performance Tuning.
psql meta-commands for SQL work
Besides the introduction in Getting Started, a handful of
meta-commands turn psql into a scripting tool. \gset stores the columns of a query’s single row in variables,
referenced as :name, :'name' (as a quoted literal) or :"name" (as a quoted identifier). \gexec runs each value of
the result as SQL, generating statements from queries. \gdesc describes the columns of a query without running it,
\set sets variables, and \watch reruns the previous query on an interval.
SELECT id, status FROM orders WHERE id = 1001 \gset
\echo order :id is :status
SELECT format('ANALYZE %I.%I', schemaname, tablename) FROM pg_tables WHERE schemaname = 'shop' ORDER BY tablename \gexec
SELECT 1 + 1 AS two, 'x'::text AS t \gdesc
\set min_price 100
SELECT sku, price FROM products WHERE price > :min_price ORDER BY price;
SELECT count(*) AS orders FROM orders \watch i=1 c=2
order 1001 is shipped
Column | Type
--------+---------
two | integer
t | text
(2 rows)
sku | price
-----+--------
A-2 | 189.50
C-9 | 279.00
A-1 | 349.00
(3 rows)
Tue 10 Nov 2026 07:25:27 PM UTC (every 1s)
orders
--------
8
(1 row)
Tue 10 Nov 2026 07:25:28 PM UTC (every 1s)
orders
--------
8
(1 row)
The \gexec line produced no visible output because psql was started with -q; it ran one ANALYZE per shop
table. Other meta-commands for exploration are \df (functions), \dT (types), \dD (domains), \di (indexes) and
\dx (extensions); \h prints the syntax of any SQL command. For GUI clients and IDE integrations see
Database IDEs & Tools.
For transaction semantics see Transactions, Isolation & MVCC and SQL Transactions; for the standard SQL of the shop’s JSON columns compare JSON & XML Functions with JSON & JSONB.