← Interview prep

PostgreSQL interview questions

SQL depth, indexing, transactions, and Postgres internals.

100 questions · Page 3 of 5

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

Page 3 of 5

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

41.postgresql-0041Mediummid

Read EXPLAIN ANALYZE output: compare estimated and actual rows to spot a bad estimate.

EXPLAIN ANALYZE runs the query and shows, for each plan node, the planner's estimated rows next to actual rows and loops. A large gap means the statistics or assumptions are wrong, often from correlated columns or stale stats, and leads to bad join choices. ANALYZE refreshes statistics, and CREATE STATISTICS captures correlations between columns.

Full answer

Setup for the example:

sql
CREATE TABLE addresses (id int, city text, pincode text);
INSERT INTO addresses SELECT g, c.city, c.pin FROM generate_series(1, 20000) g
  CROSS JOIN LATERAL (SELECT (ARRAY['Pune','Delhi','Chennai','Kolkata'])[1 + g % 4] AS city) x
  CROSS JOIN LATERAL (SELECT CASE x.city WHEN 'Pune' THEN '411001' WHEN 'Delhi' THEN '110001' WHEN 'Chennai' THEN '600001' ELSE '700001' END AS pin) p
  CROSS JOIN LATERAL (SELECT x.city, p.pin) c;
ANALYZE addresses;
sql
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, COSTS ON) SELECT id FROM addresses WHERE city = 'Pune' AND pincode = '411001';

Output:

text
Seq Scan on addresses  (cost=0.00..423.00 rows=1250 width=4) (actual rows=5000 loops=1)
  Filter: ((city = 'Pune'::text) AND (pincode = '411001'::text))
  Rows Removed by Filter: 15000
sql
CREATE STATISTICS addr_city_pin (dependencies) ON city, pincode FROM addresses; ANALYZE addresses; EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, COSTS ON) SELECT id FROM addresses WHERE city = 'Pune' AND pincode = '411001';

PostgreSQL returns:

text
Seq Scan on addresses  (cost=0.00..423.00 rows=5000 width=4) (actual rows=5000 loops=1)
  Filter: ((city = 'Pune'::text) AND (pincode = '411001'::text))
  Rows Removed by Filter: 15000

City and pincode are perfectly correlated: every Pune row has 411001. Without extended statistics, the planner multiplies the two selectivities (a quarter times a quarter) and expects about 1,250 rows, while 5,000 actually match, as the 'rows=' figures in the first plan show. After CREATE STATISTICS with dependencies and a fresh ANALYZE, the estimate moves to about 5,000. Cost figures are printed because the estimates live there; they can differ slightly between machines, but the estimated-versus-actual comparison is the point. In real plans, look for the lowest node where estimates go wrong.

sql
CREATE TABLE addresses (id int, city text, pincode text);
INSERT INTO addresses SELECT g, c.city, c.pin FROM generate_series(1, 20000) g
  CROSS JOIN LATERAL (SELECT (ARRAY['Pune','Delhi','Chennai','Kolkata'])[1 + g % 4] AS city) x
  CROSS JOIN LATERAL (SELECT CASE x.city WHEN 'Pune' THEN '411001' WHEN 'Delhi' THEN '110001' WHEN 'Chennai' THEN '600001' ELSE '700001' END AS pin) p
  CROSS JOIN LATERAL (SELECT x.city, p.pin) c;
ANALYZE addresses;

EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, COSTS ON) SELECT id FROM addresses WHERE city = 'Pune' AND pincode = '411001';

CREATE STATISTICS addr_city_pin (dependencies) ON city, pincode FROM addresses; ANALYZE addresses; EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, COSTS ON) SELECT id FROM addresses WHERE city = 'Pune' AND pincode = '411001';

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

Key points

  • Compare estimated rows with actual rows
  • Correlated columns cause underestimates
  • CREATE STATISTICS captures dependencies
  • ANALYZE refreshes statistics
  • Fix the lowest misestimated node first

Common mistakes

  • Reading only total time and ignoring row estimates
  • Running EXPLAIN ANALYZE on writes without a rollback

Follow-ups

  • What do ndistinct and mcv statistics add?
  • How does default_statistics_target matter?

Tips

  • Point at rows= values
42.postgresql-0042Mediummid

Use range types such as daterange to store periods and query overlaps and containment.

Range types (int4range, numrange, daterange, tstzrange) store a period as one value with inclusive or exclusive bounds. Operators include @> for contains, && for overlaps and * for intersection, and upper and lower extract bounds. A GiST index speeds up overlap queries, and multiranges (PostgreSQL 14+) store sets of ranges.

Full answer

Tables and rows used here:

sql
CREATE TABLE rentals (id int, item text, period daterange);
INSERT INTO rentals VALUES
  (1, 'camera', '[2026-12-01,2026-12-05)'),
  (2, 'camera', '[2026-12-05,2026-12-08)'),
  (3, 'tripod', '[2026-12-03,2026-12-10)');
CREATE INDEX rentals_period ON rentals USING gist (period);
sql
SELECT id, item, period @> date '2026-12-05' AS on_dec5, period && daterange('2026-12-04', '2026-12-06') AS overlaps_window, upper(period) - lower(period) AS days FROM rentals ORDER BY id;

PostgreSQL returns:

text
 id |  item  | on_dec5 | overlaps_window | days
----+--------+---------+-----------------+------
 1  | camera | f       | t               | 4
 2  | camera | t       | t               | 3
 3  | tripod | t       | t               | 7
(3 rows)
sql
SELECT a.id AS first, b.id AS second, a.period * b.period AS shared FROM rentals a JOIN rentals b ON a.id < b.id AND a.period && b.period ORDER BY 1, 2;

Result on PostgreSQL 17:

text
 first | second |          shared
-------+--------+-------------------------
 1     | 3      | [2026-12-03,2026-12-05)
 2     | 3      | [2026-12-05,2026-12-08)
(2 rows)
sql
SELECT range_agg(period)::text AS busy_days FROM rentals WHERE item = 'camera';

Result:

text
         busy_days
---------------------------
 {[2026-12-01,2026-12-08)}
(1 row)

The half-open bound [start, end) means rental 1 ends before 5 December, so it does not contain that day while rental 2 does; back-to-back rentals do not overlap. Rental lengths come from subtracting bounds. The self-join finds overlapping pairs and their intersections: rental 3 overlaps both camera rentals. range_agg merges the camera's two adjacent periods into one multirange, {[2026-12-01,2026-12-08)}. An exclusion constraint can forbid overlapping rentals of the same item entirely.

sql
CREATE TABLE rentals (id int, item text, period daterange);
INSERT INTO rentals VALUES
  (1, 'camera', '[2026-12-01,2026-12-05)'),
  (2, 'camera', '[2026-12-05,2026-12-08)'),
  (3, 'tripod', '[2026-12-03,2026-12-10)');
CREATE INDEX rentals_period ON rentals USING gist (period);

SELECT id, item, period @> date '2026-12-05' AS on_dec5, period && daterange('2026-12-04', '2026-12-06') AS overlaps_window, upper(period) - lower(period) AS days FROM rentals ORDER BY id;

SELECT a.id AS first, b.id AS second, a.period * b.period AS shared FROM rentals a JOIN rentals b ON a.id < b.id AND a.period && b.period ORDER BY 1, 2;

SELECT range_agg(period)::text AS busy_days FROM rentals WHERE item = 'camera';

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

Key points

  • Ranges store periods as one value
  • Half-open bounds avoid off-by-one overlaps
  • @>, && and * operators
  • GiST indexes speed up overlap tests
  • range_agg builds multiranges

Common mistakes

  • Using inclusive end dates and double-booking boundaries
  • Two separate columns with hand-written overlap logic

Follow-ups

  • How do exclusion constraints prevent overlaps?
  • How are empty ranges handled?

Tips

  • Explain half-open bounds
43.postgresql-0043Mediummid

Walk a hierarchy with a recursive CTE and use the SEARCH and CYCLE clauses from PostgreSQL 14.

WITH RECURSIVE combines an anchor query with a recursive step. The SEARCH DEPTH FIRST BY clause adds an ordering column for tree-shaped output, and CYCLE ... SET is_cycle USING path detects and stops loops in graph data. Both clauses replace hand-built path arrays used in earlier versions.

Full answer

Test data:

sql
CREATE TABLE categories (id int, parent_id int, name text);
INSERT INTO categories VALUES
  (1, NULL, 'All'), (2, 1, 'Stationery'), (3, 2, 'Pens'), (4, 2, 'Paper'), (5, 1, 'Electronics'), (6, 5, 'Cables');
CREATE TABLE links (src text, dst text);
INSERT INTO links VALUES ('a', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'd');
sql
WITH RECURSIVE tree AS (SELECT id, name, 0 AS depth FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.id, c.name, t.depth + 1 FROM categories c JOIN tree t ON c.parent_id = t.id) SEARCH DEPTH FIRST BY name SET ord SELECT repeat('  ', depth) || name AS outline FROM tree ORDER BY ord;

Result on PostgreSQL 17:

text
    outline
---------------
 All
   Electronics
     Cables
   Stationery
     Paper
     Pens
(6 rows)
sql
WITH RECURSIVE walk AS (SELECT src, dst FROM links WHERE src = 'a' UNION ALL SELECT l.src, l.dst FROM links l JOIN walk w ON l.src = w.dst) CYCLE dst SET is_cycle USING path SELECT src, dst, is_cycle FROM walk ORDER BY path;

Result:

text
 src | dst | is_cycle
-----+-----+----------
 a   | b   | f
 b   | c   | f
 c   | a   | f
 a   | b   | t
 c   | d   | f
(5 rows)

SEARCH DEPTH FIRST orders the output as an indented outline, with children directly under their parent and siblings by name. In the link graph, a to b to c to a is a loop; the walk returns to a, and the CYCLE clause marks the next step, a to b, with is_cycle = true because b is already on the path, and stops following it, so the query ends instead of running forever. Without the clause, UNION ALL recursion on cyclic data runs until it exhausts resources, and UNION only helps when whole rows repeat.

sql
CREATE TABLE categories (id int, parent_id int, name text);
INSERT INTO categories VALUES
  (1, NULL, 'All'), (2, 1, 'Stationery'), (3, 2, 'Pens'), (4, 2, 'Paper'), (5, 1, 'Electronics'), (6, 5, 'Cables');
CREATE TABLE links (src text, dst text);
INSERT INTO links VALUES ('a', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'd');

WITH RECURSIVE tree AS (SELECT id, name, 0 AS depth FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.id, c.name, t.depth + 1 FROM categories c JOIN tree t ON c.parent_id = t.id) SEARCH DEPTH FIRST BY name SET ord SELECT repeat('  ', depth) || name AS outline FROM tree ORDER BY ord;

WITH RECURSIVE walk AS (SELECT src, dst FROM links WHERE src = 'a' UNION ALL SELECT l.src, l.dst FROM links l JOIN walk w ON l.src = w.dst) CYCLE dst SET is_cycle USING path SELECT src, dst, is_cycle FROM walk ORDER BY path;

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

Key points

  • WITH RECURSIVE has an anchor and a step
  • SEARCH DEPTH FIRST orders trees
  • CYCLE detects loops
  • Available from PostgreSQL 14
  • Unchecked recursion on cycles never ends

Common mistakes

  • Recursing over graph data without cycle protection
  • Sorting tree output by id

Follow-ups

  • How would you compute the full path string?
  • When would ltree be a better fit?

Tips

  • Show the cycle row
44.postgresql-0044Mediummid

Write a PL/pgSQL function that returns a table, and choose between IMMUTABLE, STABLE and VOLATILE.

A function with RETURNS TABLE(...) and RETURN QUERY returns rows usable in FROM. Volatility tells the planner what it may assume: IMMUTABLE for pure computations (allowed in indexes), STABLE for functions that read the database but do not change it within a statement, and VOLATILE (the default) for anything else. Mislabelling a function can return wrong results.

Full answer

Schema and sample rows:

sql
CREATE TABLE sales (region text, amount numeric(10,2), sold_on date);
INSERT INTO sales VALUES ('north', 100, '2026-11-01'), ('north', 250, '2026-11-15'), ('south', 75, '2026-11-20'), ('south', 300, '2026-12-01');

CREATE FUNCTION gst(amount numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$ SELECT round(amount * 0.18, 2) $$;

CREATE FUNCTION region_summary(since date)
RETURNS TABLE (region text, orders bigint, revenue numeric, tax numeric)
LANGUAGE plpgsql STABLE AS $$
BEGIN
  RETURN QUERY
    SELECT s.region, count(*), sum(s.amount), sum(gst(s.amount))
    FROM sales s
    WHERE s.sold_on >= since
    GROUP BY s.region
    ORDER BY s.region;
END;
$$;
sql
SELECT * FROM region_summary('2026-11-10');

Result:

text
 region | orders | revenue |  tax
--------+--------+---------+-------
 north  | 1      | 250.00  | 45.00
 south  | 2      | 375.00  | 67.50
(2 rows)
sql
SELECT proname, provolatile FROM pg_proc WHERE proname IN ('gst', 'region_summary') ORDER BY proname;

Output:

text
    proname     | provolatile
----------------+-------------
 gst            | i
 region_summary | s
(2 rows)
sql
CREATE FUNCTION bad_now_label() RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT now()::text $$; CREATE TABLE t (x text); CREATE INDEX ON t ((x || bad_now_label())); CREATE INDEX ON t ((x || now()::text));

PostgreSQL returns:

text
ERROR:  functions in index expression must be marked IMMUTABLE

region_summary returns rows filtered by date, with tax computed by the IMMUTABLE gst helper. Columns in the function body are qualified with s. because RETURNS TABLE column names become variables inside PL/pgSQL, and an unqualified region would be ambiguous. pg_proc records volatility as i, s or v. The last run shows the danger of lying: PostgreSQL trusts the IMMUTABLE label and accepts an index using bad_now_label(), whose value actually changes, while using now() directly in an index fails with 'functions in index expression must be marked IMMUTABLE'.

sql
CREATE TABLE sales (region text, amount numeric(10,2), sold_on date);
INSERT INTO sales VALUES ('north', 100, '2026-11-01'), ('north', 250, '2026-11-15'), ('south', 75, '2026-11-20'), ('south', 300, '2026-12-01');

CREATE FUNCTION gst(amount numeric) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$ SELECT round(amount * 0.18, 2) $$;

CREATE FUNCTION region_summary(since date)
RETURNS TABLE (region text, orders bigint, revenue numeric, tax numeric)
LANGUAGE plpgsql STABLE AS $$
BEGIN
  RETURN QUERY
    SELECT s.region, count(*), sum(s.amount), sum(gst(s.amount))
    FROM sales s
    WHERE s.sold_on >= since
    GROUP BY s.region
    ORDER BY s.region;
END;
$$;

SELECT * FROM region_summary('2026-11-10');

SELECT proname, provolatile FROM pg_proc WHERE proname IN ('gst', 'region_summary') ORDER BY proname;

CREATE FUNCTION bad_now_label() RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT now()::text $$; CREATE TABLE t (x text); CREATE INDEX ON t ((x || bad_now_label())); CREATE INDEX ON t ((x || now()::text));

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

Key points

  • RETURNS TABLE with RETURN QUERY returns rows
  • Volatility guides the planner
  • IMMUTABLE is required in indexes
  • Qualify columns to avoid name clashes
  • Mislabelled volatility gives wrong results

Common mistakes

  • Marking functions IMMUTABLE that read tables or time
  • Unqualified column names clashing with OUT parameters

Follow-ups

  • When would you use LANGUAGE sql instead of plpgsql?
  • What does PARALLEL SAFE mean?

Tips

  • Explain the name clash
45.postgresql-0045Mediummid

Create a DOMAIN to reuse a validated type such as an Indian PIN code or a positive amount.

CREATE DOMAIN name AS base_type CHECK (...) defines a reusable type with constraints, so every column of that type gets the same validation. Changing the rule in one place applies everywhere, and errors name the domain. Domains suit formats used across many tables, such as PIN codes, email addresses or non-negative money.

Full answer

Sample schema and data:

sql
CREATE DOMAIN pincode AS text CHECK (VALUE ~ '^[1-9][0-9]{5}$');
CREATE DOMAIN money_inr AS numeric(12,2) CHECK (VALUE >= 0);
CREATE TABLE shops (name text, pin pincode NOT NULL, deposit money_inr DEFAULT 0);
CREATE TABLE warehouses (code text, pin pincode);
INSERT INTO shops (name, pin) VALUES ('Koramangala', '560034');
sql
INSERT INTO warehouses VALUES ('W1', '056003');

Output:

text
ERROR:  value for domain pincode violates check constraint "pincode_check"
sql
INSERT INTO shops VALUES ('Indiranagar', '560038', -100);

PostgreSQL returns:

text
ERROR:  value for domain money_inr violates check constraint "money_inr_check"
sql
SELECT name, pin, deposit, pg_typeof(pin)::text AS pin_type FROM shops;

Result on PostgreSQL 17:

text
     name    |  pin   | deposit | pin_type
-------------+--------+---------+----------
 Koramangala | 560034 | 0.00    | pincode
(1 row)

A PIN cannot start with 0, so the warehouse insert fails with an error naming the pincode domain, and the same rule applies in both tables without repeating it. A negative deposit violates the money_inr domain. Columns keep their domain type, as pg_typeof shows. Changing a domain's check later uses ALTER DOMAIN ... ADD CONSTRAINT, optionally NOT VALID to skip checking existing data. Domains over arrays or composite types are possible but less common.

sql
CREATE DOMAIN pincode AS text CHECK (VALUE ~ '^[1-9][0-9]{5}$');
CREATE DOMAIN money_inr AS numeric(12,2) CHECK (VALUE >= 0);
CREATE TABLE shops (name text, pin pincode NOT NULL, deposit money_inr DEFAULT 0);
CREATE TABLE warehouses (code text, pin pincode);
INSERT INTO shops (name, pin) VALUES ('Koramangala', '560034');

INSERT INTO warehouses VALUES ('W1', '056003');

INSERT INTO shops VALUES ('Indiranagar', '560038', -100);

SELECT name, pin, deposit, pg_typeof(pin)::text AS pin_type FROM shops;

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

Key points

  • Domains are reusable constrained types
  • One rule applies to every column
  • Errors name the domain
  • ALTER DOMAIN changes rules centrally
  • Good for formats used across tables

Common mistakes

  • Copying the same CHECK into many tables
  • Validating formats only in application code

Follow-ups

  • How do domains interact with ORMs?
  • Can a domain constraint reference other tables?

Tips

  • Name the domain in the error
46.postgresql-0046Mediummid

Why does REFRESH MATERIALIZED VIEW CONCURRENTLY fail on a new view, and what does it need?

A plain REFRESH rebuilds the view under an exclusive lock that blocks readers. CONCURRENTLY lets reads continue by computing the new result and applying differences, which requires a unique index on the materialized view covering all rows. It is slower than a plain refresh and cannot be used on a view that has never been populated.

Full answer

Setup for the example:

sql
CREATE TABLE sales (region text, amount int);
INSERT INTO sales VALUES ('north', 100), ('south', 50), ('north', 70);
CREATE MATERIALIZED VIEW region_totals AS SELECT region, sum(amount) AS total FROM sales GROUP BY region;
sql
REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals;

PostgreSQL returns:

text
ERROR:  cannot refresh materialized view "ib_0046.region_totals" concurrently
sql
CREATE UNIQUE INDEX region_totals_region ON region_totals (region); INSERT INTO sales VALUES ('east', 30), ('south', 25); REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals; SELECT region, total FROM region_totals ORDER BY region;

Result on PostgreSQL 17:

text
 region | total
--------+-------
 east   | 30
 north  | 170
 south  | 75
(3 rows)
sql
CREATE MATERIALIZED VIEW empty_mv AS SELECT * FROM sales WITH NO DATA; SELECT ispopulated FROM pg_matviews WHERE matviewname = 'empty_mv';

Result:

text
 ispopulated
-------------
 f
(1 row)

Without a unique index, the concurrent refresh fails with 'cannot refresh materialized view ... concurrently', and the error's hint asks for a unique index. After adding a unique index on region, new sales are merged in while readers could keep querying: east appears and south rises to 75. A view created WITH NO DATA is not populated, cannot be queried until refreshed, and its first refresh must be a plain one. Schedule refreshes with cron or pg_cron, and monitor their duration, because a concurrent refresh scans the full query each time.

sql
CREATE TABLE sales (region text, amount int);
INSERT INTO sales VALUES ('north', 100), ('south', 50), ('north', 70);
CREATE MATERIALIZED VIEW region_totals AS SELECT region, sum(amount) AS total FROM sales GROUP BY region;

REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals;

CREATE UNIQUE INDEX region_totals_region ON region_totals (region); INSERT INTO sales VALUES ('east', 30), ('south', 25); REFRESH MATERIALIZED VIEW CONCURRENTLY region_totals; SELECT region, total FROM region_totals ORDER BY region;

CREATE MATERIALIZED VIEW empty_mv AS SELECT * FROM sales WITH NO DATA; SELECT ispopulated FROM pg_matviews WHERE matviewname = 'empty_mv';

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

Key points

  • Plain REFRESH blocks readers
  • CONCURRENTLY needs a unique index
  • Concurrent refresh is slower
  • WITH NO DATA views need a first plain refresh
  • Schedule and monitor refreshes

Common mistakes

  • Refreshing large views at peak without CONCURRENTLY
  • Unique indexes that do not cover all rows

Follow-ups

  • How would you refresh incrementally instead?
  • When should a summary table replace a materialized view?

Tips

  • Name the unique index requirement
47.postgresql-0047Mediummid

Pivot rows into columns with crosstab from the tablefunc extension, and compare it with FILTER.

crosstab(source_sql, category_sql) turns rows of (row key, category, value) into one row per key with a column per category; the output columns must be declared in the query. The two-argument form places values correctly even when some categories are missing. For a few fixed categories, aggregates with FILTER are simpler and need no extension.

Full answer

Tables and rows used here:

sql
CREATE EXTENSION IF NOT EXISTS tablefunc;
CREATE TABLE monthly (store text, month text, revenue int);
INSERT INTO monthly VALUES ('A', 'Oct', 100), ('A', 'Nov', 120), ('A', 'Dec', 90), ('B', 'Oct', 80), ('B', 'Dec', 110);
sql
SELECT * FROM crosstab($$SELECT store, month, revenue FROM monthly ORDER BY 1$$, $$VALUES ('Oct'), ('Nov'), ('Dec')$$) AS ct(store text, oct int, nov int, dec int);

Result on PostgreSQL 17:

text
 store | oct | nov  | dec
-------+-----+------+-----
 A     | 100 | 120  | 90
 B     | 80  | NULL | 110
(2 rows)
sql
SELECT store, sum(revenue) FILTER (WHERE month = 'Oct') AS oct, sum(revenue) FILTER (WHERE month = 'Nov') AS nov, sum(revenue) FILTER (WHERE month = 'Dec') AS dec FROM monthly GROUP BY store ORDER BY store;

Result:

text
 store | oct | nov  | dec
-------+-----+------+-----
 A     | 100 | 120  | 90
 B     | 80  | NULL | 110
(2 rows)

Store B has no November row, and the two-argument crosstab still puts its December value in the dec column, leaving nov NULL; the one-argument form would shift values left into the wrong columns. The FILTER version gives the same table with plain SQL and is easier to maintain when the categories are fixed. Neither approach creates columns dynamically: a truly dynamic pivot needs generated SQL or should be done in the reporting layer. The extension is created inside this item's schema and removed with it.

sql
CREATE EXTENSION IF NOT EXISTS tablefunc;
CREATE TABLE monthly (store text, month text, revenue int);
INSERT INTO monthly VALUES ('A', 'Oct', 100), ('A', 'Nov', 120), ('A', 'Dec', 90), ('B', 'Oct', 80), ('B', 'Dec', 110);

SELECT * FROM crosstab($$SELECT store, month, revenue FROM monthly ORDER BY 1$$, $$VALUES ('Oct'), ('Nov'), ('Dec')$$) AS ct(store text, oct int, nov int, dec int);

SELECT store, sum(revenue) FILTER (WHERE month = 'Oct') AS oct, sum(revenue) FILTER (WHERE month = 'Nov') AS nov, sum(revenue) FILTER (WHERE month = 'Dec') AS dec FROM monthly GROUP BY store ORDER BY store;

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

Key points

  • crosstab pivots rows into columns
  • Use the two-argument form for missing categories
  • Output columns must be declared
  • FILTER aggregates pivot fixed categories simply
  • Dynamic pivots need generated SQL

Common mistakes

  • Using one-argument crosstab with gaps
  • Expecting SQL to create columns dynamically

Follow-ups

  • How would you pivot by week for a year?
  • Where should pivoting happen in a BI stack?

Tips

  • Explain the column shift
48.postgresql-0048Mediummid

Find similar names despite typos with pg_trgm similarity and a trigram index.

pg_trgm splits text into three-character trigrams and scores similarity between 0 and 1. The % operator matches strings above pg_trgm.similarity_threshold (0.3 by default), similarity() returns the score, and <-> orders by distance. A GIN or GiST index with gin_trgm_ops speeds up %, LIKE '%x%' and ILIKE.

Full answer

Test data:

sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE cities (name text);
INSERT INTO cities VALUES ('Bengaluru'), ('Bangalore'), ('Belgaum'), ('Mangaluru'), ('Chennai'), ('Bhubaneswar');
CREATE INDEX cities_name_trgm ON cities USING gin (name gin_trgm_ops);
sql
SELECT name, round(similarity(name, 'Bengalru')::numeric, 2) AS score FROM cities WHERE name % 'Bengalru' ORDER BY score DESC, name;

Result:

text
    name   | score
-----------+-------
 Bengaluru | 0.58
(1 row)
sql
SELECT name FROM cities ORDER BY name <-> 'Mangalore' LIMIT 2;

Output:

text
    name
-----------
 Bangalore
 Mangaluru
(2 rows)
sql
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM cities WHERE name ILIKE '%galu%';

PostgreSQL returns:

text
Bitmap Heap Scan on cities
  Recheck Cond: (name ~~* '%galu%'::text)
  ->  Bitmap Index Scan on cities_name_trgm
        Index Cond: (name ~~* '%galu%'::text)

The misspelling 'Bengalru' still finds Bengaluru with a score of 0.58; Mangaluru and Bangalore share fewer trigrams and fall below the default 0.3 threshold. Ordering by the <-> distance operator ranks names by closeness to 'Mangalore', and Bangalore comes before Mangaluru because its spelling differs in fewer trigrams. The trigram index also serves the infix ILIKE search, as the bitmap index scan shows. Sequential scans were disabled only because the demo table is tiny. Trigram matching is spelling-based, so it does not know that Bangalore and Bengaluru are the same city; aliases need a lookup table.

sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE cities (name text);
INSERT INTO cities VALUES ('Bengaluru'), ('Bangalore'), ('Belgaum'), ('Mangaluru'), ('Chennai'), ('Bhubaneswar');
CREATE INDEX cities_name_trgm ON cities USING gin (name gin_trgm_ops);

SELECT name, round(similarity(name, 'Bengalru')::numeric, 2) AS score FROM cities WHERE name % 'Bengalru' ORDER BY score DESC, name;

SELECT name FROM cities ORDER BY name <-> 'Mangalore' LIMIT 2;

SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT name FROM cities WHERE name ILIKE '%galu%';

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

Key points

  • Trigrams measure spelling similarity
  • % uses a threshold, similarity() returns a score
  • <-> orders by distance
  • gin_trgm_ops serves %, LIKE and ILIKE
  • Spelling similarity is not meaning

Common mistakes

  • Using LIKE '%x%' on large tables without a trigram index
  • Expecting fuzzy search to know aliases

Follow-ups

  • How would you tune the similarity threshold?
  • When is GiST better than GIN for trigrams?

Tips

  • Mention the threshold
49.postgresql-0049Mediummid

Expand parallel arrays into rows with unnest, keeping element positions with WITH ORDINALITY.

unnest(a, b) in FROM expands several arrays side by side, padding shorter ones with NULL. WITH ORDINALITY adds a column with each element's 1-based position, which preserves order for later sorting or for pairing values with their index. It works with any set-returning function, including jsonb_array_elements and regexp_split_to_table.

Full answer

Schema and sample rows:

sql
CREATE TABLE quizzes (student text, answers text[], marks int[]);
INSERT INTO quizzes VALUES ('Asha', ARRAY['b','c','a'], ARRAY[1,1,0]), ('Ben', ARRAY['a','c'], ARRAY[0,1,1]);
sql
SELECT q.student, u.pos, u.answer, u.mark FROM quizzes q CROSS JOIN LATERAL unnest(q.answers, q.marks) WITH ORDINALITY AS u(answer, mark, pos) ORDER BY q.student, u.pos;

Output:

text
 student | pos | answer | mark
---------+-----+--------+------
 Asha    | 1   | b      | 1
 Asha    | 2   | c      | 1
 Asha    | 3   | a      | 0
 Ben     | 1   | a      | 0
 Ben     | 2   | c      | 1
 Ben     | 3   | NULL   | 1
(6 rows)
sql
SELECT word, n FROM regexp_split_to_table('to be or not to be', ' ') WITH ORDINALITY AS t(word, n) WHERE word = 'be';

PostgreSQL returns:

text
 word | n
------+---
 be   | 2
 be   | 6
(2 rows)

Asha's arrays have equal lengths, so each position pairs an answer with its mark. Ben has two answers but three marks, so position 3 has a NULL answer, which shows a data problem worth checking. The ordinality column is listed last in the alias because it is appended after the function's own columns. The second query uses the same idea on a string split, reporting that 'be' is the second and sixth word. Relying on the output order of unnest without ORDINALITY works in practice but is not guaranteed after joins or sorting.

sql
CREATE TABLE quizzes (student text, answers text[], marks int[]);
INSERT INTO quizzes VALUES ('Asha', ARRAY['b','c','a'], ARRAY[1,1,0]), ('Ben', ARRAY['a','c'], ARRAY[0,1,1]);

SELECT q.student, u.pos, u.answer, u.mark FROM quizzes q CROSS JOIN LATERAL unnest(q.answers, q.marks) WITH ORDINALITY AS u(answer, mark, pos) ORDER BY q.student, u.pos;

SELECT word, n FROM regexp_split_to_table('to be or not to be', ' ') WITH ORDINALITY AS t(word, n) WHERE word = 'be';

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

Key points

  • Multi-argument unnest zips arrays
  • Shorter arrays are padded with NULL
  • WITH ORDINALITY adds positions
  • The ordinality column comes last in the alias
  • Works with any set-returning function

Common mistakes

  • Relying on implicit element order
  • Unnesting arrays separately and getting a cross product

Follow-ups

  • How would you rebuild the arrays after editing elements?
  • What happens with unnest in the SELECT list?

Tips

  • Show the NULL padding
50.postgresql-0050Mediummid

Under READ COMMITTED, what does session A see when session B commits a change in the middle of A's transaction?

READ COMMITTED, PostgreSQL's default, takes a new snapshot for every statement. So within one transaction, a second SELECT sees rows committed by other sessions after the first SELECT ran, a non-repeatable read. Use REPEATABLE READ when a transaction needs one consistent view across several statements.

Full answer

Sample schema and data:

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);
sql
BEGIN; SELECT balance FROM accounts WHERE id = 1;

PostgreSQL returns:

text
 balance
---------
 500
(1 row)

In a second session:

sql
UPDATE accounts SET balance = 450 WHERE id = 1;

Result on PostgreSQL 17:

text
UPDATE 1
sql
SELECT balance FROM accounts WHERE id = 1;

Result:

text
 balance
---------
 450
(1 row)
sql
COMMIT; BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 1;

Output:

text
 balance
---------
 450
(1 row)

In a second session:

sql
UPDATE accounts SET balance = 400 WHERE id = 1;

PostgreSQL returns:

text
UPDATE 1
sql
SELECT balance FROM accounts WHERE id = 1;

Result on PostgreSQL 17:

text
 balance
---------
 450
(1 row)
sql
COMMIT; SELECT balance FROM accounts WHERE id = 1;

Result:

text
 balance
---------
 400
(1 row)

In the first transaction, A reads 500, B commits 450 in autocommit mode, and A's next statement reads 450 although A never ended its transaction. Under REPEATABLE READ, A's snapshot is fixed at its first query: after B commits 400, A still reads 450 until it commits, and only a new statement after COMMIT sees 400. Reports that compute several totals in one transaction should use REPEATABLE READ so the numbers agree with each other.

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);

BEGIN; SELECT balance FROM accounts WHERE id = 1;

-- session B
UPDATE accounts SET balance = 450 WHERE id = 1;

SELECT balance FROM accounts WHERE id = 1;

COMMIT; BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 1;

-- session B
UPDATE accounts SET balance = 400 WHERE id = 1;

SELECT balance FROM accounts WHERE id = 1;

COMMIT; SELECT balance FROM accounts WHERE id = 1;

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

Key points

  • READ COMMITTED snapshots per statement
  • Committed changes appear mid-transaction
  • REPEATABLE READ fixes the snapshot
  • The snapshot starts at the first query
  • Use REPEATABLE READ for consistent multi-query reports

Common mistakes

  • Assuming BEGIN alone gives a consistent view
  • Running multi-query reports in READ COMMITTED

Follow-ups

  • What happens if A tries to update the row under REPEATABLE READ?
  • Does PostgreSQL implement READ UNCOMMITTED?

Tips

  • Narrate the timeline
51.postgresql-0051Mediummid

Why does an UPDATE under REPEATABLE READ fail with 'could not serialize access due to concurrent update', and how should the application respond?

Under REPEATABLE READ, a transaction cannot update a row that another transaction changed and committed after its snapshot was taken, so PostgreSQL raises a serialization failure (SQLSTATE 40001) instead of overwriting the newer value. The application must roll back and retry the whole transaction, which then sees the new data.

Full answer

Setup for the example:

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);
sql
BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 2;

Result on PostgreSQL 17:

text
 balance
---------
 300
(1 row)

In a second session:

sql
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

Result:

text
UPDATE 1
sql
UPDATE accounts SET balance = balance - 50 WHERE id = 2;

Output:

text
ERROR:  could not serialize access due to concurrent update
sql
ROLLBACK; BEGIN ISOLATION LEVEL REPEATABLE READ; UPDATE accounts SET balance = balance - 50 WHERE id = 2; COMMIT; SELECT balance FROM accounts WHERE id = 2;

PostgreSQL returns:

text
 balance
---------
 350
(1 row)

A's snapshot shows 300. B adds 100 and commits. A's update would be based on a stale view, so it fails with the serialization error rather than silently losing B's deposit. After rolling back, the retried transaction sees 400 and ends at 350, the correct result. Retry loops should cover the whole transaction, including its reads, and cap the number of attempts. Under READ COMMITTED the same update would instead wait for B and then apply to the new row version, which is fine for simple increments but not for decisions based on earlier reads.

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);

BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 2;

-- session B
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

UPDATE accounts SET balance = balance - 50 WHERE id = 2;

ROLLBACK; BEGIN ISOLATION LEVEL REPEATABLE READ; UPDATE accounts SET balance = balance - 50 WHERE id = 2; COMMIT; SELECT balance FROM accounts WHERE id = 2;

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

Key points

  • Concurrent updates fail under REPEATABLE READ
  • SQLSTATE 40001 means retry
  • Retry the whole transaction
  • Prevents lost updates
  • READ COMMITTED re-applies to the new row instead

Common mistakes

  • Retrying only the failing statement
  • Treating 40001 as a fatal error

Follow-ups

  • How does SERIALIZABLE differ?
  • How would you write a retry decorator for 40001?

Tips

  • Name the SQLSTATE
52.postgresql-0052Mediummid

Lock a row with SELECT ... FOR UPDATE, and fail fast with NOWAIT instead of waiting.

SELECT ... FOR UPDATE locks the selected rows until the transaction ends, so other transactions wanting to update or lock them wait. NOWAIT makes the second request fail immediately with an error instead of waiting, and lock_timeout sets a maximum wait. FOR NO KEY UPDATE and FOR SHARE are weaker lock modes for less conflicting cases.

Full answer

Tables and rows used here:

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);
sql
BEGIN; SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE;

Result:

text
 id | balance
----+---------
 1  | 500
(1 row)

In a second session:

sql
SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

Output:

text
ERROR:  could not obtain lock on row in relation "accounts"

In a second session:

sql
SELECT id, balance FROM accounts WHERE id = 1;

PostgreSQL returns:

text
 id | balance
----+---------
 1  | 500
(1 row)

In a second session:

sql
SELECT id FROM accounts WHERE id = 2 FOR UPDATE NOWAIT;

Result on PostgreSQL 17:

text
 id
----
 2
(1 row)
sql
UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT;

Result:

text
COMMIT

In a second session:

sql
SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

Output:

text
 id | balance
----+---------
 1  | 400
(1 row)

While A holds the lock, B's FOR UPDATE NOWAIT fails with 'could not obtain lock on row in relation "accounts"'. A plain SELECT is not blocked and still reads the committed value 500, because readers never wait for row locks in PostgreSQL. Locking a different row succeeds. After A commits, B can lock the row and sees 400. NOWAIT suits user-facing actions such as 'someone else is editing this order', where waiting is worse than a clear message.

sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);

BEGIN; SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE;

-- session B
SELECT id FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

-- session B
SELECT id, balance FROM accounts WHERE id = 1;

-- session B
SELECT id FROM accounts WHERE id = 2 FOR UPDATE NOWAIT;

UPDATE accounts SET balance = balance - 100 WHERE id = 1; COMMIT;

-- session B
SELECT id, balance FROM accounts WHERE id = 1 FOR UPDATE NOWAIT;

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

Key points

  • FOR UPDATE locks rows until commit
  • NOWAIT errors instead of waiting
  • Plain reads are never blocked
  • Locks are per row
  • lock_timeout bounds waiting

Common mistakes

  • Holding row locks across user think time
  • Expecting plain SELECTs to block

Follow-ups

  • When is FOR NO KEY UPDATE enough?
  • How do row locks interact with foreign keys?

Tips

  • Show that readers are not blocked
53.postgresql-0053Mediummid

Build a job queue where several workers take different jobs using FOR UPDATE SKIP LOCKED.

Each worker runs SELECT ... FOR UPDATE SKIP LOCKED LIMIT n inside a transaction: rows locked by other workers are skipped, so workers never wait for or double-process the same job. The worker processes the job and marks it done in the same transaction; if it crashes, the lock is released and the job becomes available again.

Full answer

Test data:

sql
CREATE TABLE jobs (id int PRIMARY KEY, kind text, status text DEFAULT 'queued');
INSERT INTO jobs (id, kind) VALUES (1, 'email'), (2, 'email'), (3, 'report'), (4, 'email');
sql
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

Output:

text
 id
----
 1
(1 row)

In a second session:

sql
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

PostgreSQL returns:

text
 id
----
 2
(1 row)
sql
UPDATE jobs SET status = 'done' WHERE id = 1; COMMIT;

Result on PostgreSQL 17:

text
COMMIT

In a second session:

sql
ROLLBACK;

Result:

text
ROLLBACK
sql
SELECT id, status FROM jobs ORDER BY id;

Output:

text
 id | status
----+--------
 1  | done
 2  | queued
 3  | queued
 4  | queued
(4 rows)

Worker A takes job 1 and worker B, running the same query at the same time, skips the locked row and gets job 2. A finishes and commits. B's transaction rolls back, as a crash would, so job 2 is still queued and the next worker will take it. A partial index on (id) WHERE status = 'queued' keeps the query fast as done jobs accumulate. SKIP LOCKED gives an inconsistent view on purpose, so it is right for queues and wrong for reports.

sql
CREATE TABLE jobs (id int PRIMARY KEY, kind text, status text DEFAULT 'queued');
INSERT INTO jobs (id, kind) VALUES (1, 'email'), (2, 'email'), (3, 'report'), (4, 'email');

BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

-- session B
BEGIN; SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;

UPDATE jobs SET status = 'done' WHERE id = 1; COMMIT;

-- session B
ROLLBACK;

SELECT id, status FROM jobs ORDER BY id;

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

Key points

  • SKIP LOCKED skips rows other workers hold
  • Workers never wait or duplicate work
  • Process and mark done in one transaction
  • Crashes release jobs automatically
  • Index the queued subset

Common mistakes

  • Selecting then updating without locks, causing double processing
  • Long transactions holding jobs while calling slow APIs

Follow-ups

  • How would you add retries and a dead-letter state?
  • When would a dedicated broker be better?

Tips

  • Show the second worker's choice
54.postgresql-0054Mediummid

A migration's ALTER TABLE hangs and blocks all queries. Explain why and protect it with lock_timeout.

ALTER TABLE usually needs an ACCESS EXCLUSIVE lock, so it waits behind any open transaction that has touched the table, even an idle one. While it waits in the lock queue, every new query on that table queues behind it, which looks like an outage. Set lock_timeout for migrations so the ALTER gives up quickly and can be retried.

Full answer

Schema and sample rows:

sql
CREATE TABLE products (id int PRIMARY KEY, name text);
INSERT INTO products VALUES (1, 'pen');
sql
BEGIN; SELECT name FROM products WHERE id = 1;

PostgreSQL returns:

text
 name
------
 pen
(1 row)

In a second session:

sql
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int;

Result on PostgreSQL 17:

text
ERROR:  canceling statement due to lock timeout
sql
COMMIT;

Result:

text
COMMIT

In a second session:

sql
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int; SELECT column_name FROM information_schema.columns WHERE table_name = 'products' ORDER BY ordinal_position;

Output:

text
 column_name
-------------
 id
 name
 price
(3 rows)

Session A's open transaction holds an ACCESS SHARE lock from its SELECT. The ALTER in session B waits for it, and after 200 ms fails with 'canceling statement due to lock timeout' instead of hanging; without the timeout, every later query on products would have queued behind the ALTER. Once A commits, the same ALTER succeeds instantly, because adding a nullable column only updates the catalog. Migration tooling should set lock_timeout and retry with backoff, and idle_in_transaction_session_timeout helps end forgotten transactions.

sql
CREATE TABLE products (id int PRIMARY KEY, name text);
INSERT INTO products VALUES (1, 'pen');

BEGIN; SELECT name FROM products WHERE id = 1;

-- session B
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int;

COMMIT;

-- session B
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int; SELECT column_name FROM information_schema.columns WHERE table_name = 'products' ORDER BY ordinal_position;

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

Key points

  • ALTER TABLE takes an exclusive lock
  • It waits behind open transactions
  • Queued DDL blocks later queries
  • lock_timeout makes migrations fail fast
  • Retry with backoff

Common mistakes

  • Running migrations without lock_timeout
  • Leaving transactions idle in application code

Follow-ups

  • Which ALTER TABLE forms take weaker locks?
  • How would you find the blocking session?

Tips

  • Explain the lock queue
55.postgresql-0055Mediummid

Stop runaway queries with statement_timeout, and set it per role or per transaction.

statement_timeout cancels any statement that runs longer than the limit with an error. Set it per session, per transaction with SET LOCAL, or as a default for an application role with ALTER ROLE ... SET, so one bad query cannot hold connections indefinitely. Reporting roles can be given longer limits than web-request roles.

Full answer

Sample schema and data:

sql
CREATE TABLE numbers (n int);
INSERT INTO numbers SELECT generate_series(1, 10);
sql
SET statement_timeout = '100ms'; SELECT pg_sleep(1);

Result on PostgreSQL 17:

text
ERROR:  canceling statement due to statement timeout
sql
BEGIN; SET LOCAL statement_timeout = '5s'; SELECT count(*) AS rows_counted FROM numbers; SHOW statement_timeout;

Result:

text
 statement_timeout
-------------------
 5s
(1 row)
sql
COMMIT; SHOW statement_timeout;

Output:

text
 statement_timeout
-------------------
 0
(1 row)

The one-second sleep is cancelled after 100 ms with 'canceling statement due to statement timeout'. SET LOCAL changes the value for the current transaction only: inside it the limit shows 5s, and after COMMIT the setting is back to 0, meaning no limit. It is 0 rather than 100ms because the first script ran as one implicit transaction that failed, and a SET inside a failed transaction is rolled back along with everything else. In production, a typical pattern is ALTER ROLE web_app SET statement_timeout = '5s' and a longer limit for a reporting role, with exceptions raised by SET LOCAL in the few transactions that need more time.

sql
CREATE TABLE numbers (n int);
INSERT INTO numbers SELECT generate_series(1, 10);

SET statement_timeout = '100ms'; SELECT pg_sleep(1);

BEGIN; SET LOCAL statement_timeout = '5s'; SELECT count(*) AS rows_counted FROM numbers; SHOW statement_timeout;

COMMIT; SHOW statement_timeout;

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

Key points

  • statement_timeout cancels long statements
  • SET LOCAL scopes to a transaction
  • ALTER ROLE sets defaults per role
  • Different roles need different limits
  • Pair with lock_timeout and idle timeouts

Common mistakes

  • No timeout on web-facing roles
  • Setting a global timeout that breaks maintenance jobs

Follow-ups

  • What is idle_in_transaction_session_timeout for?
  • How does a timeout interact with connection poolers?

Tips

  • Show SET LOCAL scope
56.postgresql-0056Mediummid

Show how an UPDATE creates a new row version, using ctid and xmin.

PostgreSQL never updates a row in place: an UPDATE writes a new row version with a new physical location (ctid) and creating transaction (xmin), and marks the old version as deleted by setting its xmax. Old versions become dead rows that VACUUM later reclaims. This is why heavy updates cause bloat.

Full answer

Setup for the example:

sql
CREATE TABLE items (id int, qty int);
INSERT INTO items VALUES (1, 10), (2, 20);
sql
CREATE TEMP TABLE before AS SELECT id, ctid::text AS old_ctid, xmin::text::bigint AS old_xmin FROM items; SELECT id, ctid FROM items ORDER BY id;

Result:

text
 id |  ctid
----+-------
 1  | (0,1)
 2  | (0,2)
(2 rows)
sql
UPDATE items SET qty = qty + 1 WHERE id = 1; SELECT i.id, i.ctid AS new_ctid, b.old_ctid, i.xmin::text::bigint > b.old_xmin AS newer_xmin FROM items i JOIN before b USING (id) ORDER BY i.id;

Output:

text
 id | new_ctid | old_ctid | newer_xmin
----+----------+----------+------------
 1  | (0,3)    | (0,1)    | t
 2  | (0,2)    | (0,2)    | f
(2 rows)
sql
UPDATE items SET qty = qty WHERE id = 2; SELECT id, ctid FROM items ORDER BY id;

PostgreSQL returns:

text
 id |  ctid
----+-------
 1  | (0,3)
 2  | (0,4)
(2 rows)

The two rows start at positions (0,1) and (0,2), page 0 slots 1 and 2. After the update, row 1 lives at (0,3) with a newer xmin, while row 2 is untouched. Even an update that changes nothing, such as setting qty to itself, writes a new version, moving row 2 to (0,4). The old versions at (0,1) and (0,2) remain on the page as dead rows until VACUUM. Raw xmin values are shown only as comparisons because transaction ids differ between runs. ctid changes, so it must never be used as a permanent row identifier.

sql
CREATE TABLE items (id int, qty int);
INSERT INTO items VALUES (1, 10), (2, 20);

CREATE TEMP TABLE before AS SELECT id, ctid::text AS old_ctid, xmin::text::bigint AS old_xmin FROM items; SELECT id, ctid FROM items ORDER BY id;

UPDATE items SET qty = qty + 1 WHERE id = 1; SELECT i.id, i.ctid AS new_ctid, b.old_ctid, i.xmin::text::bigint > b.old_xmin AS newer_xmin FROM items i JOIN before b USING (id) ORDER BY i.id;

UPDATE items SET qty = qty WHERE id = 2; SELECT id, ctid FROM items ORDER BY id;

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

Key points

  • UPDATE writes a new row version
  • ctid is the physical location
  • xmin records the creating transaction
  • No-op updates still create versions
  • VACUUM reclaims dead versions

Common mistakes

  • Using ctid as a stable key
  • Running no-op updates in loops

Follow-ups

  • What are HOT updates?
  • How does VACUUM decide a row is dead?

Tips

  • Show the no-op update
57.postgresql-0057Mediummid

Why does ON CONFLICT fail with 'no unique or exclusion constraint matching' when the unique index is partial?

ON CONFLICT (cols) must name columns that match a unique index or constraint the planner can infer. For a partial unique index, the conflict target must repeat the index predicate: ON CONFLICT (email) WHERE deleted_at IS NULL. Without the WHERE, no arbiter index matches and PostgreSQL raises an error.

Full answer

Tables and rows used here:

sql
CREATE TABLE members (id int GENERATED ALWAYS AS IDENTITY, email text, name text, deleted_at date);
CREATE UNIQUE INDEX members_active_email ON members (email) WHERE deleted_at IS NULL;
INSERT INTO members (email, name, deleted_at) VALUES ('a@x.in', 'Old Asha', '2026-01-01'), ('a@x.in', 'Asha', NULL);
sql
INSERT INTO members (email, name) VALUES ('a@x.in', 'Asha R') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;

Output:

text
ERROR:  there is no unique or exclusion constraint matching the ON CONFLICT specification
sql
INSERT INTO members (email, name) VALUES ('a@x.in', 'Asha R') ON CONFLICT (email) WHERE deleted_at IS NULL DO UPDATE SET name = EXCLUDED.name; SELECT email, name, deleted_at FROM members ORDER BY id;

PostgreSQL returns:

text
 email  |   name   | deleted_at
--------+----------+------------
 a@x.in | Old Asha | 2026-01-01
 a@x.in | Asha R   | NULL
(2 rows)

The partial index allows one active row per email plus any number of deleted ones, which is why the setup holds two rows for a@x.in. The first upsert fails with 'there is no unique or exclusion constraint matching the ON CONFLICT specification'. Repeating the predicate lets PostgreSQL use the partial index as the arbiter, so the active row is renamed while the deleted row is untouched. ON CONFLICT ON CONSTRAINT cannot name a partial index, because it is an index and not a constraint.

sql
CREATE TABLE members (id int GENERATED ALWAYS AS IDENTITY, email text, name text, deleted_at date);
CREATE UNIQUE INDEX members_active_email ON members (email) WHERE deleted_at IS NULL;
INSERT INTO members (email, name, deleted_at) VALUES ('a@x.in', 'Old Asha', '2026-01-01'), ('a@x.in', 'Asha', NULL);

INSERT INTO members (email, name) VALUES ('a@x.in', 'Asha R') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;

INSERT INTO members (email, name) VALUES ('a@x.in', 'Asha R') ON CONFLICT (email) WHERE deleted_at IS NULL DO UPDATE SET name = EXCLUDED.name; SELECT email, name, deleted_at FROM members ORDER BY id;

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

Key points

  • Conflict targets must match a unique index
  • Partial indexes need the predicate repeated
  • EXCLUDED holds the proposed row
  • ON CONSTRAINT works only for constraints
  • Soft-delete designs need partial uniqueness

Common mistakes

  • Omitting the WHERE for partial unique indexes
  • Trying ON CONSTRAINT with an index name

Follow-ups

  • How would you resurrect a soft-deleted member instead?
  • What happens with ON CONFLICT DO NOTHING without a target?

Tips

  • Repeat the predicate
58.postgresql-0058Mediummid

Paginate a large table with keyset pagination using a row-value comparison.

Keyset pagination remembers the last row's sort key and asks for rows after it: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT n. The row-value comparison handles ties on created_at correctly, and a matching composite index lets each page start directly at the right place, unlike OFFSET, which reads and discards earlier rows.

Full answer

Test data:

sql
CREATE TABLE posts (id int PRIMARY KEY, created_at date, title text);
INSERT INTO posts SELECT g, date '2026-12-01' - (g / 3), 'post ' || g FROM generate_series(1, 30000) g;
CREATE INDEX posts_created_id ON posts (created_at DESC, id DESC);
ANALYZE posts;
sql
SELECT id, created_at FROM posts ORDER BY created_at DESC, id DESC LIMIT 3;

PostgreSQL returns:

text
 id | created_at
----+------------
 2  | 2026-12-01
 1  | 2026-12-01
 5  | 2026-11-30
(3 rows)
sql
SELECT id, created_at FROM posts WHERE (created_at, id) < ('2026-11-30', 5) ORDER BY created_at DESC, id DESC LIMIT 3;

Result on PostgreSQL 17:

text
 id | created_at
----+------------
 4  | 2026-11-30
 3  | 2026-11-30
 8  | 2026-11-29
(3 rows)
sql
EXPLAIN (COSTS OFF) SELECT id FROM posts WHERE (created_at, id) < ('2026-11-01', 90) ORDER BY created_at DESC, id DESC LIMIT 20;

Result:

text
Limit
  ->  Index Only Scan using posts_created_id on posts
        Index Cond: (ROW(created_at, id) < ROW('2026-11-01'::date, 90))

The first page returns posts 2, 1 and 5, ending at (2026-11-30, 5). The next page asks for rows that sort after that pair and continues with posts 4 and 3, which share 30 November, then post 8 from 29 November; comparing created_at alone would have skipped or repeated the tied rows. The plan is an index-only scan with the row comparison as its index condition, so page 1,000 costs about the same as page 1. Keyset pages cannot jump to an arbitrary page number, which suits infinite scroll and APIs with next-page cursors.

sql
CREATE TABLE posts (id int PRIMARY KEY, created_at date, title text);
INSERT INTO posts SELECT g, date '2026-12-01' - (g / 3), 'post ' || g FROM generate_series(1, 30000) g;
CREATE INDEX posts_created_id ON posts (created_at DESC, id DESC);
ANALYZE posts;

SELECT id, created_at FROM posts ORDER BY created_at DESC, id DESC LIMIT 3;

SELECT id, created_at FROM posts WHERE (created_at, id) < ('2026-11-30', 5) ORDER BY created_at DESC, id DESC LIMIT 3;

EXPLAIN (COSTS OFF) SELECT id FROM posts WHERE (created_at, id) < ('2026-11-01', 90) ORDER BY created_at DESC, id DESC LIMIT 20;

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

Key points

  • Remember the last row's key
  • Row-value comparisons handle ties
  • Composite index in the same order
  • Constant cost per page
  • No random page jumps

Common mistakes

  • Using OFFSET for deep pages
  • Comparing only a non-unique column

Follow-ups

  • How would you paginate backwards?
  • How do you encode the cursor for an API?

Tips

  • Show the tie handling
59.postgresql-0059Mediummid

Make an updatable view that cannot be used to insert rows outside its filter, with WITH CHECK OPTION.

A simple view over one table is automatically updatable: INSERT, UPDATE and DELETE pass through to the table. Without WITH CHECK OPTION, a write through the view can create rows the view itself cannot see. WITH CHECK OPTION rejects such writes, which matters when views restrict what a user may touch.

Full answer

Schema and sample rows:

sql
CREATE TABLE tickets (id int PRIMARY KEY, team text, title text);
INSERT INTO tickets VALUES (1, 'billing', 'refund'), (2, 'support', 'login');
CREATE VIEW billing_open AS SELECT id, team, title FROM tickets WHERE team = 'billing';
CREATE VIEW billing_checked AS SELECT id, team, title FROM tickets WHERE team = 'billing' WITH CHECK OPTION;
sql
INSERT INTO billing_open VALUES (3, 'support', 'sneaked in'); SELECT id, team FROM tickets ORDER BY id;

Result on PostgreSQL 17:

text
 id |   team
----+---------
 1  | billing
 2  | support
 3  | support
(3 rows)
sql
INSERT INTO billing_checked VALUES (4, 'support', 'blocked');

Result:

text
ERROR:  new row violates check option for view "billing_checked"
sql
UPDATE billing_checked SET team = 'support' WHERE id = 1;

Output:

text
ERROR:  new row violates check option for view "billing_checked"
sql
UPDATE billing_checked SET title = 'refund request' WHERE id = 1 RETURNING id, title;

PostgreSQL returns:

text
 id |     title
----+----------------
 1  | refund request
(1 row)

Through the unchecked view, a support ticket was inserted even though the view shows only billing tickets. The checked view rejects both the insert and an update that would move a ticket out of billing, with 'new row violates check option for view'. Updates that keep the row inside the filter work normally. For real access control, combine views with GRANTs on the view and no direct table access, or use row-level security on the table.

sql
CREATE TABLE tickets (id int PRIMARY KEY, team text, title text);
INSERT INTO tickets VALUES (1, 'billing', 'refund'), (2, 'support', 'login');
CREATE VIEW billing_open AS SELECT id, team, title FROM tickets WHERE team = 'billing';
CREATE VIEW billing_checked AS SELECT id, team, title FROM tickets WHERE team = 'billing' WITH CHECK OPTION;

INSERT INTO billing_open VALUES (3, 'support', 'sneaked in'); SELECT id, team FROM tickets ORDER BY id;

INSERT INTO billing_checked VALUES (4, 'support', 'blocked');

UPDATE billing_checked SET team = 'support' WHERE id = 1;

UPDATE billing_checked SET title = 'refund request' WHERE id = 1 RETURNING id, title;

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

Key points

  • Simple views are updatable
  • Writes can escape an unchecked view
  • WITH CHECK OPTION blocks escaping rows
  • Applies to inserts and updates
  • Combine with grants or row-level security

Common mistakes

  • Relying on a view's WHERE as a security boundary
  • Forgetting updates can move rows out of the view

Follow-ups

  • How do LOCAL and CASCADED check options behave?
  • When would you use security_barrier?

Tips

  • Show the escape
60.postgresql-0060Mediummid

Partition a large table by month with declarative range partitioning and confirm partition pruning.

PARTITION BY RANGE (column) splits a table into child tables by key range; each partition is created with FOR VALUES FROM ... TO .... Queries filtering on the key skip irrelevant partitions (pruning), and old data is removed by dropping or detaching a partition instead of a slow DELETE. A DEFAULT partition catches rows outside every range.

Full answer

Sample schema and data:

sql
CREATE TABLE events (id bigint, happened date, kind text) PARTITION BY RANGE (happened);
CREATE TABLE events_2026_10 PARTITION OF events FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_2026_12 PARTITION OF events FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
INSERT INTO events SELECT g, date '2026-10-01' + (g % 92), 'view' FROM generate_series(1, 9200) g;
ANALYZE events;
sql
SELECT tableoid::regclass::text AS partition, count(*) FROM events GROUP BY 1 ORDER BY 1;

Result:

text
   partition    | count
----------------+-------
 events_2026_10 | 3100
 events_2026_11 | 3000
 events_2026_12 | 3100
(3 rows)
sql
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE happened >= '2026-11-10' AND happened < '2026-11-20';

Output:

text
Aggregate
  ->  Seq Scan on events_2026_11 events
        Filter: ((happened >= '2026-11-10'::date) AND (happened < '2026-11-20'::date))
sql
INSERT INTO events VALUES (99999, '2027-02-01', 'view');

PostgreSQL returns:

text
ERROR:  no partition of relation "events" found for row
sql
CREATE TABLE events_default PARTITION OF events DEFAULT; INSERT INTO events VALUES (99999, '2027-02-01', 'view'); ALTER TABLE events DETACH PARTITION events_2026_10; SELECT count(*) AS remaining FROM events;

Result on PostgreSQL 17:

text
 remaining
-----------
 6101
(1 row)

Rows are routed to partitions automatically, about 3,000 per month. The plan for a mid-November filter scans only events_2026_11. A row dated February 2027 fails with 'no partition of relation "events" found for row' until a DEFAULT partition exists. Detaching the October partition removes its 3,100 rows from the parent instantly, and the detached table can be archived or dropped. Partitioning helps with very large tables and retention, but adds planning overhead and rules: unique constraints must include the partition key.

sql
CREATE TABLE events (id bigint, happened date, kind text) PARTITION BY RANGE (happened);
CREATE TABLE events_2026_10 PARTITION OF events FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_2026_12 PARTITION OF events FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
INSERT INTO events SELECT g, date '2026-10-01' + (g % 92), 'view' FROM generate_series(1, 9200) g;
ANALYZE events;

SELECT tableoid::regclass::text AS partition, count(*) FROM events GROUP BY 1 ORDER BY 1;

EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE happened >= '2026-11-10' AND happened < '2026-11-20';

INSERT INTO events VALUES (99999, '2027-02-01', 'view');

CREATE TABLE events_default PARTITION OF events DEFAULT; INSERT INTO events VALUES (99999, '2027-02-01', 'view'); ALTER TABLE events DETACH PARTITION events_2026_10; SELECT count(*) AS remaining FROM events;

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

Key points

  • PARTITION BY RANGE splits by key ranges
  • Pruning skips irrelevant partitions
  • DEFAULT partitions catch other rows
  • Detach or drop for fast retention
  • Unique keys must include the partition key

Common mistakes

  • Partitioning small tables
  • Queries that do not filter on the partition key

Follow-ups

  • How would you automate creating next month's partition?
  • What does DETACH ... CONCURRENTLY change?

Tips

  • Show the pruned plan