← Interview prep

PostgreSQL interview questions

SQL depth, indexing, transactions, and Postgres internals.

100 questions · Page 5 of 5

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

Page 5 of 5

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

81.postgresql-0081Hardsenior

Delete millions of old rows without long locks or replication lag, using batches in a procedure.

One huge DELETE holds locks and a long transaction, generates a burst of WAL that replicas must replay, and leaves dead rows for one giant VACUUM. Deleting in batches of a few thousand rows with a COMMIT between them, from a procedure (PostgreSQL 11+) or a script, keeps each transaction short. Partition-based retention, which drops a partition instead, is better still.

Full answer

Setup for the example:

sql
CREATE TABLE logs (id bigint PRIMARY KEY, created date);
INSERT INTO logs SELECT g, date '2026-01-01' + (g % 330) FROM generate_series(1, 30000) g;

CREATE PROCEDURE purge_logs(before date, batch int)
LANGUAGE plpgsql AS $$
DECLARE
  removed int;
  total int := 0;
  rounds int := 0;
BEGIN
  LOOP
    DELETE FROM logs WHERE id IN (SELECT id FROM logs WHERE created < before ORDER BY id LIMIT batch);
    GET DIAGNOSTICS removed = ROW_COUNT;
    EXIT WHEN removed = 0;
    total := total + removed;
    rounds := rounds + 1;
    COMMIT;
  END LOOP;
  RAISE NOTICE 'removed % rows in % batches', total, rounds;
END;
$$;
sql
CALL purge_logs('2026-04-01', 2500);

Output:

text
NOTICE:  removed 8189 rows in 4 batches
CALL
sql
SELECT min(created) AS oldest, count(*) AS remaining FROM logs;

PostgreSQL returns:

text
   oldest   | remaining
------------+-----------
 2026-04-01 | 21811
(1 row)

The procedure removes rows older than April in batches of 2,500, committing after each batch, which a function cannot do; the notice reports the total and the number of batches. Each batch selects ids through the primary key, so it stays cheap as the table shrinks; with an index on created, the subquery would also avoid scanning. In production, add a short pg_sleep between batches to let replicas and autovacuum keep up, run outside peak hours, and log progress. CALL must not be wrapped in an explicit transaction block, or the COMMITs inside fail.

sql
CREATE TABLE logs (id bigint PRIMARY KEY, created date);
INSERT INTO logs SELECT g, date '2026-01-01' + (g % 330) FROM generate_series(1, 30000) g;

CREATE PROCEDURE purge_logs(before date, batch int)
LANGUAGE plpgsql AS $$
DECLARE
  removed int;
  total int := 0;
  rounds int := 0;
BEGIN
  LOOP
    DELETE FROM logs WHERE id IN (SELECT id FROM logs WHERE created < before ORDER BY id LIMIT batch);
    GET DIAGNOSTICS removed = ROW_COUNT;
    EXIT WHEN removed = 0;
    total := total + removed;
    rounds := rounds + 1;
    COMMIT;
  END LOOP;
  RAISE NOTICE 'removed % rows in % batches', total, rounds;
END;
$$;

CALL purge_logs('2026-04-01', 2500);

SELECT min(created) AS oldest, count(*) AS remaining FROM logs;

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

Key points

  • Large single deletes cause long locks and WAL bursts
  • Batch with COMMIT between rounds
  • Procedures can commit, functions cannot
  • Pause between batches for replicas
  • Partition dropping is better still

Common mistakes

  • Deleting 100 million rows in one statement
  • Calling the procedure inside BEGIN ... COMMIT

Follow-ups

  • How would you resume after an interruption?
  • How do batch sizes affect lock and WAL behaviour?

Tips

  • Show the notice
82.postgresql-0082Hardsenior

Build weighted full-text search with a generated tsvector column, websearch_to_tsquery and ts_rank.

A stored generated column holding setweight(to_tsvector(title), 'A') || setweight(to_tsvector(body), 'B') keeps the search vector in sync automatically, and a GIN index on it makes matching fast. websearch_to_tsquery accepts user input with quotes, OR and minus signs safely, and ts_rank orders results so title matches score above body matches.

Full answer

Tables and rows used here:

sql
CREATE TABLE articles (
  id int PRIMARY KEY,
  title text,
  body text,
  search tsvector GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(body, '')), 'B')) STORED
);
CREATE INDEX articles_search ON articles USING gin (search);
INSERT INTO articles (id, title, body) VALUES
  (1, 'Indexing strategies', 'How B-tree and GIN indexes speed up queries.'),
  (2, 'Query tuning basics', 'Reading plans and choosing indexes for slow queries.'),
  (3, 'Backups', 'Point in time recovery keeps data safe.');
sql
SELECT id, title, round(ts_rank(search, q)::numeric, 3) AS rank FROM articles, websearch_to_tsquery('english', 'index queries') q WHERE search @@ q ORDER BY rank DESC, id;

PostgreSQL returns:

text
 id |        title        |  rank
----+---------------------+-------
 2  | Query tuning basics | 0.683
 1  | Indexing strategies | 0.504
(2 rows)
sql
SELECT websearch_to_tsquery('english', '"point in time" -backups or tuning')::text AS parsed;

Result on PostgreSQL 17:

text
                  parsed
-----------------------------------------
 'point' <2> 'time' & !'backup' | 'tune'
(1 row)
sql
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english', 'recovery');

Result:

text
Bitmap Heap Scan on articles
  Recheck Cond: (search @@ '''recoveri'''::tsquery)
  ->  Bitmap Index Scan on articles_search
        Index Cond: (search @@ '''recoveri'''::tsquery)

Both indexing articles match 'index queries' after stemming (indexes and indexing reduce to index, queries to queri), and article 3 does not. Each matching article has one search word in its A-weighted title and both words in its body, and ts_rank's weighting and frequency scoring puts article 2 slightly ahead. The parsed query shows how websearch syntax becomes tsquery operators: the quoted phrase becomes a sequence with <2> rather than <->, because the dropped stop word 'in' still occupies a position, the minus sign becomes NOT and 'or' becomes |, and stop words such as 'in' are dropped. The GIN index serves the match, shown here with sequential scans disabled because the table is tiny. The generated column means application code never has to remember to update the vector.

sql
CREATE TABLE articles (
  id int PRIMARY KEY,
  title text,
  body text,
  search tsvector GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(body, '')), 'B')) STORED
);
CREATE INDEX articles_search ON articles USING gin (search);
INSERT INTO articles (id, title, body) VALUES
  (1, 'Indexing strategies', 'How B-tree and GIN indexes speed up queries.'),
  (2, 'Query tuning basics', 'Reading plans and choosing indexes for slow queries.'),
  (3, 'Backups', 'Point in time recovery keeps data safe.');

SELECT id, title, round(ts_rank(search, q)::numeric, 3) AS rank FROM articles, websearch_to_tsquery('english', 'index queries') q WHERE search @@ q ORDER BY rank DESC, id;

SELECT websearch_to_tsquery('english', '"point in time" -backups or tuning')::text AS parsed;

SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english', 'recovery');

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

Key points

  • Generated tsvector columns stay in sync
  • setweight ranks title above body
  • websearch_to_tsquery parses user input safely
  • ts_rank orders results
  • GIN indexes serve @@

Common mistakes

  • Building tsquery strings from raw user input
  • Recomputing to_tsvector in every query

Follow-ups

  • How would you support multiple languages?
  • When is a search engine such as OpenSearch worth adding?

Tips

  • Explain the weights
83.postgresql-0083Hardsenior

Find foreign keys whose referencing columns have no index, using the system catalogs.

PostgreSQL indexes the referenced primary key but not the referencing column. Without an index on the child column, deleting or updating a parent scans the whole child table, and joins from parent to children are slow. A catalog query comparing pg_constraint foreign keys with pg_index leading columns lists the gaps.

Full answer

Test data:

sql
CREATE TABLE customers (id int PRIMARY KEY);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int REFERENCES customers(id));
CREATE TABLE reviews (id int PRIMARY KEY, customer_id int REFERENCES customers(id), order_id int REFERENCES orders(id));
CREATE INDEX reviews_customer ON reviews (customer_id);
sql
SELECT c.conrelid::regclass::text AS table_name, c.conname AS fk, a.attname AS column_name
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
  AND c.connamespace = current_schema()::regnamespace
  AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1])
ORDER BY 1, 2;

Result on PostgreSQL 17:

text
 table_name |            fk           | column_name
------------+-------------------------+-------------
 orders     | orders_customer_id_fkey | customer_id
 reviews    | reviews_order_id_fkey   | order_id
(2 rows)

The query reports orders.customer_id and reviews.order_id, while reviews.customer_id is skipped because an index starts with that column. It checks only the first column of each key, which covers the common single-column case; composite foreign keys need a comparison of the full column lists. Not every foreign key needs an index: tiny tables and parents that are never deleted can do without, but on large child tables the missing index turns each parent delete into a full scan while holding locks.

sql
CREATE TABLE customers (id int PRIMARY KEY);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int REFERENCES customers(id));
CREATE TABLE reviews (id int PRIMARY KEY, customer_id int REFERENCES customers(id), order_id int REFERENCES orders(id));
CREATE INDEX reviews_customer ON reviews (customer_id);

SELECT c.conrelid::regclass::text AS table_name, c.conname AS fk, a.attname AS column_name
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
  AND c.connamespace = current_schema()::regnamespace
  AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1])
ORDER BY 1, 2;

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

Key points

  • Referencing columns are not indexed automatically
  • Missing indexes slow parent deletes and joins
  • pg_constraint lists foreign keys
  • pg_index shows leading columns
  • Composite keys need full comparison

Common mistakes

  • Assuming foreign keys create indexes
  • Indexing every foreign key blindly on tiny tables

Follow-ups

  • How would you extend this to composite keys?
  • What does a missing index do to ON DELETE CASCADE?

Tips

  • Explain the leading column check
84.postgresql-0084Hardsenior

A single counter row receives thousands of updates per second and becomes a bottleneck. Design an alternative and show it.

Every update to one row serialises on its row lock and creates a new row version, so a global counter becomes a queue. Spread the writes across N shard rows chosen at random or by session, and sum them when reading; or append events and aggregate periodically. Exactness is kept, and contention drops roughly by the number of shards.

Full answer

Schema and sample rows:

sql
CREATE TABLE page_views (page text, shard int, views bigint NOT NULL DEFAULT 0, PRIMARY KEY (page, shard));
INSERT INTO page_views SELECT 'home', s, 0 FROM generate_series(0, 7) s;
sql
UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 3; UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 5; UPDATE page_views SET views = views + 2 WHERE page = 'home' AND shard = 3;

Result:

text
UPDATE 1
sql
SELECT page, sum(views) AS total_views, count(*) AS shards FROM page_views GROUP BY page;

Output:

text
 page | total_views | shards
------+-------------+--------
 home | 4           | 8
(1 row)
sql
BEGIN; UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 1;

PostgreSQL returns:

text
UPDATE 1

In a second session:

sql
SET lock_timeout = '200ms'; UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 6; SELECT sum(views) AS total_seen_by_b FROM page_views;

Result on PostgreSQL 17:

text
 total_seen_by_b
-----------------
 5
(1 row)
sql
COMMIT; SELECT sum(views) AS total FROM page_views;

Result:

text
 total
-------
 6
(1 row)

Increments land on different shards, chosen in real code with something like floor(random() * 8), and the read sums them to 4. While session A holds an open increment on shard 1, session B increments shard 6 without waiting and sees the committed total of 5, excluding A's pending change. With a single row, B would have queued behind A. Other designs: an append-only events table rolled up every minute, which also gives history; an in-memory counter in Redis flushed periodically when slight loss is acceptable; and lowering fillfactor so the frequent updates stay HOT.

sql
CREATE TABLE page_views (page text, shard int, views bigint NOT NULL DEFAULT 0, PRIMARY KEY (page, shard));
INSERT INTO page_views SELECT 'home', s, 0 FROM generate_series(0, 7) s;

UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 3; UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 5; UPDATE page_views SET views = views + 2 WHERE page = 'home' AND shard = 3;

SELECT page, sum(views) AS total_views, count(*) AS shards FROM page_views GROUP BY page;

BEGIN; UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 1;

-- session B
SET lock_timeout = '200ms'; UPDATE page_views SET views = views + 1 WHERE page = 'home' AND shard = 6; SELECT sum(views) AS total_seen_by_b FROM page_views;

COMMIT; SELECT sum(views) AS total FROM page_views;

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

Key points

  • One hot row serialises all writers
  • Sharded rows spread lock contention
  • Reads sum the shards
  • Event tables plus roll-ups give history
  • Choose by exactness and latency needs

Common mistakes

  • A single global counter row under heavy write load
  • Using SELECT count(*) on a huge table for every page view

Follow-ups

  • How many shards would you choose?
  • How would you make the roll-up job idempotent?

Tips

  • Show B not waiting
85.postgresql-0085Hardsenior

Design reliable event publishing from a PostgreSQL-backed service with the transactional outbox pattern.

Write the business change and an outbox row in the same transaction, so either both happen or neither does. A relay process reads unsent outbox rows with FOR UPDATE SKIP LOCKED, publishes them to the broker, and marks them sent; consumers deduplicate by event id because delivery is at least once. This avoids the dual-write problem of committing to the database and publishing separately.

Full answer

Sample schema and data:

sql
CREATE TABLE orders (id int PRIMARY KEY, status text);
CREATE TABLE outbox (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  topic text NOT NULL,
  payload jsonb NOT NULL,
  sent_at timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;
sql
BEGIN; INSERT INTO orders VALUES (1, 'paid'); INSERT INTO outbox (topic, payload) VALUES ('order.paid', '{"order_id": 1}'); COMMIT;

Output:

text
COMMIT
sql
BEGIN; INSERT INTO orders VALUES (2, 'paid'); INSERT INTO outbox (topic, payload) VALUES ('order.paid', '{"order_id": 2}'); ROLLBACK; SELECT (SELECT count(*) FROM orders) AS orders, (SELECT count(*) FROM outbox) AS events;

PostgreSQL returns:

text
 orders | events
--------+--------
 1      | 1
(1 row)
sql
BEGIN; SELECT id, topic, payload FROM outbox WHERE sent_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED;

Result on PostgreSQL 17:

text
 id |   topic    |     payload
----+------------+-----------------
 1  | order.paid | {"order_id": 1}
(1 row)
sql
UPDATE outbox SET sent_at = now() WHERE id = 1; COMMIT; SELECT count(*) FILTER (WHERE sent_at IS NULL) AS unsent FROM outbox;

Result:

text
 unsent
--------
 0
(1 row)

The first transaction stores the order and its event together; the second rolls back and leaves neither, so the database and the event stream cannot disagree. The relay picks unsent events with SKIP LOCKED, so several relay instances can run, publishes them (outside this demo) and marks them sent. If the relay crashes after publishing but before committing, the event is published again, which is why consumers must be idempotent. Further points: keep outbox rows small, delete or partition sent rows, preserve order per aggregate if consumers need it, and consider logical decoding tools such as Debezium when polling latency matters.

sql
CREATE TABLE orders (id int PRIMARY KEY, status text);
CREATE TABLE outbox (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  topic text NOT NULL,
  payload jsonb NOT NULL,
  sent_at timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;

BEGIN; INSERT INTO orders VALUES (1, 'paid'); INSERT INTO outbox (topic, payload) VALUES ('order.paid', '{"order_id": 1}'); COMMIT;

BEGIN; INSERT INTO orders VALUES (2, 'paid'); INSERT INTO outbox (topic, payload) VALUES ('order.paid', '{"order_id": 2}'); ROLLBACK; SELECT (SELECT count(*) FROM orders) AS orders, (SELECT count(*) FROM outbox) AS events;

BEGIN; SELECT id, topic, payload FROM outbox WHERE sent_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED;

UPDATE outbox SET sent_at = now() WHERE id = 1; COMMIT; SELECT count(*) FILTER (WHERE sent_at IS NULL) AS unsent FROM outbox;

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

Key points

  • Write the change and the event in one transaction
  • A relay publishes unsent rows
  • SKIP LOCKED lets relays scale
  • Delivery is at least once; consumers deduplicate
  • Clean up sent rows

Common mistakes

  • Publishing to the broker inside the database transaction
  • Assuming exactly-once delivery

Follow-ups

  • How would you keep per-order event ordering?
  • When would logical decoding replace polling?

Tips

  • Show the rollback case
86.postgresql-0086Hardsenior

Why is a SECURITY DEFINER function dangerous without a fixed search_path, and how is it hardened?

A SECURITY DEFINER function runs with its owner's privileges. If it refers to unqualified names and does not set search_path, a caller who can create objects in a schema earlier on the path can substitute their own function or table and run code with the owner's rights. Harden it with SET search_path = pg_catalog, pg_temp (or a trusted schema) in the function definition, qualified names, and REVOKE EXECUTE FROM PUBLIC.

Full answer

Setup for the example:

sql
CREATE SCHEMA vault;
CREATE TABLE vault.secrets (id int, value text);
CREATE TABLE secrets (id int, value text);
CREATE FUNCTION count_secrets_unsafe() RETURNS bigint LANGUAGE sql SECURITY DEFINER AS $$ SELECT count(*) FROM secrets $$;
CREATE FUNCTION count_secrets_safe() RETURNS bigint LANGUAGE sql SECURITY DEFINER
  SET search_path = pg_catalog, pg_temp AS $$ SELECT count(*) FROM vault.secrets $$;
REVOKE EXECUTE ON FUNCTION count_secrets_safe() FROM PUBLIC;
sql
SELECT proname, prosecdef, coalesce(proconfig::text, 'no search_path set') AS config FROM pg_proc WHERE proname LIKE 'count_secrets%' ORDER BY proname;

PostgreSQL returns:

text
       proname        | prosecdef |                config
----------------------+-----------+-------------------------------------
 count_secrets_safe   | t         | {"search_path=pg_catalog, pg_temp"}
 count_secrets_unsafe | t         | no search_path set
(2 rows)
sql
SELECT p.proname FROM pg_proc p WHERE p.prosecdef AND p.pronamespace = current_schema()::regnamespace AND (p.proconfig IS NULL OR NOT EXISTS (SELECT 1 FROM unnest(p.proconfig) c WHERE c LIKE 'search_path=%'));

Result on PostgreSQL 17:

text
       proname
----------------------
 count_secrets_unsafe
(1 row)
sql
DROP SCHEMA vault CASCADE;

Result:

text
NOTICE:  drop cascades to table vault.secrets
DROP SCHEMA

The catalog shows that both functions are security definers, but only the safe one carries its own search_path setting, with pg_temp listed last so temporary objects cannot shadow anything. The second query is an audit that lists security-definer functions without a fixed search_path, here the unsafe one. The actual attack needs a second, less privileged role and was not run here: that role creates a table or function named like the referenced object in a schema it controls and calls the function with that schema first on its path. Besides the fixed path, schema-qualify names in the body and grant EXECUTE only to the roles that need it. The last run removes the demo's vault schema.

sql
CREATE SCHEMA vault;
CREATE TABLE vault.secrets (id int, value text);
CREATE TABLE secrets (id int, value text);
CREATE FUNCTION count_secrets_unsafe() RETURNS bigint LANGUAGE sql SECURITY DEFINER AS $$ SELECT count(*) FROM secrets $$;
CREATE FUNCTION count_secrets_safe() RETURNS bigint LANGUAGE sql SECURITY DEFINER
  SET search_path = pg_catalog, pg_temp AS $$ SELECT count(*) FROM vault.secrets $$;
REVOKE EXECUTE ON FUNCTION count_secrets_safe() FROM PUBLIC;

SELECT proname, prosecdef, coalesce(proconfig::text, 'no search_path set') AS config FROM pg_proc WHERE proname LIKE 'count_secrets%' ORDER BY proname;

SELECT p.proname FROM pg_proc p WHERE p.prosecdef AND p.pronamespace = current_schema()::regnamespace AND (p.proconfig IS NULL OR NOT EXISTS (SELECT 1 FROM unnest(p.proconfig) c WHERE c LIKE 'search_path=%'));

DROP SCHEMA vault CASCADE;

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

Key points

  • SECURITY DEFINER runs with owner rights
  • Unqualified names follow the caller's search_path
  • Set search_path on the function
  • Put pg_temp last
  • Revoke EXECUTE from PUBLIC

Common mistakes

  • Creating security definer functions without SET search_path
  • Leaving EXECUTE granted to PUBLIC

Follow-ups

  • How did PostgreSQL 15 change the public schema to reduce this risk?
  • When is SECURITY DEFINER the right tool?

Tips

  • Audit with the catalog
87.postgresql-0087Hardsenior

What is transaction ID wraparound, and how do you keep a busy PostgreSQL cluster away from it?

Transaction ids are 32-bit and compared in a circle, so rows must be frozen by VACUUM before about two billion newer transactions pass, or their visibility would flip. Autovacuum runs anti-wraparound vacuums automatically, but long-running transactions, abandoned replication slots or prepared transactions can block freezing. Monitor age(datfrozenxid) per database and age(relfrozenxid) per table, and alert well before autovacuum_freeze_max_age.

Full answer

Each row records the transaction that created it (xmin). Because ids wrap around after about 4 billion values, PostgreSQL treats the 2 billion ids before the current one as the past and the rest as the future. A row whose xmin falls too far behind would suddenly look as if it came from the future and disappear, so VACUUM marks old rows as frozen, meaning visible to everyone, regardless of xmin.

What goes wrong in practice:

  • A transaction or session left open for days holds back the oldest xmin, so VACUUM cannot freeze anything newer.
  • An unused replication slot keeps catalog_xmin old.
  • Forgotten prepared transactions (PREPARE TRANSACTION) do the same.
  • Autovacuum throttled too hard on very large tables never finishes a full pass.

If the margin gets very small, PostgreSQL warns, and at about 3 million transactions remaining it refuses new transactions that assign ids until a VACUUM completes, which is an outage.

Monitoring queries (illustrative, not run here):

sql
SELECT datname, age(datfrozenxid) FROM pg_database ORDER BY 2 DESC;
SELECT relname, age(relfrozenxid) FROM pg_class WHERE relkind = 'r' ORDER BY 2 DESC LIMIT 10;

Keep idle_in_transaction_session_timeout set, drop unused slots, and make sure autovacuum has enough workers and cost budget for the largest tables. PostgreSQL 17's improved vacuum memory handling helps large tables finish faster.

Key points

  • Transaction ids are 32-bit and circular
  • VACUUM freezes old rows
  • Long transactions and slots block freezing
  • Monitor age(datfrozenxid)
  • Running out forces a protective shutdown of writes

Common mistakes

  • Disabling autovacuum on large tables
  • Leaving replication slots unused

Follow-ups

  • What does VACUUM FREEZE do?
  • How do 64-bit transaction ids in other systems avoid this?

Tips

  • Name the blockers
88.postgresql-0088Hardsenior

Design connection management for 2,000 application instances talking to one PostgreSQL primary.

Each PostgreSQL connection is a process using memory, and performance drops well before max_connections when thousands are active. Put a pooler such as PgBouncer between the applications and the database, usually in transaction mode, so a few hundred server connections serve thousands of clients. Size the pool to the database's cores and I/O, keep transactions short, and avoid session state that transaction pooling breaks.

Full answer

Why direct connections fail at this scale: 2,000 instances with 10 connections each would need 20,000 backends. Each costs several megabytes and adds contention on shared structures such as the lock manager and snapshot building, so throughput falls as connections rise.

A typical design:

  • Application-side pools stay small (2 to 5 connections per instance).
  • PgBouncer runs in transaction pooling mode, close to the database or as a sidecar, with a server pool of roughly 2 to 4 times the database's CPU cores for an OLTP workload.
  • A separate pool or role for long-running jobs, so reports do not starve web requests.
  • Timeouts: statement_timeout per role, idle_in_transaction_session_timeout, and pooler query and client timeouts.

What transaction pooling breaks, because consecutive transactions from one client may use different server connections:

  • Session-level SET (use SET LOCAL), advisory locks held across transactions, LISTEN, temporary tables that outlive a transaction, and WITH HOLD cursors.
  • Server-side prepared statements, unless the pooler supports them (PgBouncer 1.21+ can track protocol-level prepared statements).

Operational checks: watch pooler wait times (clients waiting for a server connection) as the main saturation signal, and scale reads with replicas rather than more primary connections.

Key points

  • Connections are processes and do not scale to thousands
  • Use a pooler in transaction mode
  • Size server pools to hardware
  • Transaction pooling breaks session state
  • Watch client wait time in the pooler

Common mistakes

  • Raising max_connections to 10,000
  • Using session SET with transaction pooling

Follow-ups

  • When would session pooling be required?
  • How do serverless functions change pooling?

Tips

  • Size the pool from cores
89.postgresql-0089Hardsenior

Design a backup and recovery strategy that can restore a production database to any point in the last 14 days.

Point-in-time recovery needs periodic physical base backups plus continuous WAL archiving; restoring a base backup and replaying WAL up to a target time recovers to that moment. Tools such as pgBackRest or Barman manage retention, compression, encryption and verification. pg_dump logical backups complement this for single-table restores and migrations but cannot do PITR. Test restores regularly and measure recovery time.

Full answer

Building blocks:

  • Base backups: full physical copies (pg_basebackup, or pgBackRest full and incremental backups; PostgreSQL 17 adds native incremental backups with pg_combinebackup), taken daily or weekly.
  • WAL archiving: archive_command or archive_library ships every completed WAL segment to durable storage in another location; archive lag is monitored.
  • Retention: keep base backups and all WAL since the oldest one you may restore from, here at least 14 days plus one full backup cycle.
  • Recovery: restore the nearest base backup before the target, set recovery_target_time, and replay WAL; the server stops at the target and can be promoted.

Targets to agree on: RPO (how much data may be lost, driven by archive frequency or synchronous replicas) and RTO (how long a restore may take, driven by database size, backup format and WAL volume).

Practices that matter more than the tool: automated restore tests into a scratch environment with checks that the data is sane, encryption and access control for the backup bucket, alerts on failed archiving, and a written runbook. Replicas are not backups, because an accidental DELETE replicates immediately; delayed replicas (recovery_min_apply_delay) can help for quick recovery from such mistakes.

This item describes infrastructure and has nothing to run in a single schema.

Key points

  • PITR needs base backups plus WAL archiving
  • Restore to recovery_target_time
  • Define RPO and RTO
  • Test restores regularly
  • Replicas are not backups

Common mistakes

  • Relying only on nightly pg_dump
  • Never testing a restore

Follow-ups

  • How do you recover a single dropped table quickly?
  • What does PostgreSQL 17's incremental backup change?

Tips

  • State RPO and RTO
90.postgresql-0090Hardsenior

Users report that they sometimes do not see their own changes right after saving. The app reads from replicas. Diagnose and fix it.

Streaming replicas apply WAL asynchronously, so a read routed to a replica shortly after a write on the primary can return old data. Measure lag with pg_stat_replication on the primary or the replay timestamp on replicas. Fix it by routing a user's reads to the primary for a short time after they write, by waiting for the replica to reach the write's LSN, or by using synchronous replication with remote_apply for critical paths.

Full answer

How to confirm: on the primary, pg_stat_replication shows write_lag, flush_lag and replay_lag per replica; on a replica, now() - pg_last_xact_replay_timestamp() approximates delay (it grows when the primary is idle, so read it together with traffic). Correlate spikes with heavy writes such as batch jobs, long queries on the replica that conflict with replay, or network issues.

Fix options, from simplest:

  1. Read-your-writes routing: after a user writes, send their reads to the primary for a few seconds (track a timestamp in the session or a cookie).
  2. LSN waiting: return pg_current_wal_lsn() after the write, and before reading on a replica, check pg_last_wal_replay_lsn() >= that LSN, falling back to the primary if it is behind.
  3. Synchronous replication with synchronous_commit = remote_apply for the specific transactions that need it, accepting higher write latency.
  4. Reduce lag itself: tune replicas so long queries do not delay replay (hot_standby_feedback and max_standby_streaming_delay trade-offs), spread batch writes, and size replica hardware like the primary.

Also review which reads need freshness at all: dashboards and search can tolerate seconds of lag; a profile page right after saving cannot. Not run here, because it needs a replica.

Key points

  • Replicas lag the primary asynchronously
  • Measure with pg_stat_replication
  • Route reads after writes to the primary
  • LSN checks give precise freshness
  • remote_apply for critical paths

Common mistakes

  • Sending all reads to replicas blindly
  • Treating replication lag as constant

Follow-ups

  • What do hot_standby_feedback and max_standby_streaming_delay trade off?
  • How would a proxy handle read-your-writes?

Tips

  • Mention LSN comparison
91.postgresql-0091Hardsenior

After a deploy, database CPU doubles but no single query looks slow. How do you find the cause with pg_stat_statements?

pg_stat_statements aggregates execution counts, total and mean time, rows and buffer use per normalised query. Sort by total_exec_time, not mean time: a cheap query whose call count jumped from thousands to millions, often an N+1 loop introduced by the deploy, dominates CPU while each call stays fast. Compare snapshots before and after the deploy, then fix the code path or add caching.

Full answer

Approach:

  1. Ensure the extension is loaded (shared_preload_libraries) and take snapshots of pg_stat_statements periodically, or reset it after the deploy to see the new pattern clearly.
  2. Rank by total time and by calls (illustrative, not run here):
sql
SELECT queryid, calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS mean_ms,
       rows, shared_blks_hit + shared_blks_read AS blocks, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;
  1. Compare with the previous snapshot: look for queries whose calls per minute rose sharply, new queries, or rising blocks per call, which suggests a plan change or a missing index.
  2. Map the query back to code through application tracing, query comments added by the ORM, or the query text.

Common findings: a new loop issuing one query per item, an ORM relationship loaded lazily inside a serializer, a cache that is no longer hit because of a key change, or a query whose plan changed to a sequential scan after statistics shifted. Each needs a different fix: batching or eager loading, restoring the cache, or an index or statistics change. Track calls per request as a metric so the next regression is caught in staging.

Key points

  • Rank by total time, not mean time
  • Call counts reveal N+1 regressions
  • Compare before and after snapshots
  • Rising blocks per call hint at plan changes
  • Map queries back to code

Common mistakes

  • Looking only at the slowest single queries
  • Resetting statistics without saving a snapshot

Follow-ups

  • How do you track plan changes over time?
  • What does track_io_timing add?

Tips

  • Sort by total_exec_time
92.postgresql-0092Hardsenior

Choose between a shared table with tenant_id, a schema per tenant and a database per tenant for a B2B SaaS on PostgreSQL.

A shared schema with a tenant_id column on every table scales to many tenants with one set of migrations and pooled connections, and row-level security can enforce isolation. Schema per tenant gives stronger separation and easy per-tenant export but makes migrations and catalogs heavy beyond a few thousand tenants. Database per tenant isolates most strongly, suits a few large or regulated customers, and costs the most to operate. Many products mix them: shared by default, dedicated for large customers.

Full answer

Compare on the dimensions that decide it:

ConcernShared tables + tenant_idSchema per tenantDatabase per tenant
Tenant count it handles wellUp to millionsHundreds to low thousandsTens to hundreds
IsolationLogical (RLS, app checks)Namespace levelStrong, separate catalogs
MigrationsOne runOne run per schemaOne run per database
Connection poolingOne poolOne pool, search_path per tenantPool per database
Cross-tenant analyticsSimple queriesUNION across schemasSeparate pipeline
Per-tenant restore or deleteHarder (filtered)Drop or dump a schemaDrop or dump a database
Noisy neighboursShared resourcesShared resourcesCan be placed on separate servers

Design details for the shared model: put tenant_id first in composite primary keys and indexes, include it in every foreign key so rows cannot point across tenants, enforce it with RLS and SET LOCAL per transaction, and plan to shard by tenant_id later (for example with Citus) if one server is not enough.

Decide by tenant count, size skew, compliance needs (data residency, dedicated hardware) and team capacity for operations. This is a design item with nothing to run.

Key points

  • Shared tables scale to many tenants
  • Schemas give middle-ground isolation
  • Databases isolate strongly but cost most
  • Lead indexes and keys with tenant_id
  • Hybrid models are common

Common mistakes

  • Schema per tenant with tens of thousands of tenants
  • Shared tables without tenant_id in foreign keys

Follow-ups

  • How would you move one large tenant to its own database?
  • How does Citus distribute by tenant?

Tips

  • Compare along fixed dimensions
93.postgresql-0093Hardsenior

Should primary keys be bigint identities or UUIDs? Weigh index locality, exposure and distributed generation.

bigint identities are compact (8 bytes), sequential so inserts append to the right of the B-tree, and cheap to join, but they reveal row counts and need the database to generate them. Random UUIDv4 values (16 bytes) can be generated anywhere and leak nothing, but scatter inserts across the index, causing more page splits, cache misses and WAL. Time-ordered UUIDs (UUIDv7) keep most of the locality while staying globally unique.

Full answer

Trade-offs in detail:

  • Size: uuid is 16 bytes against 8 for bigint; every index containing the key, including foreign-key indexes in child tables, grows accordingly.
  • Locality: sequential keys keep the hot part of the index small and in memory. Random UUIDs touch random leaf pages, so on large tables inserts read pages from disk and full-page writes after checkpoints add WAL volume.
  • Generation: UUIDs can be created by clients or services before inserting, which helps offline-first apps, merging data from several databases, and idempotent APIs where the client chooses the id.
  • Exposure: sequential ids in URLs let outsiders guess other records and estimate volume; a separate public UUID or slug avoids this while keeping a bigint internal key.

PostgreSQL 17 provides gen_random_uuid() (version 4) natively; UUIDv7 needs an extension or application-side generation on 17, and PostgreSQL 18 adds uuidv7(). (Not run here, since generated values are random.)

A common compromise: bigint identity as the primary key used in joins, plus a unique UUID column exposed in APIs. When ids must be generated outside the database, prefer UUIDv7 over v4 for new tables.

Key points

  • bigint is compact and sequential
  • Random UUIDs hurt index locality
  • UUIDs can be generated anywhere
  • Sequential ids leak counts
  • UUIDv7 or bigint plus public UUID are common compromises

Common mistakes

  • Random UUIDv4 keys on very large insert-heavy tables without considering locality
  • Exposing sequential ids where enumeration matters

Follow-ups

  • How would you migrate a table from bigint to UUID keys?
  • What is the storage cost of uuid in child tables?

Tips

  • Mention UUIDv7
94.postgresql-0094Hardsenior

Explain WAL, checkpoints and full-page writes, and what tuning max_wal_size changes.

Every change is first written to the write-ahead log, which is flushed at commit for durability; data pages are written later. A checkpoint flushes all dirty pages so older WAL can be recycled, and after each checkpoint the first change to a page writes the full page image into WAL to protect against torn pages. Larger max_wal_size and checkpoint_timeout mean fewer checkpoints and fewer full-page images, at the cost of longer crash recovery and more WAL disk.

Full answer

How the pieces fit:

  • Commit: the WAL records of a transaction are flushed to disk (unless synchronous_commit is off); the changed data pages stay in shared buffers.
  • Background writer and checkpointer write dirty pages over time. A checkpoint guarantees all changes up to its start are on disk, so recovery only replays WAL from the last checkpoint.
  • Full-page writes: the first modification of each page after a checkpoint logs the whole 8 kB page. Frequent checkpoints therefore inflate WAL volume, which also burdens replication and archiving.
  • Checkpoints are triggered by checkpoint_timeout or by WAL reaching max_wal_size; checkpoint_completion_target spreads the writes out.

Symptoms of checkpoints that are too frequent: log lines saying checkpoints are occurring too frequently, high WAL volume, I/O spikes, and replication lag after bulk loads. Typical tuning on a busy server: raise max_wal_size (several GB or more), set checkpoint_timeout to 10 to 15 minutes, and keep completion target at 0.9.

Trade-off: recovery after a crash replays more WAL, so recovery time grows with the interval. Measure with pg_stat_checkpointer (PostgreSQL 17) and WAL generation rates. This item is descriptive and nothing was run here.

Key points

  • WAL is written and flushed at commit
  • Checkpoints flush dirty pages
  • Full-page writes follow each checkpoint
  • Larger max_wal_size means fewer checkpoints
  • Longer intervals lengthen crash recovery

Common mistakes

  • Turning off fsync or full_page_writes for speed
  • Leaving max_wal_size at the default on write-heavy systems

Follow-ups

  • What does synchronous_commit = off risk?
  • How does wal_compression help?

Tips

  • Mention pg_stat_checkpointer
95.postgresql-0095Hardsenior

Plan a major-version upgrade of a 2 TB PostgreSQL database with minimal downtime.

pg_upgrade with --link upgrades in place in minutes regardless of size, but needs a short full outage and careful extension compatibility checks. Logical replication to a new-version cluster allows near-zero downtime: replicate, verify, then switch traffic, at the cost of more setup and caveats such as sequences and DDL not being replicated. Either way, rehearse on a copy, run ANALYZE afterwards, and keep a rollback path.

Full answer

Option 1, pg_upgrade --link:

  • Install the new version and all extensions in compatible versions; run pg_upgrade --check.
  • Stop the old cluster, run the upgrade (hard links make it fast), start the new one, then run vacuumdb --analyze-in-stages, because planner statistics are not carried over (PostgreSQL 18 begins to preserve them).
  • Replicas are rebuilt or upgraded with rsync procedures. Rollback after starting the new cluster in link mode is not possible, so take a backup first.

Option 2, logical replication:

  • Create the schema on the new cluster, publish all tables on the old one and subscribe from the new one; wait for the initial copy and catch-up.
  • Logical replication does not copy sequence values or DDL: freeze schema changes during the window and set sequences after the switch.
  • Tables need primary keys or replica identity for updates and deletes.
  • Switch by stopping writes, waiting for zero lag, moving sequences, and repointing applications or the pooler. The old cluster stays as a fallback.

Common to both: rehearse with production-sized data, read the release notes for behaviour changes, test the application against the new version in CI, and watch query plans and pg_stat_statements closely for the first days. Nothing was run here.

Key points

  • pg_upgrade --link is fast but needs a short outage
  • Logical replication gives near-zero downtime
  • Sequences and DDL do not replicate logically
  • ANALYZE after upgrading
  • Rehearse and keep a rollback path

Common mistakes

  • Skipping ANALYZE after pg_upgrade
  • Forgetting sequences in a logical cutover

Follow-ups

  • How do extensions such as PostGIS affect upgrades?
  • What does pg_createsubscriber in PostgreSQL 17 offer?

Tips

  • Compare the two methods
96.postgresql-0096Hardsenior

A dashboard runs heavy aggregate queries every few seconds and slows the primary. Design a better approach.

Stop recomputing totals from raw rows on every refresh. Precompute: incremental summary tables updated by batch jobs or triggers, materialized views refreshed on a schedule, or a time-bucketed roll-up of recent data. Serve dashboards from a replica or an analytics store, and cache results at the application layer for the refresh interval users actually need.

Full answer

Questions to settle first: how fresh must the numbers be (seconds, minutes, hourly), how many users view them, and which filters they apply.

Options, by freshness and cost:

  • Application cache: cache each dashboard query result for 30 to 60 seconds; many viewers then cost one query per interval.
  • Roll-up tables: a job aggregates new raw rows into per-minute or per-hour buckets (insert ... on conflict do update), so dashboards scan thousands of summary rows instead of millions of events. Keep a watermark of the last processed id or time so the job is incremental and idempotent.
  • Materialized views refreshed CONCURRENTLY on a schedule, suitable when a full recompute is acceptable every few minutes.
  • Trigger-maintained summaries for exact real-time totals, accepting write overhead and contention on hot summary rows.
  • Read replicas or a column store (for example a separate analytics database or extension) for ad-hoc exploration, keeping the primary for transactions.

Also check the queries themselves: missing indexes on time columns, aggregates over all history when the screen shows the last 24 hours, and per-widget queries that could be one. Measure the dashboard's share of primary load in pg_stat_statements before and after. This is a design item with nothing to run.

Key points

  • Agree on freshness needs first
  • Cache results per refresh interval
  • Incremental roll-up tables
  • Scheduled materialized view refreshes
  • Move analytics off the primary

Common mistakes

  • Recomputing from raw events on every refresh
  • Real-time triggers where minute-level freshness suffices

Follow-ups

  • How would you make the roll-up job idempotent?
  • When would you add a dedicated analytics database?

Tips

  • Start with freshness requirements
97.postgresql-0097Hardsenior

A nightly job must load 50 million rows from CSV files as quickly as possible. What would you change?

Use COPY instead of row-by-row INSERTs, load into a staging table, and build indexes and foreign keys after the load rather than maintaining them per row. Batch commits, consider an unlogged staging table for data that can be reloaded, raise maintenance_work_mem for index builds, and run ANALYZE at the end. Validate and merge from staging into the real tables in set-based statements.

Full answer

Where the time usually goes, and the fix for each:

  • Per-row round trips: single INSERTs over the network are slow; COPY (or psycopg's copy support, or \copy from psql) streams rows in one operation and is typically an order of magnitude faster.
  • Index maintenance: each index is updated for every row. Load into a staging table without indexes, or drop and recreate secondary indexes around a full reload; building an index once is much cheaper.
  • Constraints and triggers: foreign key checks and triggers fire per row. Validate in bulk with set-based queries on the staging table, then insert into the target.
  • WAL volume: an UNLOGGED staging table skips WAL (and is emptied after a crash, which is fine if the file can be reloaded). Loading into a table created or truncated in the same transaction with wal_level = minimal also avoids WAL, but that setting is unusual on servers with replicas.
  • Memory: raise maintenance_work_mem for the session that builds indexes.
  • Statistics: run ANALYZE after loading so the first queries plan well.

Example flow (not run here): COPY into staging, delete or flag invalid rows with reports, INSERT ... SELECT or MERGE into the target in batches, ANALYZE, then swap or refresh dependent summaries. Measure each step's time so the next optimisation targets the real bottleneck.

Key points

  • COPY beats row-by-row inserts
  • Load into staging, then merge
  • Build indexes after the load
  • Unlogged staging tables cut WAL
  • ANALYZE afterwards

Common mistakes

  • Inserting rows one at a time from application code
  • Keeping every index and trigger active during a full reload

Follow-ups

  • How would you load files in parallel safely?
  • How do you handle bad rows without failing the whole load?

Tips

  • Name COPY first
98.postgresql-0098Hardsenior

What does logical replication offer compared with physical streaming replication, and when would you choose it?

Physical streaming replication copies the whole cluster byte for byte, giving an exact read-only standby for failover. Logical replication sends row changes for chosen tables through publications and subscriptions, so it works across major versions, can replicate a subset of tables or rows, and allows the subscriber to be writable and have its own indexes. It does not replicate DDL or sequences and needs replica identity on tables.

Full answer

Physical replication:

  • Replicates everything: all databases, tables, indexes and catalog changes.
  • Standbys are read-only and must run the same major version and platform.
  • Best for high availability and read scaling of the whole cluster.

Logical replication (CREATE PUBLICATION ... FOR TABLE ...; CREATE SUBSCRIPTION ... on the target; illustrative, not run here):

  • Replicates selected tables, optionally with row filters and column lists (PostgreSQL 15+).
  • Works between different major versions, which makes it a tool for low-downtime upgrades and migrations.
  • Subscribers are normal writable databases, useful for feeding reporting databases or consolidating data from several sources.
  • Limits: schema changes must be applied on both sides by hand, sequences are not synchronised, large initial copies take time, and conflicts on the subscriber stop replication until resolved. PostgreSQL 17 adds failover slots so logical subscribers can follow a promoted standby.

Choose physical for failover and identical replicas, logical for selective, cross-version or cross-system data movement, and change data capture tools built on logical decoding when events need to go to systems outside PostgreSQL.

Key points

  • Physical copies the whole cluster
  • Logical replicates chosen tables as row changes
  • Logical works across versions
  • DDL and sequences are not replicated logically
  • Choose by purpose: failover versus data movement

Common mistakes

  • Using logical replication as the only HA mechanism
  • Forgetting to apply DDL on subscribers

Follow-ups

  • What is replica identity used for?
  • How does logical decoding power change data capture?

Tips

  • Contrast purposes
99.postgresql-0099Hardsenior

Plan a zero-downtime rename of a heavily used column from user_name to username.

Use expand and contract: add the new column, write to both (trigger or application), backfill old rows in batches, switch reads to the new column, stop writing the old one, then drop it. Each step is backward compatible with the application versions running at that moment. A direct RENAME is instant in the database but breaks every running application instance that still uses the old name.

Full answer

Why not just rename: ALTER TABLE ... RENAME COLUMN takes a brief exclusive lock and is instant, but during a rolling deploy, old application instances still query user_name and fail until they are replaced.

Steps (illustrative SQL, not run here):

  1. Expand: ALTER TABLE users ADD COLUMN username text; (instant, nullable, no default).
  2. Dual write: a trigger copies user_name to username on insert and update, or the new application version writes both.
  3. Backfill in batches: UPDATE users SET username = user_name WHERE id BETWEEN ... AND username IS NULL; with pauses, watching replication lag.
  4. Constraints and indexes: CREATE UNIQUE INDEX CONCURRENTLY ... (username), and NOT NULL via a CHECK (username IS NOT NULL) NOT VALID, VALIDATE, then SET NOT NULL, which can use the validated check to avoid a full scan.
  5. Switch reads: deploy the version that reads username.
  6. Contract: stop writing user_name, drop the trigger, and finally drop the column in a later release.

Alternative for small teams: create a view or a generated column alias during the transition. Whatever the method, set lock_timeout on every DDL step, run each step as its own deploy, and keep each one reversible until the final drop.

Key points

  • Direct renames break running app versions
  • Expand, dual-write, backfill, switch, contract
  • Backfill in batches
  • Build indexes concurrently and validate constraints separately
  • Keep steps reversible

Common mistakes

  • Renaming during a rolling deploy
  • Backfilling in one huge UPDATE

Follow-ups

  • How does SET NOT NULL use a validated CHECK constraint?
  • How would you handle a column type change the same way?

Tips

  • List the phases
100.postgresql-0100Hardsenior

Design a schema to store the full history of price changes so that 'price as of any date' queries are fast and correct.

Store one row per price version with a validity period, either valid_from and valid_to columns or a daterange or tstzrange, and enforce no overlaps per product with an exclusion constraint. 'As of' queries then filter on period @> the date, served by a GiST index. Keep current prices queryable cheaply, for example with a partial index on open-ended rows or a separate current table.

Full answer

Schema sketch (illustrative, not run here):

sql
CREATE TABLE product_prices (
  product_id bigint NOT NULL,
  price      numeric(12,2) NOT NULL,
  valid      tstzrange NOT NULL,
  changed_by text,
  EXCLUDE USING gist (product_id WITH =, valid WITH &&)
);
-- price as of a moment
SELECT price FROM product_prices WHERE product_id = $1 AND valid @> $2::timestamptz;
-- current prices
CREATE INDEX ON product_prices (product_id) WHERE upper_inf(valid);

Design points:

  • Changing a price is one transaction that closes the current row (set the upper bound to now) and inserts the new row starting at the same instant; the exclusion constraint guarantees no gaps are filled twice, and a check that bounds are half-open avoids double counting at the boundary.
  • Use timestamptz ranges for prices that change within a day.
  • Joins from orders to the price in effect at order time use the same @> condition, or store the price on the order line, which is usually the right choice for invoices.
  • Corrections to the past (bitemporal needs) require a second time dimension, recorded_at, if the business must know what was believed at a given time.
  • For audits of every column of many tables, a generic audit log table or trigger-based history may be simpler than temporal modelling per table.

Key points

  • One row per version with a validity range
  • Exclusion constraint prevents overlaps
  • GiST index serves as-of queries
  • Close and open versions in one transaction
  • Bitemporal needs a second time axis

Common mistakes

  • Overwriting prices and losing history
  • Inclusive end dates causing double matches

Follow-ups

  • How would you query price changes during a month?
  • When is a bitemporal model necessary?

Tips

  • Use half-open ranges