← Interview prep

PostgreSQL interview questions

SQL depth, indexing, transactions, and Postgres internals.

100 questions · Page 4 of 5

Want the full pack? Interview packs · Mock interview · Mentora

Page 4 of 5

Questions 61–80 of 100 · 0 of 20 on this page marked learned

61.postgresql-0061Mediummid

Bucket timestamps into 15-minute intervals with date_bin and fill empty buckets.

date_bin(stride, ts, origin) (PostgreSQL 14+) rounds a timestamp down to the start of its bucket for any interval, such as 15 minutes, which date_trunc cannot do. Grouping by the bucket counts events per interval, and joining to generate_series over the same buckets shows intervals with no events as zero.

Full answer

Setup for the example:

sql
CREATE TABLE requests (at timestamp, path text);
INSERT INTO requests VALUES
  ('2026-12-04 09:02', '/'), ('2026-12-04 09:14', '/pay'), ('2026-12-04 09:16', '/'),
  ('2026-12-04 09:58', '/'), ('2026-12-04 09:59', '/pay');
sql
SELECT date_bin('15 minutes', at, timestamp '2026-12-04 00:00') AS bucket, count(*) FROM requests GROUP BY 1 ORDER BY 1;

Output:

text
        bucket       | count
---------------------+-------
 2026-12-04 09:00:00 | 2
 2026-12-04 09:15:00 | 1
 2026-12-04 09:45:00 | 2
(3 rows)
sql
SELECT g AS bucket, count(r.at) AS requests FROM generate_series(timestamp '2026-12-04 09:00', timestamp '2026-12-04 09:45', interval '15 minutes') g LEFT JOIN requests r ON date_bin('15 minutes', r.at, timestamp '2026-12-04 00:00') = g GROUP BY g ORDER BY g;

PostgreSQL returns:

text
        bucket       | requests
---------------------+----------
 2026-12-04 09:00:00 | 2
 2026-12-04 09:15:00 | 1
 2026-12-04 09:30:00 | 0
 2026-12-04 09:45:00 | 2
(4 rows)

The first query shows three non-empty buckets: two requests at 09:00, one at 09:15 and two at 09:45. The 09:30 bucket is missing because nothing happened then. The second query generates all four buckets and counts matching requests with count(r.at), which ignores the NULLs from the outer join, so 09:30 shows 0. The origin fixes the bucket boundaries; an origin of 00:07 would produce buckets starting at :07, :22 and so on.

sql
CREATE TABLE requests (at timestamp, path text);
INSERT INTO requests VALUES
  ('2026-12-04 09:02', '/'), ('2026-12-04 09:14', '/pay'), ('2026-12-04 09:16', '/'),
  ('2026-12-04 09:58', '/'), ('2026-12-04 09:59', '/pay');

SELECT date_bin('15 minutes', at, timestamp '2026-12-04 00:00') AS bucket, count(*) FROM requests GROUP BY 1 ORDER BY 1;

SELECT g AS bucket, count(r.at) AS requests FROM generate_series(timestamp '2026-12-04 09:00', timestamp '2026-12-04 09:45', interval '15 minutes') g LEFT JOIN requests r ON date_bin('15 minutes', r.at, timestamp '2026-12-04 00:00') = g GROUP BY g ORDER BY g;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • date_bin buckets by any interval
  • Origin sets boundaries
  • generate_series fills gaps
  • count(col) ignores outer-join NULLs
  • PostgreSQL 14+

Common mistakes

  • Using count(*) after a LEFT JOIN, counting empty buckets as 1
  • Bucketing with string formatting

Follow-ups

  • How would you bucket in the user's time zone?
  • How does date_bin handle timestamptz?

Tips

  • Explain count(r.at)
62.postgresql-0062Mediummid

Tell whether an upsert inserted a new row or updated an existing one, using RETURNING and xmax.

An upsert with RETURNING returns the final row whether it was inserted or updated. A widely used PostgreSQL-specific trick is RETURNING (xmax = 0) AS inserted: a freshly inserted row has xmax 0, while an updated row carries the updating transaction's id. It relies on internals, so wrap it in a tested helper.

Full answer

Tables and rows used here:

sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int);
INSERT INTO stock VALUES ('PEN', 10);
sql
INSERT INTO stock VALUES ('PEN', 5), ('INK', 3) ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty RETURNING sku, qty, (xmax = 0) AS inserted;

PostgreSQL returns:

text
 sku | qty | inserted
-----+-----+----------
 PEN | 15  | f
 INK | 3   | t
(2 rows)
sql
INSERT INTO stock VALUES ('PAD', 1) ON CONFLICT (sku) DO NOTHING RETURNING sku; INSERT INTO stock VALUES ('PAD', 9) ON CONFLICT (sku) DO NOTHING RETURNING sku;

Result on PostgreSQL 17:

text
 sku
-----
(0 rows)

PEN existed, so its quantity became 15 and inserted is false; INK was new, so inserted is true. In the second run, the first PAD insert succeeds, and the repeated insert with DO NOTHING returns no rows at all, since RETURNING only reports rows actually inserted or updated, which is a clean way to detect skipped duplicates. Only the last statement's result is shown, so the zero-row output belongs to the second PAD insert. The xmax test is an implementation detail that could change between versions.

sql
CREATE TABLE stock (sku text PRIMARY KEY, qty int);
INSERT INTO stock VALUES ('PEN', 10);

INSERT INTO stock VALUES ('PEN', 5), ('INK', 3) ON CONFLICT (sku) DO UPDATE SET qty = stock.qty + EXCLUDED.qty RETURNING sku, qty, (xmax = 0) AS inserted;

INSERT INTO stock VALUES ('PAD', 1) ON CONFLICT (sku) DO NOTHING RETURNING sku; INSERT INTO stock VALUES ('PAD', 9) ON CONFLICT (sku) DO NOTHING RETURNING sku;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • RETURNING works with upserts
  • xmax = 0 identifies inserts
  • DO NOTHING returns no row for skips
  • The xmax trick relies on internals
  • Wrap it in a tested helper

Common mistakes

  • Running a SELECT before the upsert to decide, which races
  • Depending on internals without tests

Follow-ups

  • How would you count inserts versus updates in a batch?
  • What does EXCLUDED refer to?

Tips

  • Explain the zero-row result
63.postgresql-0063Mediummid

Measure how much disk space tables and indexes use with the size functions.

pg_relation_size gives a table's main data size, pg_indexes_size its indexes, and pg_total_relation_size everything including TOAST and indexes. pg_size_pretty formats bytes for humans. Comparing index size with table size often reveals unused or oversized indexes.

Full answer

Test data:

sql
CREATE TABLE logs (id bigint PRIMARY KEY, level text, message text);
INSERT INTO logs SELECT g, CASE WHEN g % 10 = 0 THEN 'error' ELSE 'info' END, repeat('m', 100) FROM generate_series(1, 10000) g;
CREATE INDEX logs_level ON logs (level);
sql
SELECT pg_size_pretty(pg_relation_size('logs')) AS table_size, pg_size_pretty(pg_indexes_size('logs')) AS indexes, pg_size_pretty(pg_total_relation_size('logs')) AS total;

Result on PostgreSQL 17:

text
 table_size | indexes |  total
------------+---------+---------
 1456 kB    | 328 kB  | 1816 kB
(1 row)
sql
SELECT indexrelid::regclass::text AS index_name, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'logs'::regclass ORDER BY 1;

Result:

text
 index_name |  size
------------+--------
 logs_level | 88 kB
 logs_pkey  | 240 kB
(2 rows)

Ten thousand rows with 100-character messages take 1456 kB of table data, and the two indexes add 328 kB. The level index is only 88 kB against 240 kB for the primary key, because B-tree deduplication (PostgreSQL 13+) stores each repeated value once with a list of row pointers, and level has only two values. Such a low-selectivity index rarely helps queries anyway, and pg_stat_user_indexes.idx_scan shows whether it is used at all. Sizes depend on page layout, so they are stable for the same data and version.

sql
CREATE TABLE logs (id bigint PRIMARY KEY, level text, message text);
INSERT INTO logs SELECT g, CASE WHEN g % 10 = 0 THEN 'error' ELSE 'info' END, repeat('m', 100) FROM generate_series(1, 10000) g;
CREATE INDEX logs_level ON logs (level);

SELECT pg_size_pretty(pg_relation_size('logs')) AS table_size, pg_size_pretty(pg_indexes_size('logs')) AS indexes, pg_size_pretty(pg_total_relation_size('logs')) AS total;

SELECT indexrelid::regclass::text AS index_name, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'logs'::regclass ORDER BY 1;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • pg_relation_size for the table
  • pg_indexes_size for indexes
  • pg_total_relation_size for everything
  • pg_size_pretty for display
  • Check idx_scan for unused indexes

Common mistakes

  • Indexing low-selectivity columns
  • Ignoring index size when planning disk

Follow-ups

  • How would you find the largest tables in a database?
  • What is TOAST?

Tips

  • Compare index and table size
64.postgresql-0064Mediummid

Is ALTER TABLE ... ADD COLUMN with a DEFAULT instant on a large table in PostgreSQL 11+?

Since PostgreSQL 11, adding a column with a constant (non-volatile) default is a catalog-only change: the default is stored as a 'missing value' and returned for existing rows without rewriting the table. A volatile default such as random() or clock_timestamp() still rewrites every row. The ALTER still needs a brief exclusive lock.

Full answer

Schema and sample rows:

sql
CREATE TABLE big (id int);
INSERT INTO big SELECT generate_series(1, 50000);
sql
CREATE TEMP TABLE file_before AS SELECT pg_relation_filenode('big') AS node; ALTER TABLE big ADD COLUMN status text NOT NULL DEFAULT 'new'; SELECT (SELECT node FROM file_before) = pg_relation_filenode('big') AS same_file, (SELECT atthasmissing FROM pg_attribute WHERE attrelid = 'big'::regclass AND attname = 'status') AS stored_as_missing;

Result:

text
 same_file | stored_as_missing
-----------+-------------------
 t         | t
(1 row)
sql
CREATE TEMP TABLE file_before2 AS SELECT pg_relation_filenode('big') AS node; ALTER TABLE big ADD COLUMN token float8 DEFAULT random(); SELECT (SELECT node FROM file_before2) = pg_relation_filenode('big') AS same_file;

Output:

text
 same_file
-----------
 f
(1 row)
sql
SELECT count(*) FILTER (WHERE status = 'new') AS defaulted FROM big;

PostgreSQL returns:

text
 defaulted
-----------
 50000
(1 row)

Adding status with a constant default kept the same data file and marked the column with a stored missing value, so 50,000 rows were not touched, yet all of them read back 'new'. Adding a column with random() as its default changed the file node, showing that the table was rewritten so each row could get its own value. On big tables, a rewrite holds the exclusive lock for the whole copy, so volatile defaults are better backfilled in batches after adding the column without a default.

sql
CREATE TABLE big (id int);
INSERT INTO big SELECT generate_series(1, 50000);

CREATE TEMP TABLE file_before AS SELECT pg_relation_filenode('big') AS node; ALTER TABLE big ADD COLUMN status text NOT NULL DEFAULT 'new'; SELECT (SELECT node FROM file_before) = pg_relation_filenode('big') AS same_file, (SELECT atthasmissing FROM pg_attribute WHERE attrelid = 'big'::regclass AND attname = 'status') AS stored_as_missing;

CREATE TEMP TABLE file_before2 AS SELECT pg_relation_filenode('big') AS node; ALTER TABLE big ADD COLUMN token float8 DEFAULT random(); SELECT (SELECT node FROM file_before2) = pg_relation_filenode('big') AS same_file;

SELECT count(*) FILTER (WHERE status = 'new') AS defaulted FROM big;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Constant defaults are catalog-only since PostgreSQL 11
  • Existing rows read the stored missing value
  • Volatile defaults rewrite the table
  • The ALTER still takes a brief exclusive lock
  • Backfill volatile values in batches

Common mistakes

  • Assuming every ADD COLUMN DEFAULT rewrites the table
  • Using volatile defaults on huge tables

Follow-ups

  • Is now() volatile for this purpose?
  • How would you add NOT NULL to an existing column safely?

Tips

  • Show the file node check
65.postgresql-0065Mediummid

When are temporary tables useful, and what do ON COMMIT DROP and ON COMMIT DELETE ROWS do?

A temporary table exists only for the current session and is invisible to other sessions, so it suits staging data during an import or holding intermediate results. ON COMMIT DROP removes it at the end of the transaction, ON COMMIT DELETE ROWS empties it, and the default keeps rows until the session ends. Temporary tables are not WAL-logged and autovacuum does not analyse them, so run ANALYZE before heavy queries.

Full answer

Sample schema and data:

sql
CREATE TABLE prices (sku text PRIMARY KEY, price int);
INSERT INTO prices VALUES ('PEN', 10), ('INK', 45);
sql
CREATE TEMP TABLE staging (sku text, price int); INSERT INTO staging VALUES ('PEN', 12), ('PAD', 60); SELECT count(*) AS staged FROM staging;

Output:

text
 staged
--------
 2
(1 row)

In a second session:

sql
SELECT count(*) FROM staging;

PostgreSQL returns:

text
ERROR:  relation "staging" does not exist
sql
INSERT INTO prices SELECT sku, price FROM staging ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price; SELECT sku, price FROM prices ORDER BY sku;

Result on PostgreSQL 17:

text
 sku | price
-----+-------
 INK | 45
 PAD | 60
 PEN | 12
(3 rows)
sql
BEGIN; CREATE TEMP TABLE scratch (x int) ON COMMIT DROP; INSERT INTO scratch VALUES (1); COMMIT; SELECT to_regclass('scratch') IS NULL AS dropped;

Result:

text
 dropped
---------
 t
(1 row)

Session A loads two rows into its staging table, and session B cannot see the table at all: 'relation "staging" does not exist'. Merging from staging updates PEN and adds PAD. The ON COMMIT DROP table vanished when its transaction ended. With PgBouncer in transaction mode, session-lifetime temporary tables can leak between clients that share a server connection, so ON COMMIT DROP is the safer choice there.

sql
CREATE TABLE prices (sku text PRIMARY KEY, price int);
INSERT INTO prices VALUES ('PEN', 10), ('INK', 45);

CREATE TEMP TABLE staging (sku text, price int); INSERT INTO staging VALUES ('PEN', 12), ('PAD', 60); SELECT count(*) AS staged FROM staging;

-- session B
SELECT count(*) FROM staging;

INSERT INTO prices SELECT sku, price FROM staging ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price; SELECT sku, price FROM prices ORDER BY sku;

BEGIN; CREATE TEMP TABLE scratch (x int) ON COMMIT DROP; INSERT INTO scratch VALUES (1); COMMIT; SELECT to_regclass('scratch') IS NULL AS dropped;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Temp tables are private to a session
  • ON COMMIT DROP removes them at transaction end
  • ON COMMIT DELETE ROWS empties them
  • Not WAL-logged; analyse manually
  • Be careful with transaction poolers

Common mistakes

  • Using session temp tables behind transaction pooling
  • Forgetting ANALYZE on large temp tables

Follow-ups

  • How do unlogged tables differ?
  • When would a CTE replace a temp table?

Tips

  • Mention poolers
66.postgresql-0066Hardsenior

Under SERIALIZABLE, why can two transactions that insert different rows still fail with a serialization error?

PostgreSQL's SERIALIZABLE uses serializable snapshot isolation: it tracks what each transaction read, through predicate locks, and aborts one transaction when reads and writes form a dangerous cycle. A sequential scan locks the whole table as read, so two transactions that each count rows and then insert can conflict although they touch different rows. Indexes narrow the predicate locks and reduce false conflicts; retries remain mandatory.

Full answer

Setup for the example:

sql
CREATE TABLE shifts (day date, doctor text);
INSERT INTO shifts VALUES ('2026-12-04', 'Asha'), ('2026-12-05', 'Ben');
sql
BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-06';

PostgreSQL returns:

text
 count
-------
 0
(1 row)

In a second session:

sql
BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-07';

Result on PostgreSQL 17:

text
 count
-------
 0
(1 row)
sql
INSERT INTO shifts VALUES ('2026-12-07', 'Chen');

Result:

text
INSERT 0 1

In a second session:

sql
INSERT INTO shifts VALUES ('2026-12-06', 'Dev');

Output:

text
INSERT 0 1
sql
COMMIT;

PostgreSQL returns:

text
COMMIT

In a second session:

sql
COMMIT;

Result on PostgreSQL 17:

text
ERROR:  could not serialize access due to read/write dependencies among transactions
sql
SELECT day, doctor FROM shifts ORDER BY day;

Result:

text
    day     | doctor
------------+--------
 2026-12-04 | Asha
 2026-12-05 | Ben
 2026-12-07 | Chen
(3 rows)

Each transaction counts shifts for one day and then inserts into the day the other one read. Because both reads were sequential scans, each transaction's read covers the whole table, so each insert conflicts with the other's read. A commits first; B's commit fails with 'could not serialize access due to read/write dependencies among transactions', and only Chen's shift is stored. With an index on day, the predicate locks would cover only the index ranges read, and these two transactions would usually both succeed. SERIALIZABLE is the simplest way to rule out anomalies such as write skew, but the application must retry on SQLSTATE 40001, and tables queried in serializable transactions should have indexes that match their predicates.

sql
CREATE TABLE shifts (day date, doctor text);
INSERT INTO shifts VALUES ('2026-12-04', 'Asha'), ('2026-12-05', 'Ben');

BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-06';

-- session B
BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-07';

INSERT INTO shifts VALUES ('2026-12-07', 'Chen');

-- session B
INSERT INTO shifts VALUES ('2026-12-06', 'Dev');

COMMIT;

-- session B
COMMIT;

SELECT day, doctor FROM shifts ORDER BY day;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • SSI tracks read/write dependencies
  • Sequential scans lock the whole relation as read
  • Errors can come at COMMIT
  • Indexes narrow predicate locks
  • Always retry 40001

Common mistakes

  • Assuming different rows can never conflict
  • Running SERIALIZABLE without retry logic

Follow-ups

  • How does READ ONLY DEFERRABLE help reports?
  • What does max_pred_locks_per_transaction control?

Tips

  • Explain the table-level read lock
67.postgresql-0067Hardsenior

Prevent double bookings at the database level with an exclusion constraint.

EXCLUDE USING gist (room WITH =, period WITH &&) rejects any two rows with the same room and overlapping periods, enforced atomically even under concurrency. Equality on a scalar column inside a GiST constraint needs the btree_gist extension. Application-level checks cannot do this safely because two transactions can both check and then both insert.

Full answer

Tables and rows used here:

sql
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
  room   int,
  guest  text,
  period tstzrange,
  EXCLUDE USING gist (room WITH =, period WITH &&)
);
INSERT INTO room_bookings VALUES (101, 'Asha', '[2026-12-10 14:00+05:30, 2026-12-12 11:00+05:30)');
sql
INSERT INTO room_bookings VALUES (101, 'Ben', '[2026-12-11 14:00+05:30, 2026-12-13 11:00+05:30)');

Result on PostgreSQL 17:

text
ERROR:  conflicting key value violates exclusion constraint "room_bookings_room_period_excl"
sql
INSERT INTO room_bookings VALUES (101, 'Chen', '[2026-12-12 11:00+05:30, 2026-12-14 11:00+05:30)'), (102, 'Ben', '[2026-12-11 14:00+05:30, 2026-12-13 11:00+05:30)'); SELECT room, guest FROM room_bookings ORDER BY room, lower(period);

Result:

text
 room | guest
------+-------
 101  | Asha
 101  | Chen
 102  | Ben
(3 rows)
sql
BEGIN; SELECT count(*) AS clashes FROM room_bookings WHERE room = 101 AND period && '[2026-12-13 00:00+05:30, 2026-12-13 12:00+05:30)';

Output:

text
 clashes
---------
 1
(1 row)

In a second session:

sql
BEGIN; SELECT count(*) AS clashes FROM room_bookings WHERE room = 101 AND period && '[2026-12-15 00:00+05:30, 2026-12-15 12:00+05:30)'; INSERT INTO room_bookings VALUES (101, 'Dev', '[2026-12-15 10:00+05:30, 2026-12-16 10:00+05:30)'); COMMIT;

PostgreSQL returns:

text
COMMIT
sql
ROLLBACK;

Result on PostgreSQL 17:

text
ROLLBACK

Ben's booking overlaps Asha's stay in room 101 and is rejected with 'conflicting key value violates exclusion constraint'. Chen's booking starts exactly when Asha's ends, which is allowed because the range upper bound is exclusive, and Ben gets room 102 instead. In the last runs, session A's pre-check finds one clash on 13 December (Chen's stay), so A rolls back, while session B checks 15 December, finds it free and books it. Pre-checks like these are useful for friendly messages, but only the constraint is safe when two requests for the same slot race: the second insert waits for the first transaction and then fails. The constraint's GiST index also speeds up availability searches.

sql
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
  room   int,
  guest  text,
  period tstzrange,
  EXCLUDE USING gist (room WITH =, period WITH &&)
);
INSERT INTO room_bookings VALUES (101, 'Asha', '[2026-12-10 14:00+05:30, 2026-12-12 11:00+05:30)');

INSERT INTO room_bookings VALUES (101, 'Ben', '[2026-12-11 14:00+05:30, 2026-12-13 11:00+05:30)');

INSERT INTO room_bookings VALUES (101, 'Chen', '[2026-12-12 11:00+05:30, 2026-12-14 11:00+05:30)'), (102, 'Ben', '[2026-12-11 14:00+05:30, 2026-12-13 11:00+05:30)'); SELECT room, guest FROM room_bookings ORDER BY room, lower(period);

BEGIN; SELECT count(*) AS clashes FROM room_bookings WHERE room = 101 AND period && '[2026-12-13 00:00+05:30, 2026-12-13 12:00+05:30)';

-- session B
BEGIN; SELECT count(*) AS clashes FROM room_bookings WHERE room = 101 AND period && '[2026-12-15 00:00+05:30, 2026-12-15 12:00+05:30)'; INSERT INTO room_bookings VALUES (101, 'Dev', '[2026-12-15 10:00+05:30, 2026-12-16 10:00+05:30)'); COMMIT;

ROLLBACK;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • EXCLUDE enforces no-overlap rules
  • btree_gist enables = in GiST
  • Exclusive upper bounds allow back-to-back stays
  • Constraints beat check-then-insert
  • The index also serves availability queries

Common mistakes

  • Checking overlaps only in application code
  • Using inclusive end times

Follow-ups

  • How would you allow overlaps for cancelled bookings?
  • How does this behave under heavy write load?

Tips

  • Show the back-to-back case
68.postgresql-0068Hardsenior

Implement tenant isolation with row-level security driven by a session setting, and avoid the table-owner bypass.

ALTER TABLE ... ENABLE ROW LEVEL SECURITY plus a policy USING (tenant_id = current_setting('app.tenant_id')::int) makes every query see only the current tenant's rows, and WITH CHECK stops writes into other tenants. Table owners and superusers bypass RLS unless FORCE ROW LEVEL SECURITY is set. The application sets the tenant per transaction with SET LOCAL, which must happen on every pooled connection.

Full answer

Test data:

sql
CREATE TABLE invoices (id int, tenant_id int, amount int);
INSERT INTO invoices VALUES (1, 10, 500), (2, 10, 700), (3, 20, 900);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id', true)::int)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::int);
-- a non-superuser application role that owns the table (superusers always bypass RLS)
DO $$ BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'ibank_app') THEN CREATE ROLE ibank_app NOLOGIN; END IF;
  EXECUTE format('GRANT USAGE ON SCHEMA %I TO ibank_app', current_schema());
END $$;
ALTER TABLE invoices OWNER TO ibank_app;
sql
SET ROLE ibank_app; SELECT count(*) AS visible_as_owner FROM invoices;

Result:

text
 visible_as_owner
------------------
 3
(1 row)
sql
ALTER TABLE invoices FORCE ROW LEVEL SECURITY; SELECT count(*) AS visible_without_tenant FROM invoices;

Output:

text
 visible_without_tenant
------------------------
 0
(1 row)
sql
BEGIN; SET LOCAL app.tenant_id = '10'; SELECT id, amount FROM invoices ORDER BY id;

PostgreSQL returns:

text
 id | amount
----+--------
 1  | 500
 2  | 700
(2 rows)
sql
INSERT INTO invoices VALUES (4, 20, 100);

Result on PostgreSQL 17:

text
ERROR:  new row violates row-level security policy for table "invoices"
sql
ROLLBACK; BEGIN; SET LOCAL app.tenant_id = '20'; UPDATE invoices SET amount = amount + 1 RETURNING id, tenant_id, amount;

Result:

text
 id | tenant_id | amount
----+-----------+--------
 3  | 20        | 901
(1 row)
sql
COMMIT; RESET ROLE;

Output:

text
RESET

The demo switches to ibank_app, an ordinary role that owns the table, because superusers bypass RLS in every case. Even with RLS enabled, the table owner still sees all three rows, a common surprise in development where the app connects as the owner. After FORCE ROW LEVEL SECURITY, a session without a tenant setting sees nothing, because current_setting(..., true) returns NULL and the policy is never true. With tenant 10 set locally, only invoices 1 and 2 are visible, and inserting a row for tenant 20 fails with 'new row violates row-level security policy'. The UPDATE as tenant 20 touches only invoice 3, though it has no WHERE clause. Use a separate non-owner role for the application, SET LOCAL inside each transaction so pooled connections do not leak tenants, and index tenant_id.

sql
CREATE TABLE invoices (id int, tenant_id int, amount int);
INSERT INTO invoices VALUES (1, 10, 500), (2, 10, 700), (3, 20, 900);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id', true)::int)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::int);
-- a non-superuser application role that owns the table (superusers always bypass RLS)
DO $$ BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'ibank_app') THEN CREATE ROLE ibank_app NOLOGIN; END IF;
  EXECUTE format('GRANT USAGE ON SCHEMA %I TO ibank_app', current_schema());
END $$;
ALTER TABLE invoices OWNER TO ibank_app;

SET ROLE ibank_app; SELECT count(*) AS visible_as_owner FROM invoices;

ALTER TABLE invoices FORCE ROW LEVEL SECURITY; SELECT count(*) AS visible_without_tenant FROM invoices;

BEGIN; SET LOCAL app.tenant_id = '10'; SELECT id, amount FROM invoices ORDER BY id;

INSERT INTO invoices VALUES (4, 20, 100);

ROLLBACK; BEGIN; SET LOCAL app.tenant_id = '20'; UPDATE invoices SET amount = amount + 1 RETURNING id, tenant_id, amount;

COMMIT; RESET ROLE;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Policies filter rows for every query
  • WITH CHECK guards writes
  • Owners bypass RLS unless FORCE is set
  • SET LOCAL per transaction with pooling
  • Missing setting means no rows

Common mistakes

  • Testing RLS as the table owner
  • Using session-level SET with transaction pooling

Follow-ups

  • How does RLS affect query plans and performance?
  • How would you give support staff cross-tenant read access?

Tips

  • Show the owner bypass
69.postgresql-0069Hardsenior

Why do some UPDATEs bloat indexes while others do not? Show HOT updates and the role of fillfactor.

A heap-only tuple (HOT) update writes the new row version on the same page and skips index updates, which is possible only when no indexed column changes and the page has free space. Updates to indexed columns, or on full pages, must insert new index entries, causing index bloat and more WAL. A lower fillfactor leaves room on each page for HOT updates on frequently updated tables.

Full answer

Schema and sample rows:

sql
CREATE TABLE counters (id int PRIMARY KEY, views int, label text) WITH (fillfactor = 70);
CREATE INDEX counters_label ON counters (label);
INSERT INTO counters SELECT g, 0, 'item' || g FROM generate_series(1, 1000) g;
sql
BEGIN; UPDATE counters SET views = views + 1 WHERE id <= 100; SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_xact_user_tables WHERE relname = 'counters';

Output:

text
 n_tup_upd | n_tup_hot_upd
-----------+---------------
 100       | 56
(1 row)
sql
UPDATE counters SET label = label || '-x' WHERE id <= 100; SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_xact_user_tables WHERE relname = 'counters';

PostgreSQL returns:

text
 n_tup_upd | n_tup_hot_upd
-----------+---------------
 200       | 56
(1 row)
sql
COMMIT; SELECT reloptions::text FROM pg_class WHERE relname = 'counters';

Result on PostgreSQL 17:

text
    reloptions
-----------------
 {fillfactor=70}
(1 row)

pg_stat_xact_user_tables reports counts for the current transaction immediately, which makes the effect visible without waiting for the statistics collector. Changing only views, which is not indexed, produced 100 updates, and 56 of them were HOT; for the rest, the page had run out of free space, so the new version went to another page and needed new index entries. Changing label, which has an index, added 100 more updates and no more HOT ones, because each new version needed new entries in counters_label. The fillfactor of 70 left space on each page for the new versions. Practical rules: avoid indexing columns that change constantly, keep hot counters in narrow tables with a lower fillfactor, and watch n_tup_hot_upd against n_tup_upd in pg_stat_user_tables.

sql
CREATE TABLE counters (id int PRIMARY KEY, views int, label text) WITH (fillfactor = 70);
CREATE INDEX counters_label ON counters (label);
INSERT INTO counters SELECT g, 0, 'item' || g FROM generate_series(1, 1000) g;

BEGIN; UPDATE counters SET views = views + 1 WHERE id <= 100; SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_xact_user_tables WHERE relname = 'counters';

UPDATE counters SET label = label || '-x' WHERE id <= 100; SELECT n_tup_upd, n_tup_hot_upd FROM pg_stat_xact_user_tables WHERE relname = 'counters';

COMMIT; SELECT reloptions::text FROM pg_class WHERE relname = 'counters';

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • HOT updates skip index maintenance
  • They require unchanged indexed columns
  • They need free space on the page
  • Lower fillfactor leaves room
  • Monitor the HOT ratio

Common mistakes

  • Indexing frequently updated columns
  • Using fillfactor 100 on update-heavy tables

Follow-ups

  • How does pruning reclaim space within a page?
  • What fillfactor would you choose for an append-only table?

Tips

  • Compare the two update counts
70.postgresql-0070Hardsenior

After deleting most of a table, why does its size not shrink, and when is VACUUM FULL or pg_repack appropriate?

DELETE marks rows dead; plain VACUUM makes their space reusable for future inserts but normally does not return it to the operating system, except for empty pages at the end of the table. VACUUM FULL rewrites the table compactly but holds an ACCESS EXCLUSIVE lock for the whole rewrite, blocking all access. On busy systems, pg_repack rebuilds online with only brief locks.

Full answer

Sample schema and data:

sql
CREATE TABLE audit (id int PRIMARY KEY, payload text);
INSERT INTO audit SELECT g, repeat('p', 200) FROM generate_series(1, 20000) g;
sql
SELECT pg_size_pretty(pg_relation_size('audit')) AS before_delete;

PostgreSQL returns:

text
 before_delete
---------------
 4712 kB
(1 row)
sql
DELETE FROM audit WHERE id % 10 <> 0;

Result on PostgreSQL 17:

text
DELETE 18000
sql
VACUUM audit;

Result:

text
VACUUM
sql
SELECT pg_size_pretty(pg_relation_size('audit')) AS after_vacuum, count(*) AS rows_left FROM audit;

Output:

text
 after_vacuum | rows_left
--------------+-----------
 4712 kB      | 2000
(1 row)
sql
VACUUM FULL audit;

PostgreSQL returns:

text
VACUUM
sql
SELECT pg_size_pretty(pg_relation_size('audit')) AS after_vacuum_full;

Result on PostgreSQL 17:

text
 after_vacuum_full
-------------------
 472 kB
(1 row)

Deleting 90% of the rows scattered across every page leaves the table at its original size after VACUUM, because each page still holds some live rows and the freed space stays inside the file for reuse. VACUUM FULL rewrites the 2,000 surviving rows into a file about a tenth of the size. Each VACUUM is sent alone because it cannot run inside a transaction block. In production, prefer to avoid the problem: partition tables so old data is dropped as whole partitions, delete in batches with autovacuum keeping up, and use pg_repack when a rewrite is unavoidable on a live table.

sql
CREATE TABLE audit (id int PRIMARY KEY, payload text);
INSERT INTO audit SELECT g, repeat('p', 200) FROM generate_series(1, 20000) g;

SELECT pg_size_pretty(pg_relation_size('audit')) AS before_delete;

DELETE FROM audit WHERE id % 10 <> 0;

VACUUM audit;

SELECT pg_size_pretty(pg_relation_size('audit')) AS after_vacuum, count(*) AS rows_left FROM audit;

VACUUM FULL audit;

SELECT pg_size_pretty(pg_relation_size('audit')) AS after_vacuum_full;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • DELETE leaves dead rows
  • VACUUM makes space reusable, not smaller
  • VACUUM FULL rewrites under an exclusive lock
  • pg_repack rebuilds online
  • Partitioning avoids mass deletes

Common mistakes

  • Running VACUUM FULL on a busy production table
  • Expecting disk space back after plain VACUUM

Follow-ups

  • How does autovacuum decide when to run?
  • What is the visibility map used for?

Tips

  • Contrast the three sizes
71.postgresql-0071Hardsenior

Why can a prepared statement get slower after five executions? Explain custom versus generic plans.

For a prepared statement, PostgreSQL plans the first five executions with the actual parameter values (custom plans), then considers a generic plan that ignores the values and switches if its estimated cost is not worse on average. With skewed data, a generic plan that suits rare values can be terrible for common ones, or the reverse. plan_cache_mode = force_custom_plan or force_generic_plan overrides the choice.

Full answer

Setup for the example:

sql
CREATE TABLE orders (id int, status text);
INSERT INTO orders SELECT g, CASE WHEN g <= 20 THEN 'disputed' ELSE 'delivered' END FROM generate_series(1, 50000) g;
CREATE INDEX orders_status ON orders (status);
ANALYZE orders;
sql
PREPARE by_status(text) AS SELECT count(*) FROM orders WHERE status = $1; EXPLAIN (COSTS OFF) EXECUTE by_status('disputed');

Result on PostgreSQL 17:

text
Aggregate
  ->  Index Only Scan using orders_status on orders
        Index Cond: (status = 'disputed'::text)
sql
EXPLAIN (COSTS OFF) EXECUTE by_status('delivered');

Result:

text
Aggregate
  ->  Seq Scan on orders
        Filter: (status = 'delivered'::text)
sql
SET plan_cache_mode = force_generic_plan; EXPLAIN (COSTS OFF) EXECUTE by_status('delivered');

Output:

text
Aggregate
  ->  Index Only Scan using orders_status on orders
        Index Cond: (status = $1)
sql
SET plan_cache_mode = force_custom_plan; EXPLAIN (COSTS OFF) EXECUTE by_status('delivered');

PostgreSQL returns:

text
Aggregate
  ->  Seq Scan on orders
        Filter: (status = 'delivered'::text)

Custom plans use the actual value: an index-only scan for the 20 disputed orders and a sequential scan for the 49,980 delivered ones. The generic plan, forced here so the run is repeatable, is planned without knowing the value, so its condition shows the placeholder $1 and its row estimate is an average across statuses; here it picks an index-only scan, and that plan is then used for every value, including 'delivered', which matches almost the whole table and for which the custom plan prefers a sequential scan. In the default auto mode, PostgreSQL switches to the generic plan after five executions only if its estimated cost is not much worse than the custom plans seen so far, which with skewed data can lock in the wrong shape. Forcing custom plans restores value-specific planning at the cost of planning on every execution. Drivers that prepare statements on the server, such as JDBC after a threshold or psycopg with prepare_threshold, can trigger this, which makes it a common cause of a query that is fast in psql but slow in the application.

sql
CREATE TABLE orders (id int, status text);
INSERT INTO orders SELECT g, CASE WHEN g <= 20 THEN 'disputed' ELSE 'delivered' END FROM generate_series(1, 50000) g;
CREATE INDEX orders_status ON orders (status);
ANALYZE orders;

PREPARE by_status(text) AS SELECT count(*) FROM orders WHERE status = $1; EXPLAIN (COSTS OFF) EXECUTE by_status('disputed');

EXPLAIN (COSTS OFF) EXECUTE by_status('delivered');

SET plan_cache_mode = force_generic_plan; EXPLAIN (COSTS OFF) EXECUTE by_status('delivered');

SET plan_cache_mode = force_custom_plan; EXPLAIN (COSTS OFF) EXECUTE by_status('delivered');

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • First five executions use custom plans
  • Then a generic plan may be cached
  • Generic plans ignore parameter values
  • Skewed data makes generic plans risky
  • plan_cache_mode overrides the choice

Common mistakes

  • Comparing psql timings with driver behaviour without checking prepared plans
  • Forcing generic plans on skewed columns

Follow-ups

  • How do you see whether a plan is generic in production?
  • How does pg_stat_statements help here?

Tips

  • Point at $1 in the plan
72.postgresql-0072Hardsenior

Write a statement-level trigger with transition tables to maintain a summary table efficiently.

A statement-level AFTER trigger with REFERENCING NEW TABLE AS new_rows sees all rows affected by the statement as a table, so it can update a summary with one set-based query instead of firing once per row. This scales far better for bulk inserts and keeps the summary transactionally consistent with the base table.

Full answer

Tables and rows used here:

sql
CREATE TABLE sales (region text, amount int);
CREATE TABLE region_totals (region text PRIMARY KEY, total int NOT NULL);

CREATE FUNCTION add_to_totals() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO region_totals (region, total)
  SELECT region, sum(amount) FROM new_rows GROUP BY region
  ON CONFLICT (region) DO UPDATE SET total = region_totals.total + EXCLUDED.total;
  RAISE NOTICE 'summary updated from % rows', (SELECT count(*) FROM new_rows);
  RETURN NULL;
END;
$$;

CREATE TRIGGER sales_totals AFTER INSERT ON sales
  REFERENCING NEW TABLE AS new_rows
  FOR EACH STATEMENT EXECUTE FUNCTION add_to_totals();
sql
INSERT INTO sales SELECT CASE WHEN g % 2 = 0 THEN 'north' ELSE 'south' END, 10 FROM generate_series(1, 1000) g;

Result:

text
NOTICE:  summary updated from 1000 rows
INSERT 0 1000
sql
INSERT INTO sales VALUES ('east', 5), ('north', 7);

Output:

text
NOTICE:  summary updated from 2 rows
INSERT 0 2
sql
SELECT region, total FROM region_totals ORDER BY region;

PostgreSQL returns:

text
 region | total
--------+-------
 east   | 5
 north  | 5007
 south  | 5000
(3 rows)

The 1,000-row insert fires the trigger once, and its notice confirms it saw all 1,000 rows through the transition table; a row-level trigger would have run 1,000 separate upserts. The second insert adds a new region and increases north. The totals then match the base table exactly, and if the insert rolled back, the summary change would roll back with it. Concurrent inserts into the same region serialise on the summary row, so very hot summaries may need batching. UPDATE and DELETE need their own triggers with OLD TABLE as well.

sql
CREATE TABLE sales (region text, amount int);
CREATE TABLE region_totals (region text PRIMARY KEY, total int NOT NULL);

CREATE FUNCTION add_to_totals() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO region_totals (region, total)
  SELECT region, sum(amount) FROM new_rows GROUP BY region
  ON CONFLICT (region) DO UPDATE SET total = region_totals.total + EXCLUDED.total;
  RAISE NOTICE 'summary updated from % rows', (SELECT count(*) FROM new_rows);
  RETURN NULL;
END;
$$;

CREATE TRIGGER sales_totals AFTER INSERT ON sales
  REFERENCING NEW TABLE AS new_rows
  FOR EACH STATEMENT EXECUTE FUNCTION add_to_totals();

INSERT INTO sales SELECT CASE WHEN g % 2 = 0 THEN 'north' ELSE 'south' END, 10 FROM generate_series(1, 1000) g;

INSERT INTO sales VALUES ('east', 5), ('north', 7);

SELECT region, total FROM region_totals ORDER BY region;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Statement-level triggers fire once per statement
  • Transition tables expose affected rows
  • Set-based summary updates scale
  • Changes stay transactional
  • Hot summary rows can become contention points

Common mistakes

  • Row-level triggers for bulk-loaded summaries
  • Forgetting UPDATE and DELETE paths

Follow-ups

  • How would you handle UPDATEs that move rows between regions?
  • When is a materialized view better?

Tips

  • Show the notice
73.postgresql-0073Hardsenior

Swap the positions of two items under a unique constraint using a deferrable constraint.

A non-deferrable unique constraint is checked as each row changes, so swapping two values in one UPDATE can fail partway through. A DEFERRABLE constraint is checked at the end of each statement, and SET CONSTRAINTS ... DEFERRED postpones the check to COMMIT. Only constraints declared deferrable can be deferred, and deferrable unique constraints cannot be used as ON CONFLICT arbiters.

Full answer

Test data:

sql
CREATE TABLE playlist (song text, position int, CONSTRAINT playlist_pos_key UNIQUE (position));
CREATE TABLE playlist2 (song text, position int, CONSTRAINT playlist2_pos_key UNIQUE (position) DEFERRABLE INITIALLY IMMEDIATE);
INSERT INTO playlist VALUES ('intro', 1), ('chorus', 2), ('outro', 3);
INSERT INTO playlist2 SELECT * FROM playlist;
sql
UPDATE playlist SET position = CASE song WHEN 'intro' THEN 2 WHEN 'chorus' THEN 1 END WHERE song IN ('intro', 'chorus');

Output:

text
ERROR:  duplicate key value violates unique constraint "playlist_pos_key"
sql
UPDATE playlist2 SET position = CASE song WHEN 'intro' THEN 2 WHEN 'chorus' THEN 1 END WHERE song IN ('intro', 'chorus') RETURNING song, position;

PostgreSQL returns:

text
  song  | position
--------+----------
 intro  | 2
 chorus | 1
(2 rows)
sql
UPDATE playlist2 SET position = 1 WHERE song = 'outro';

Result on PostgreSQL 17:

text
ERROR:  duplicate key value violates unique constraint "playlist2_pos_key"
sql
BEGIN; SET CONSTRAINTS playlist2_pos_key DEFERRED; UPDATE playlist2 SET position = 1 WHERE song = 'outro'; UPDATE playlist2 SET position = 3 WHERE song = 'chorus'; COMMIT; SELECT song, position FROM playlist2 ORDER BY position;

Result:

text
  song  | position
--------+----------
 outro  | 1
 intro  | 2
 chorus | 3
(3 rows)

Swapping two positions in one UPDATE fails on the plain table, because a non-deferrable unique index is checked as each row changes, and the first changed row collides with the row not yet updated. The same single statement succeeds on the deferrable table even in IMMEDIATE mode: PostgreSQL checks deferrable unique constraints at the end of each statement. Moves that span several statements still fail in IMMEDIATE mode, as the third run shows. After SET CONSTRAINTS ... DEFERRED, the check runs at COMMIT, so outro and chorus can be moved one statement at a time. A design alternative is to store positions with gaps (10, 20, 30) or fractional ranks so that most reorderings touch one row.

sql
CREATE TABLE playlist (song text, position int, CONSTRAINT playlist_pos_key UNIQUE (position));
CREATE TABLE playlist2 (song text, position int, CONSTRAINT playlist2_pos_key UNIQUE (position) DEFERRABLE INITIALLY IMMEDIATE);
INSERT INTO playlist VALUES ('intro', 1), ('chorus', 2), ('outro', 3);
INSERT INTO playlist2 SELECT * FROM playlist;

UPDATE playlist SET position = CASE song WHEN 'intro' THEN 2 WHEN 'chorus' THEN 1 END WHERE song IN ('intro', 'chorus');

UPDATE playlist2 SET position = CASE song WHEN 'intro' THEN 2 WHEN 'chorus' THEN 1 END WHERE song IN ('intro', 'chorus') RETURNING song, position;

UPDATE playlist2 SET position = 1 WHERE song = 'outro';

BEGIN; SET CONSTRAINTS playlist2_pos_key DEFERRED; UPDATE playlist2 SET position = 1 WHERE song = 'outro'; UPDATE playlist2 SET position = 3 WHERE song = 'chorus'; COMMIT; SELECT song, position FROM playlist2 ORDER BY position;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Non-deferrable uniques are checked per row
  • Deferrable ones at statement end or commit
  • SET CONSTRAINTS DEFERRED inside a transaction
  • Deferrable uniques cannot arbitrate ON CONFLICT
  • Gapped positions reduce swaps

Common mistakes

  • Using temporary negative values as a workaround everywhere
  • Deferring constraints without need

Follow-ups

  • What is the cost of deferrable unique indexes?
  • How would you design drag-and-drop ordering at scale?

Tips

  • Show the statement-end check
74.postgresql-0074Hardsenior

Which lock does each common ALTER TABLE take? Inspect them in pg_locks inside a transaction.

Lock levels differ by operation: most ALTER TABLE forms take ACCESS EXCLUSIVE, which blocks even reads, while ADD CONSTRAINT ... NOT VALID for a foreign key, VALIDATE CONSTRAINT and CREATE INDEX CONCURRENTLY take weaker locks that allow reads and often writes. Checking pg_locks inside a transaction that runs the DDL shows exactly what a migration will hold.

Full answer

Schema and sample rows:

sql
CREATE TABLE parents (id int PRIMARY KEY);
CREATE TABLE children (id int, parent_id int);
INSERT INTO parents VALUES (1);
INSERT INTO children VALUES (1, 1);
CREATE VIEW my_locks AS
  SELECT c.relname::text AS rel, l.mode
  FROM pg_locks l JOIN pg_class c ON c.oid = l.relation
  WHERE l.pid = pg_backend_pid() AND c.relname IN ('parents', 'children');
sql
BEGIN; ALTER TABLE children ADD COLUMN note text; SELECT rel, mode FROM my_locks ORDER BY 1, 2;

PostgreSQL returns:

text
   rel    |         mode
----------+---------------------
 children | AccessExclusiveLock
(1 row)
sql
ROLLBACK; BEGIN; ALTER TABLE children ADD CONSTRAINT children_parent_fk FOREIGN KEY (parent_id) REFERENCES parents(id) NOT VALID; SELECT rel, mode FROM my_locks ORDER BY 1, 2;

Result on PostgreSQL 17:

text
   rel    |          mode
----------+-----------------------
 children | AccessShareLock
 children | ShareRowExclusiveLock
 parents  | AccessShareLock
 parents  | ShareRowExclusiveLock
(4 rows)
sql
COMMIT; BEGIN; ALTER TABLE children VALIDATE CONSTRAINT children_parent_fk; SELECT rel, mode FROM my_locks ORDER BY 1, 2;

Result:

text
   rel    |           mode
----------+--------------------------
 children | AccessShareLock
 children | ShareUpdateExclusiveLock
 parents  | AccessShareLock
 parents  | RowShareLock
(4 rows)
sql
COMMIT; BEGIN; CREATE INDEX children_parent_idx ON children (parent_id); SELECT rel, mode FROM my_locks ORDER BY 1, 2;

Output:

text
   rel    |    mode
----------+-----------
 children | ShareLock
(1 row)
sql
ROLLBACK;

PostgreSQL returns:

text
ROLLBACK

Adding a column takes AccessExclusiveLock on children, so even SELECTs on the table queue behind it, briefly if nothing blocks it. Adding the foreign key as NOT VALID takes ShareRowExclusiveLock on both tables, which blocks writes but not reads and finishes quickly because no rows are checked. VALIDATE CONSTRAINT then needs only ShareUpdateExclusiveLock on children, compatible with normal reads and writes, while it scans the table, plus a RowShareLock on parents. A plain CREATE INDEX takes ShareLock, which blocks writes for the whole build; CREATE INDEX CONCURRENTLY avoids that but cannot run inside a transaction, so it is not shown in this transaction-based check. The extra AccessShareLock entries are ordinary read locks taken while the statements read the tables. Splitting migrations into these weaker steps is the basis of zero-downtime schema changes.

sql
CREATE TABLE parents (id int PRIMARY KEY);
CREATE TABLE children (id int, parent_id int);
INSERT INTO parents VALUES (1);
INSERT INTO children VALUES (1, 1);
CREATE VIEW my_locks AS
  SELECT c.relname::text AS rel, l.mode
  FROM pg_locks l JOIN pg_class c ON c.oid = l.relation
  WHERE l.pid = pg_backend_pid() AND c.relname IN ('parents', 'children');

BEGIN; ALTER TABLE children ADD COLUMN note text; SELECT rel, mode FROM my_locks ORDER BY 1, 2;

ROLLBACK; BEGIN; ALTER TABLE children ADD CONSTRAINT children_parent_fk FOREIGN KEY (parent_id) REFERENCES parents(id) NOT VALID; SELECT rel, mode FROM my_locks ORDER BY 1, 2;

COMMIT; BEGIN; ALTER TABLE children VALIDATE CONSTRAINT children_parent_fk; SELECT rel, mode FROM my_locks ORDER BY 1, 2;

COMMIT; BEGIN; CREATE INDEX children_parent_idx ON children (parent_id); SELECT rel, mode FROM my_locks ORDER BY 1, 2;

ROLLBACK;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Most ALTER TABLE forms take ACCESS EXCLUSIVE
  • NOT VALID foreign keys lock briefly
  • VALIDATE uses a weaker lock
  • Plain CREATE INDEX blocks writes
  • Inspect pg_locks to verify a migration

Common mistakes

  • Assuming DDL only blocks writes
  • Building indexes without CONCURRENTLY on busy tables

Follow-ups

  • Which lock does DROP INDEX CONCURRENTLY take?
  • How do you simulate migration locking in CI?

Tips

  • Name the lock modes
75.postgresql-0075Hardsenior

CREATE UNIQUE INDEX CONCURRENTLY failed halfway. What state is the database in, and how do you recover?

If CREATE INDEX CONCURRENTLY fails, for example on duplicate values for a unique index or a cancelled build, it leaves an INVALID index behind. The invalid index is not used for queries but is still maintained on writes, adding cost, and it blocks a retry with the same name. Find it through pg_index.indisvalid, drop it with DROP INDEX CONCURRENTLY, fix the cause, and build again.

Full answer

Sample schema and data:

sql
CREATE TABLE customers (id int, email text);
INSERT INTO customers VALUES (1, 'a@x.in'), (2, 'b@x.in'), (3, 'a@x.in');
sql
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);

Result on PostgreSQL 17:

text
ERROR:  could not create unique index "customers_email_key"
sql
SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;

Result:

text
      index_name     | indisvalid
---------------------+------------
 customers_email_key | f
(1 row)
sql
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);

Output:

text
ERROR:  relation "customers_email_key" already exists
sql
DROP INDEX CONCURRENTLY customers_email_key;

PostgreSQL returns:

text
DROP INDEX
sql
DELETE FROM customers WHERE id = 3;

Result on PostgreSQL 17:

text
DELETE 1
sql
CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);

Result:

text
CREATE INDEX
sql
SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;

Output:

text
      index_name     | indisvalid
---------------------+------------
 customers_email_key | t
(1 row)

The concurrent build fails on the duplicate email, but the catalog still holds customers_email_key with indisvalid = false. A retry fails at once because the name is taken. Dropping the leftover index concurrently, removing the duplicate and rebuilding produces a valid index. Each concurrent command runs alone because none of them can run inside a transaction block. Migration tools should detect invalid indexes before retrying, and a periodic check for indisvalid = false catches leftovers from cancelled deployments.

sql
CREATE TABLE customers (id int, email text);
INSERT INTO customers VALUES (1, 'a@x.in'), (2, 'b@x.in'), (3, 'a@x.in');

CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);

SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;

CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);

DROP INDEX CONCURRENTLY customers_email_key;

DELETE FROM customers WHERE id = 3;

CREATE UNIQUE INDEX CONCURRENTLY customers_email_key ON customers (email);

SELECT indexrelid::regclass::text AS index_name, indisvalid FROM pg_index WHERE indrelid = 'customers'::regclass;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Failed concurrent builds leave INVALID indexes
  • Invalid indexes are maintained but unused
  • They block retries with the same name
  • Drop concurrently, fix, rebuild
  • Monitor indisvalid

Common mistakes

  • Ignoring leftover invalid indexes
  • Retrying without removing the failed index

Follow-ups

  • Why does a concurrent build need two table scans?
  • What does REINDEX CONCURRENTLY do?

Tips

  • Show indisvalid
76.postgresql-0076Hardsenior

An int4 primary key is about to run out of values. Show the failure and plan the move to bigint.

An integer identity or serial column tops out at 2,147,483,647; once the sequence reaches it, every insert fails. Detect it early by comparing sequence values with the type's maximum. The fix is migrating to bigint, which on a big table means adding a new column, backfilling in batches, building indexes concurrently and swapping in a short transaction, rather than one long ALTER COLUMN TYPE rewrite.

Full answer

Setup for the example:

sql
CREATE TABLE clicks (id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, url text);
SELECT setval(pg_get_serial_sequence('clicks', 'id'), 2147483646);
sql
INSERT INTO clicks (url) VALUES ('/a') RETURNING id;

Result:

text
     id
------------
 2147483647
(1 row)
sql
INSERT INTO clicks (url) VALUES ('/b');

Output:

text
ERROR:  nextval: reached maximum value of sequence "clicks_id_seq" (2147483647)
sql
SELECT seqrelid::regclass::text AS sequence, seqtypid::regtype::text AS type, round(100.0 * (SELECT last_value FROM clicks_id_seq) / seqmax, 2) AS pct_used FROM pg_sequence WHERE seqrelid = 'clicks_id_seq'::regclass;

PostgreSQL returns:

text
    sequence   |   type  | pct_used
---------------+---------+----------
 clicks_id_seq | integer | 100.00
(1 row)
sql
ALTER TABLE clicks ALTER COLUMN id TYPE bigint; ALTER SEQUENCE clicks_id_seq AS bigint MAXVALUE 9223372036854775807; INSERT INTO clicks (url) VALUES ('/b') RETURNING id;

Result on PostgreSQL 17:

text
     id
------------
 2147483648
(1 row)

The last value, 2,147,483,647, is handed out, and the next insert fails with 'nextval: reached maximum value of sequence'. The monitoring query reports 100% use; running it for every sequence and alerting at around 70% leaves months to react. On this tiny table, ALTER COLUMN TYPE bigint is instant enough, and the identity sequence must be widened as well, after which inserts continue. On a table with billions of rows, that ALTER rewrites the table under an exclusive lock for hours, so the online approach is: add id_new bigint, fill it with a trigger for new rows and batches for old ones, create a unique index concurrently, then swap columns and constraints in one short transaction. Using bigint from the start avoids all of this.

sql
CREATE TABLE clicks (id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, url text);
SELECT setval(pg_get_serial_sequence('clicks', 'id'), 2147483646);

INSERT INTO clicks (url) VALUES ('/a') RETURNING id;

INSERT INTO clicks (url) VALUES ('/b');

SELECT seqrelid::regclass::text AS sequence, seqtypid::regtype::text AS type, round(100.0 * (SELECT last_value FROM clicks_id_seq) / seqmax, 2) AS pct_used FROM pg_sequence WHERE seqrelid = 'clicks_id_seq'::regclass;

ALTER TABLE clicks ALTER COLUMN id TYPE bigint; ALTER SEQUENCE clicks_id_seq AS bigint MAXVALUE 9223372036854775807; INSERT INTO clicks (url) VALUES ('/b') RETURNING id;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • int4 keys stop at about 2.1 billion
  • Monitor sequence usage
  • ALTER TYPE rewrites the table
  • Migrate online with a new column and backfill
  • Widen the sequence too

Common mistakes

  • Using int for high-volume keys
  • Running ALTER COLUMN TYPE on a huge table at peak

Follow-ups

  • How do foreign keys referencing the id complicate the migration?
  • Why might the sequence be bigint while the column is int?

Tips

  • Show the monitoring query
77.postgresql-0077Hardsenior

Why does inserting a child row wait on a parent row locked FOR UPDATE, and how does FOR NO KEY UPDATE avoid it?

Inserting a child row makes PostgreSQL take a FOR KEY SHARE lock on the referenced parent row, so the parent cannot be deleted or have its key changed meanwhile. FOR UPDATE conflicts with FOR KEY SHARE, so a transaction that locks the parent with FOR UPDATE blocks every child insert. FOR NO KEY UPDATE, which is what a plain UPDATE of non-key columns takes, does not conflict with it.

Full answer

Tables and rows used here:

sql
CREATE TABLE orders (id int PRIMARY KEY, status text);
CREATE TABLE order_events (order_id int REFERENCES orders(id), note text);
INSERT INTO orders VALUES (1, 'new');
sql
BEGIN; SELECT id FROM orders WHERE id = 1 FOR UPDATE;

Output:

text
 id
----
 1
(1 row)

In a second session:

sql
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');

PostgreSQL returns:

text
ERROR:  canceling statement due to lock timeout
sql
ROLLBACK; BEGIN; SELECT id FROM orders WHERE id = 1 FOR NO KEY UPDATE;

Result on PostgreSQL 17:

text
 id
----
 1
(1 row)

In a second session:

sql
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');

Result:

text
INSERT 0 1
sql
UPDATE orders SET status = 'paid' WHERE id = 1; COMMIT; SELECT o.status, count(e.*) AS events FROM orders o LEFT JOIN order_events e ON e.order_id = o.id GROUP BY o.status;

Output:

text
 status | events
--------+--------
 paid   | 1
(1 row)

While A holds FOR UPDATE on order 1, B's child insert waits for the key-share lock and gives up after 200 ms with a lock timeout. With FOR NO KEY UPDATE, the same insert succeeds at once, and A can still update the order's status. Code that locks a parent only to change non-key columns should therefore use FOR NO KEY UPDATE. The same conflict explains lock waits in high-traffic systems where one hot parent row, such as an account, receives many child inserts while being locked by other work.

sql
CREATE TABLE orders (id int PRIMARY KEY, status text);
CREATE TABLE order_events (order_id int REFERENCES orders(id), note text);
INSERT INTO orders VALUES (1, 'new');

BEGIN; SELECT id FROM orders WHERE id = 1 FOR UPDATE;

-- session B
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');

ROLLBACK; BEGIN; SELECT id FROM orders WHERE id = 1 FOR NO KEY UPDATE;

-- session B
SET lock_timeout = '200ms'; INSERT INTO order_events VALUES (1, 'payment received');

UPDATE orders SET status = 'paid' WHERE id = 1; COMMIT; SELECT o.status, count(e.*) AS events FROM orders o LEFT JOIN order_events e ON e.order_id = o.id GROUP BY o.status;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Child inserts take FOR KEY SHARE on the parent
  • FOR UPDATE blocks them
  • FOR NO KEY UPDATE does not
  • Plain UPDATEs of non-key columns use NO KEY UPDATE
  • Hot parents cause lock waits

Common mistakes

  • Using FOR UPDATE by habit for every parent lock
  • Updating primary key columns casually

Follow-ups

  • Which lock does DELETE take on the parent?
  • How do you see lock waits in pg_stat_activity?

Tips

  • Name FOR KEY SHARE
78.postgresql-0078Hardsenior

A query on an indexed bigint column does a sequential scan when the application passes a numeric parameter. Why?

When the parameter's type differs from the column's, PostgreSQL may cast the column instead of the value; WHERE id = 42.0 compares id::numeric to a numeric, and an index on id cannot be used for that expression. The fix is passing parameters of the column's type, or casting the parameter explicitly. ORMs and drivers that send numeric or text types are a common source.

Full answer

Test data:

sql
CREATE TABLE payments (id bigint PRIMARY KEY, amount int);
INSERT INTO payments SELECT g, g % 1000 FROM generate_series(1, 50000) g;
ANALYZE payments;
sql
EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42;

PostgreSQL returns:

text
Index Scan using payments_pkey on payments
  Index Cond: (id = 42)
sql
EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0;

Result on PostgreSQL 17:

text
Seq Scan on payments
  Filter: ((id)::numeric = 42.0)
sql
PREPARE by_id(numeric) AS SELECT amount FROM payments WHERE id = $1; EXPLAIN (COSTS OFF) EXECUTE by_id(42);

Result:

text
Seq Scan on payments
  Filter: ((id)::numeric = '42'::numeric)
sql
EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0::bigint;

Output:

text
Index Scan using payments_pkey on payments
  Index Cond: (id = '42'::bigint)

An integer literal uses the primary key index. The literal 42.0 is numeric, and the plan shows a sequential scan with the filter (id)::numeric = 42.0 on all 50,000 rows. A prepared statement whose parameter is declared numeric behaves the same, which is how this appears in applications: the driver declares the parameter type, not the value. Casting the parameter to bigint restores the index scan. Check for such casts on the column side of conditions in EXPLAIN output, and declare parameter types to match the columns.

sql
CREATE TABLE payments (id bigint PRIMARY KEY, amount int);
INSERT INTO payments SELECT g, g % 1000 FROM generate_series(1, 50000) g;
ANALYZE payments;

EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42;

EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0;

PREPARE by_id(numeric) AS SELECT amount FROM payments WHERE id = $1; EXPLAIN (COSTS OFF) EXECUTE by_id(42);

EXPLAIN (COSTS OFF) SELECT amount FROM payments WHERE id = 42.0::bigint;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Mismatched types can cast the column
  • Casting the column prevents index use
  • Drivers choose parameter types
  • Cast the parameter, not the column
  • Look for casts in EXPLAIN filters

Common mistakes

  • Sending numeric parameters for integer keys
  • Comparing text columns with integer parameters

Follow-ups

  • Why can PostgreSQL not cast the numeric to bigint itself?
  • How do you see parameter types in pg_stat_statements?

Tips

  • Point at the cast in the filter
79.postgresql-0079Hardsenior

Pass a list of ids as one array parameter with = ANY($1) instead of building a long IN list.

WHERE id = ANY($1) with an array parameter keeps one statement text for any list length, so pg_stat_statements groups it as one query and prepared plans can be reused. A generated IN (...) list with many placeholders produces a different statement per length and can hit driver limits on parameter counts. Both use the index the same way.

Full answer

Schema and sample rows:

sql
CREATE TABLE users (id int PRIMARY KEY, name text);
INSERT INTO users SELECT g, 'user' || g FROM generate_series(1, 10000) g;
ANALYZE users;
sql
PREPARE by_ids(int[]) AS SELECT id, name FROM users WHERE id = ANY($1) ORDER BY id; EXECUTE by_ids(ARRAY[5, 42, 9999]);

Result on PostgreSQL 17:

text
  id  |   name
------+----------
 5    | user5
 42   | user42
 9999 | user9999
(3 rows)
sql
EXECUTE by_ids('{}');

Result:

text
 id | name
----+------
(0 rows)
sql
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id = ANY('{5,42,9999}'::int[]);

Output:

text
Index Only Scan using users_pkey on users
  Index Cond: (id = ANY ('{5,42,9999}'::integer[]))
sql
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id IN (5, 42, 9999);

PostgreSQL returns:

text
Index Only Scan using users_pkey on users
  Index Cond: (id = ANY ('{5,42,9999}'::integer[]))

The same prepared statement serves three ids and an empty list, which returns no rows instead of failing as an empty IN () would. The two plans are identical: PostgreSQL rewrites IN with a list of constants into = ANY of an array, and both use the primary key index. In application code, pass a native array, for example a Python list with psycopg, which adapts it to an int[] parameter. For very large lists, tens of thousands of ids, joining against unnest($1) or a temporary table can plan better than a giant array.

sql
CREATE TABLE users (id int PRIMARY KEY, name text);
INSERT INTO users SELECT g, 'user' || g FROM generate_series(1, 10000) g;
ANALYZE users;

PREPARE by_ids(int[]) AS SELECT id, name FROM users WHERE id = ANY($1) ORDER BY id; EXECUTE by_ids(ARRAY[5, 42, 9999]);

EXECUTE by_ids('{}');

EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id = ANY('{5,42,9999}'::int[]);

EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id IN (5, 42, 9999);

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • = ANY($1) takes an array parameter
  • One statement text for any list length
  • Empty arrays are valid
  • IN lists become = ANY internally
  • Use unnest or temp tables for huge lists

Common mistakes

  • Building IN lists by string concatenation
  • Generating one statement per list length

Follow-ups

  • How does pg_stat_statements normalise IN lists?
  • When would you use a VALUES join instead?

Tips

  • Show the empty-array case
80.postgresql-0080Hardsenior

Why does EXPLAIN report Subplans Removed for WHERE day >= current_date - 7, and how does that differ from plan-time pruning?

Plan-time pruning needs constants. current_date and now() are STABLE, not IMMUTABLE, so the planner keeps every partition the constant parts allow and PostgreSQL prunes the rest at executor start-up, reported as Subplans Removed. Generic prepared plans rely on the same start-up pruning.

Full answer

Sample schema and data:

sql
CREATE TABLE metrics (day date, value int) PARTITION BY RANGE (day);
CREATE TABLE metrics_old PARTITION OF metrics FOR VALUES FROM ('2000-01-01') TO ('2026-01-01');
CREATE TABLE metrics_2026 PARTITION OF metrics FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
CREATE TABLE metrics_future PARTITION OF metrics FOR VALUES FROM ('2027-01-01') TO ('2100-01-01');
INSERT INTO metrics VALUES ('2025-06-01', 1), ('2026-11-30', 2), ('2027-03-01', 3);
sql
EXPLAIN (COSTS OFF) SELECT count(*) FROM metrics WHERE day >= date '2026-11-27';

Result:

text
Aggregate
  ->  Append
        ->  Seq Scan on metrics_2026 metrics_1
              Filter: (day >= '2026-11-27'::date)
        ->  Seq Scan on metrics_future metrics_2
              Filter: (day >= '2026-11-27'::date)
sql
EXPLAIN (COSTS OFF) SELECT count(*) FROM metrics WHERE day >= current_date - 7 AND day < date '2027-01-01';

Output:

text
Aggregate
  ->  Append
        Subplans Removed: 1
        ->  Seq Scan on metrics_2026 metrics_1
              Filter: ((day < '2027-01-01'::date) AND (day >= (CURRENT_DATE - 7)))
sql
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM metrics WHERE day >= current_date - 7 AND day < date '2027-01-01';

PostgreSQL returns:

text
Aggregate (actual rows=1 loops=1)
  ->  Append (actual rows=1 loops=1)
        Subplans Removed: 1
        ->  Seq Scan on metrics_2026 metrics_1 (actual rows=1 loops=1)
              Filter: ((day < '2027-01-01'::date) AND (day >= (CURRENT_DATE - 7)))

With a constant date, the plan lists only the 2026 and future partitions. With current_date, the planner can use only the constant upper bound, so the plan keeps the old and 2026 partitions; the old one is then removed at executor start-up, shown as 'Subplans Removed: 1'. Plain EXPLAIN shows this too because it initialises the executor, and EXPLAIN ANALYZE confirms that only metrics_2026 was scanned. The output depends on the box's date only through which partition holds current_date - 7; this was run on 4 December 2026. Run-time pruning makes such queries efficient, but planning still considers every partition, so very high partition counts still cost planning time.

sql
CREATE TABLE metrics (day date, value int) PARTITION BY RANGE (day);
CREATE TABLE metrics_old PARTITION OF metrics FOR VALUES FROM ('2000-01-01') TO ('2026-01-01');
CREATE TABLE metrics_2026 PARTITION OF metrics FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
CREATE TABLE metrics_future PARTITION OF metrics FOR VALUES FROM ('2027-01-01') TO ('2100-01-01');
INSERT INTO metrics VALUES ('2025-06-01', 1), ('2026-11-30', 2), ('2027-03-01', 3);

EXPLAIN (COSTS OFF) SELECT count(*) FROM metrics WHERE day >= date '2026-11-27';

EXPLAIN (COSTS OFF) SELECT count(*) FROM metrics WHERE day >= current_date - 7 AND day < date '2027-01-01';

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT count(*) FROM metrics WHERE day >= current_date - 7 AND day < date '2027-01-01';

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • Plan-time pruning needs constants
  • STABLE functions prune at executor start
  • EXPLAIN ANALYZE shows Subplans Removed
  • Generic plans rely on run-time pruning
  • Many partitions still cost planning time

Common mistakes

  • Concluding that pruning failed from plain EXPLAIN
  • Thousands of partitions on latency-sensitive tables

Follow-ups

  • How does enable_partition_pruning affect this?
  • Can pruning happen during a join?

Tips

  • Contrast the two EXPLAIN forms