← Interview prep

PostgreSQL interview questions

SQL depth, indexing, transactions, and Postgres internals.

100 questions · Page 2 of 5

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

Page 2 of 5

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

21.postgresql-0021Easyfresher

How do TRUNCATE and DELETE differ in effect, and what do RESTART IDENTITY and CASCADE do?

DELETE removes rows one by one, fires row triggers, and leaves sequences alone. TRUNCATE empties the whole table at once, much faster and without leaving dead rows, and RESTART IDENTITY resets the table's identity sequence. TRUNCATE refuses tables referenced by foreign keys unless CASCADE is given, which also empties the referencing tables. Both are transactional in PostgreSQL.

Full answer

Setup for the example:

sql
CREATE TABLE carts (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, owner text);
CREATE TABLE cart_items (cart_id int REFERENCES carts(id), sku text);
INSERT INTO carts (owner) VALUES ('Asha'), ('Ben');
INSERT INTO cart_items VALUES (1, 'PEN'), (2, 'INK');
sql
TRUNCATE carts;

Output:

text
ERROR:  cannot truncate a table referenced in a foreign key constraint
sql
BEGIN; TRUNCATE carts RESTART IDENTITY CASCADE; SELECT (SELECT count(*) FROM carts) AS carts, (SELECT count(*) FROM cart_items) AS items;

PostgreSQL returns:

text
NOTICE:  truncate cascades to table "cart_items"
 carts | items
-------+-------
 0     | 0
(1 row)
sql
ROLLBACK; SELECT count(*) AS carts_after_rollback FROM carts;

Result on PostgreSQL 17:

text
 carts_after_rollback
----------------------
 2
(1 row)
sql
TRUNCATE carts RESTART IDENTITY CASCADE; INSERT INTO carts (owner) VALUES ('Chen') RETURNING id;

Result:

text
NOTICE:  truncate cascades to table "cart_items"
 id
----
 1
(1 row)

A plain TRUNCATE fails because cart_items refers to carts. Inside a transaction, CASCADE empties both tables, and ROLLBACK brings every row back, showing that TRUNCATE is transactional in PostgreSQL, unlike in some other databases. After truncating for real with RESTART IDENTITY, the next cart gets id 1 again. TRUNCATE takes an ACCESS EXCLUSIVE lock, so it blocks all readers while it runs, and it does not fire ON DELETE triggers; use DELETE when per-row triggers or concurrent reads matter.

sql
CREATE TABLE carts (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, owner text);
CREATE TABLE cart_items (cart_id int REFERENCES carts(id), sku text);
INSERT INTO carts (owner) VALUES ('Asha'), ('Ben');
INSERT INTO cart_items VALUES (1, 'PEN'), (2, 'INK');

TRUNCATE carts;

BEGIN; TRUNCATE carts RESTART IDENTITY CASCADE; SELECT (SELECT count(*) FROM carts) AS carts, (SELECT count(*) FROM cart_items) AS items;

ROLLBACK; SELECT count(*) AS carts_after_rollback FROM carts;

TRUNCATE carts RESTART IDENTITY CASCADE; INSERT INTO carts (owner) VALUES ('Chen') RETURNING id;

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

Key points

  • TRUNCATE empties tables at once
  • RESTART IDENTITY resets sequences
  • CASCADE empties referencing tables
  • TRUNCATE is transactional in PostgreSQL
  • It takes an exclusive lock and skips row triggers

Common mistakes

  • Using CASCADE without checking what else empties
  • Expecting DELETE to reset ids

Follow-ups

  • Which triggers fire on TRUNCATE?
  • Why does DELETE leave dead rows behind?

Tips

  • Show the rollback
22.postgresql-0022Easyfresher

What does this print when the session time zone changes, for timestamp and timestamptz values?

timestamptz stores an absolute instant (internally UTC) and displays it in the session's TimeZone, so the same value prints differently in Kolkata and London. timestamp without time zone stores the wall-clock text as given and never shifts. AT TIME ZONE converts between the two.

Full answer

Tables and rows used here:

sql
CREATE TABLE events (label text, at_tz timestamptz, at_local timestamp);
INSERT INTO events VALUES ('launch', '2026-12-04 10:00:00+05:30', '2026-12-04 10:00:00');
sql
SET TimeZone TO 'Asia/Kolkata'; SELECT at_tz::text, at_local::text FROM events;

PostgreSQL returns:

text
           at_tz           |       at_local
---------------------------+---------------------
 2026-12-04 10:00:00+05:30 | 2026-12-04 10:00:00
(1 row)
sql
SET TimeZone TO 'Europe/London'; SELECT at_tz::text, at_local::text, (at_local AT TIME ZONE 'Asia/Kolkata')::text AS local_as_kolkata FROM events;

Result on PostgreSQL 17:

text
         at_tz          |       at_local      |    local_as_kolkata
------------------------+---------------------+------------------------
 2026-12-04 04:30:00+00 | 2026-12-04 10:00:00 | 2026-12-04 04:30:00+00
(1 row)
sql
SET TimeZone TO 'UTC'; SELECT (at_tz AT TIME ZONE 'America/New_York')::text AS new_york_wall_clock FROM events;

Result:

text
 new_york_wall_clock
---------------------
 2026-12-03 23:30:00
(1 row)

In Kolkata, the timestamptz prints as 10:00 with offset +05:30; switched to London it prints as 04:30+00, the same instant. The plain timestamp prints 10:00 in both sessions because it has no zone. at_local AT TIME ZONE 'Asia/Kolkata' interprets the wall-clock value as Kolkata time and returns a timestamptz, displayed here in London time. Applied to a timestamptz, AT TIME ZONE goes the other way and returns the wall-clock time in New York, 23:30 on the previous day. Store instants as timestamptz and keep the user's zone in a separate column when needed.

sql
CREATE TABLE events (label text, at_tz timestamptz, at_local timestamp);
INSERT INTO events VALUES ('launch', '2026-12-04 10:00:00+05:30', '2026-12-04 10:00:00');

SET TimeZone TO 'Asia/Kolkata'; SELECT at_tz::text, at_local::text FROM events;

SET TimeZone TO 'Europe/London'; SELECT at_tz::text, at_local::text, (at_local AT TIME ZONE 'Asia/Kolkata')::text AS local_as_kolkata FROM events;

SET TimeZone TO 'UTC'; SELECT (at_tz AT TIME ZONE 'America/New_York')::text AS new_york_wall_clock FROM events;

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

Key points

  • timestamptz is an instant shown in the session zone
  • timestamp is a wall-clock value
  • AT TIME ZONE converts both ways
  • Session TimeZone affects display only
  • Store the user's zone separately

Common mistakes

  • Storing instants in timestamp without time zone
  • Thinking timestamptz stores the original offset

Follow-ups

  • How do DST changes affect interval arithmetic?
  • What does now() return inside a transaction?

Tips

  • Show the same instant in two zones
23.postgresql-0023Easyfresher

How do :: casts and CAST work, and what happens when a value cannot be converted?

value::type and CAST(value AS type) convert values; :: is PostgreSQL shorthand and CAST is standard. A value that cannot be converted raises an error and stops the statement. To clean messy text, test it first with a regular expression, or on PostgreSQL 16+ use pg_input_is_valid.

Full answer

Test data:

sql
CREATE TABLE raw_orders (id int, qty_text text);
INSERT INTO raw_orders VALUES (1, '3'), (2, ' 12 '), (3, 'two'), (4, '');
sql
SELECT id, qty_text::int FROM raw_orders;

Result on PostgreSQL 17:

text
ERROR:  invalid input syntax for type integer: "two"
sql
SELECT id, CASE WHEN trim(qty_text) ~ '^[0-9]+$' THEN trim(qty_text)::int END AS qty, pg_input_is_valid(qty_text, 'integer') AS valid FROM raw_orders ORDER BY id;

Result:

text
 id | qty  | valid
----+------+-------
 1  | 3    | t
 2  | 12   | t
 3  | NULL | f
 4  | NULL | f
(4 rows)
sql
SELECT '2026-12-04'::date + 1 AS tomorrow, CAST('42.50' AS numeric) * 2 AS doubled, 3.7::int AS rounded;

Output:

text
  tomorrow  | doubled | rounded
------------+---------+---------
 2026-12-05 | 85.00   | 4
(1 row)

The plain cast fails on the first bad value with 'invalid input syntax for type integer: "two"', and the whole query returns nothing. The guarded version converts only digit strings, so 'two' and the empty string become NULL. pg_input_is_valid (PostgreSQL 16+) shows that the integer parser itself accepts surrounding spaces in ' 12 '. Casting 3.7 to integer rounds to 4 rather than truncating, a frequent surprise. In import pipelines, load text into a staging table, convert with checks, and report rejected rows.

sql
CREATE TABLE raw_orders (id int, qty_text text);
INSERT INTO raw_orders VALUES (1, '3'), (2, ' 12 '), (3, 'two'), (4, '');

SELECT id, qty_text::int FROM raw_orders;

SELECT id, CASE WHEN trim(qty_text) ~ '^[0-9]+$' THEN trim(qty_text)::int END AS qty, pg_input_is_valid(qty_text, 'integer') AS valid FROM raw_orders ORDER BY id;

SELECT '2026-12-04'::date + 1 AS tomorrow, CAST('42.50' AS numeric) * 2 AS doubled, 3.7::int AS rounded;

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

Key points

  • ::type and CAST convert values
  • Bad input raises an error
  • Guard casts with checks
  • pg_input_is_valid in PostgreSQL 16+
  • numeric to int rounds

Common mistakes

  • Casting unvalidated text in production queries
  • Expecting 3.7::int to be 3

Follow-ups

  • How would you report rejected rows during an import?
  • What does pg_input_error_info return?

Tips

  • Show the rounding surprise
24.postgresql-0024Easyfresher

How does numeric(p, s) round values on insert, and when does it raise an overflow error?

numeric(p, s) stores at most p significant digits with s of them after the decimal point. Inserting more decimal places rounds to s digits, half away from zero; a value with too many digits before the point raises 'numeric field overflow'. numeric without parameters stores any precision exactly.

Full answer

Schema and sample rows:

sql
CREATE TABLE prices (label text, amount numeric(6,2));
sql
INSERT INTO prices VALUES ('a', 12.345), ('b', 12.344), ('c', -0.005), ('d', 9999.999 - 0.009); SELECT label, amount FROM prices ORDER BY label;

Result:

text
 label |  amount
-------+---------
 a     | 12.35
 b     | 12.34
 c     | -0.01
 d     | 9999.99
(4 rows)
sql
INSERT INTO prices VALUES ('e', 10000);

Output:

text
ERROR:  numeric field overflow
sql
SELECT round(2.5) AS r1, round(3.5) AS r2, round(2.5::float8) AS float_r, round(1234.5678, -2) AS hundreds;

PostgreSQL returns:

text
 r1 | r2 | float_r | hundreds
----+----+---------+----------
 3  | 4  | 2       | 1200
(1 row)

12.345 is rounded to 12.35 and 12.344 to 12.34, and -0.005 rounds away from zero to -0.01. The value 9999.99 fits exactly into numeric(6,2), which allows four digits before the point. 10000 needs five, so it fails with a numeric field overflow error. round() on numeric rounds halves away from zero (2.5 becomes 3), while round() on double precision uses the platform's round-half-even rule, so 2.5 becomes 2. A negative scale rounds to tens or hundreds.

sql
CREATE TABLE prices (label text, amount numeric(6,2));

INSERT INTO prices VALUES ('a', 12.345), ('b', 12.344), ('c', -0.005), ('d', 9999.999 - 0.009); SELECT label, amount FROM prices ORDER BY label;

INSERT INTO prices VALUES ('e', 10000);

SELECT round(2.5) AS r1, round(3.5) AS r2, round(2.5::float8) AS float_r, round(1234.5678, -2) AS hundreds;

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

Key points

  • numeric(p, s) rounds extra decimals
  • Halves round away from zero for numeric
  • Too many integer digits overflow
  • float rounding uses half-even
  • Negative scale rounds left of the point

Common mistakes

  • Choosing a precision too small for future amounts
  • Mixing float and numeric rounding rules

Follow-ups

  • How should currency columns be sized?
  • Why is unconstrained numeric slower?

Tips

  • Contrast numeric and float rounding
25.postgresql-0025Easyfresher

Control where NULLs appear when sorting with NULLS FIRST and NULLS LAST.

PostgreSQL treats NULL as larger than any value, so NULLs come last in ascending order and first in descending order. NULLS FIRST or NULLS LAST overrides this per sort key. An index can serve such a sort only if it was created with the same NULLS ordering.

Full answer

Sample schema and data:

sql
CREATE TABLE tasks (title text, due date);
INSERT INTO tasks VALUES ('report', '2026-12-10'), ('backlog', NULL), ('invoice', '2026-12-05'), ('idea', NULL);
sql
SELECT title, due FROM tasks ORDER BY due, title;

Output:

text
  title  |    due
---------+------------
 invoice | 2026-12-05
 report  | 2026-12-10
 backlog | NULL
 idea    | NULL
(4 rows)
sql
SELECT title, due FROM tasks ORDER BY due DESC, title;

PostgreSQL returns:

text
  title  |    due
---------+------------
 backlog | NULL
 idea    | NULL
 report  | 2026-12-10
 invoice | 2026-12-05
(4 rows)
sql
SELECT title, due FROM tasks ORDER BY due DESC NULLS LAST, title;

Result on PostgreSQL 17:

text
  title  |    due
---------+------------
 report  | 2026-12-10
 invoice | 2026-12-05
 backlog | NULL
 idea    | NULL
(4 rows)

Ascending order puts the two undated tasks last, and descending order puts them first, which is often not what a 'latest first' screen wants. DESC NULLS LAST lists the dated tasks newest first and the undated ones at the end. The title is a tie-breaker so rows with equal dates come out in a stable order. MySQL and SQL Server sort NULLs first in ascending order, so explicit NULLS clauses also make queries portable in intent. For an index-backed sort, create the index as ON tasks (due DESC NULLS LAST).

sql
CREATE TABLE tasks (title text, due date);
INSERT INTO tasks VALUES ('report', '2026-12-10'), ('backlog', NULL), ('invoice', '2026-12-05'), ('idea', NULL);

SELECT title, due FROM tasks ORDER BY due, title;

SELECT title, due FROM tasks ORDER BY due DESC, title;

SELECT title, due FROM tasks ORDER BY due DESC NULLS LAST, title;

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

Key points

  • NULLs sort as largest by default
  • DESC puts NULLs first
  • NULLS FIRST/LAST overrides per key
  • Indexes must match the NULL order
  • Add tie-breakers for stable order

Common mistakes

  • Showing undated items at the top of a newest-first list
  • Assuming all databases order NULLs the same

Follow-ups

  • How would you sort NULLs last on a database without NULLS LAST?
  • Does NULLS LAST affect index usage?

Tips

  • Show the DESC surprise
26.postgresql-0026Easyfresher

Return the top three scores including ties with FETCH FIRST ... WITH TIES.

FETCH FIRST n ROWS WITH TIES (PostgreSQL 13+) returns the first n rows plus any further rows that tie with the last one on the ORDER BY keys. LIMIT n cuts off at exactly n rows, dropping tied rows arbitrarily. WITH TIES requires an ORDER BY.

Full answer

Setup for the example:

sql
CREATE TABLE results (student text, score int);
INSERT INTO results VALUES ('Asha', 95), ('Ben', 88), ('Chen', 91), ('Dev', 88), ('Esha', 70);
sql
SELECT student, score FROM results ORDER BY score DESC, student LIMIT 3;

PostgreSQL returns:

text
 student | score
---------+-------
 Asha    | 95
 Chen    | 91
 Ben     | 88
(3 rows)
sql
SELECT student, score FROM results ORDER BY score DESC FETCH FIRST 3 ROWS WITH TIES;

Result on PostgreSQL 17:

text
 student | score
---------+-------
 Asha    | 95
 Chen    | 91
 Ben     | 88
 Dev     | 88
(4 rows)
sql
SELECT student FROM results FETCH FIRST 3 ROWS WITH TIES;

Result:

text
ERROR:  WITH TIES cannot be specified without ORDER BY clause

LIMIT 3 returns Asha, Chen and Ben, leaving out Dev although he scored the same 88 as Ben; the student tie-breaker only makes the choice repeatable. WITH TIES returns four rows, because Dev ties with the third row. The order within the tied rows is not specified, since only score is in the ORDER BY. Without ORDER BY, WITH TIES is an error. A window function such as rank() <= 3 gives the same result on databases without WITH TIES.

sql
CREATE TABLE results (student text, score int);
INSERT INTO results VALUES ('Asha', 95), ('Ben', 88), ('Chen', 91), ('Dev', 88), ('Esha', 70);

SELECT student, score FROM results ORDER BY score DESC, student LIMIT 3;

SELECT student, score FROM results ORDER BY score DESC FETCH FIRST 3 ROWS WITH TIES;

SELECT student FROM results FETCH FIRST 3 ROWS WITH TIES;

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

Key points

  • WITH TIES includes tied rows
  • LIMIT cuts off at exactly n
  • Requires ORDER BY
  • PostgreSQL 13+
  • rank() is the portable alternative

Common mistakes

  • Using LIMIT for 'top 3 including ties'
  • Forgetting ties when awarding prizes

Follow-ups

  • How would you get the top 3 per class?
  • How does OFFSET interact with WITH TIES?

Tips

  • Show the dropped tie
27.postgresql-0027Easyfresher

How do E'' strings, standard strings and dollar quoting handle quotes and backslashes?

In a standard string, a single quote is written by doubling it and backslashes are literal (standard_conforming_strings is on by default). E'...' strings treat backslashes as escapes such as \n. Dollar quoting, $$...$$ or $tag$...$tag$, needs no escaping at all and is used for function bodies.

Full answer

Tables and rows used here:

sql
CREATE TABLE notes (id int, body text);
INSERT INTO notes VALUES (1, 'It''s done'), (2, E'line1\nline2'), (3, $$C:\path 'quoted'$$);
sql
SELECT id, body, length(body) AS len FROM notes ORDER BY id;

Result on PostgreSQL 17:

text
 id |       body       | len
----+------------------+-----
 1  | It's done        | 9
 2  | line1
line2      | 11
 3  | C:\path 'quoted' | 16
(3 rows)
sql
SELECT 'a\nb' AS standard, length('a\nb') AS standard_len, length(E'a\nb') AS escape_len, $tag$has $$ inside$tag$ AS tagged;

Result:

text
 standard | standard_len | escape_len |     tagged
----------+--------------+------------+---------------
 a\nb     | 4            | 3          | has $$ inside
(1 row)

The doubled quote stores "It's done". The E-string turns \n into a real newline, so its value spans two lines in the output. The dollar-quoted value keeps the backslash and the quotes exactly as written. In a standard string, 'a\nb' is four characters including a literal backslash, while E'a\nb' is three. A tag such as $tag$ allows $$ inside the text. Application code should not build SQL strings by hand at all; driver parameters handle quoting safely.

sql
CREATE TABLE notes (id int, body text);
INSERT INTO notes VALUES (1, 'It''s done'), (2, E'line1\nline2'), (3, $$C:\path 'quoted'$$);

SELECT id, body, length(body) AS len FROM notes ORDER BY id;

SELECT 'a\nb' AS standard, length('a\nb') AS standard_len, length(E'a\nb') AS escape_len, $tag$has $$ inside$tag$ AS tagged;

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

Key points

  • Double single quotes in standard strings
  • Backslashes are literal by default
  • E'' enables escapes
  • Dollar quoting needs no escaping
  • Use parameters in application code

Common mistakes

  • Escaping quotes with backslashes in standard strings
  • Building SQL with string concatenation

Follow-ups

  • What does quote_literal do?
  • Why are function bodies dollar-quoted?

Tips

  • Show the length difference
28.postgresql-0028Easyfresher

How do you document tables and columns with COMMENT ON and read the descriptions back?

COMMENT ON TABLE and COMMENT ON COLUMN store descriptions in the catalog, where psql's \d+ and most database tools show them. obj_description and col_description read them back in SQL. Keeping comments in migrations documents the schema where people look.

Full answer

Test data:

sql
CREATE TABLE subscriptions (
  id      int PRIMARY KEY,
  plan    text NOT NULL,
  mrr_inr numeric(10,2)
);
COMMENT ON TABLE subscriptions IS 'One row per active customer subscription';
COMMENT ON COLUMN subscriptions.mrr_inr IS 'Monthly recurring revenue in rupees, excluding GST';
sql
SELECT obj_description('subscriptions'::regclass, 'pg_class') AS table_comment;

Result:

text
              table_comment
------------------------------------------
 One row per active customer subscription
(1 row)
sql
SELECT column_name, data_type, is_nullable, col_description('subscriptions'::regclass, ordinal_position::int) AS description FROM information_schema.columns WHERE table_name = 'subscriptions' ORDER BY ordinal_position;

Output:

text
 column_name | data_type | is_nullable |                    description
-------------+-----------+-------------+----------------------------------------------------
 id          | integer   | NO          | NULL
 plan        | text      | NO          | NULL
 mrr_inr     | numeric   | YES         | Monthly recurring revenue in rupees, excluding GST
(3 rows)

The table comment comes back from obj_description. The second query is a portable 'describe table' built on information_schema, with col_description adding each column's comment; only mrr_inr has one, so the others show NULL. The unit and tax rule in that comment are exactly the details that otherwise live in someone's memory. In psql, \d+ subscriptions shows the same information interactively.

sql
CREATE TABLE subscriptions (
  id      int PRIMARY KEY,
  plan    text NOT NULL,
  mrr_inr numeric(10,2)
);
COMMENT ON TABLE subscriptions IS 'One row per active customer subscription';
COMMENT ON COLUMN subscriptions.mrr_inr IS 'Monthly recurring revenue in rupees, excluding GST';

SELECT obj_description('subscriptions'::regclass, 'pg_class') AS table_comment;

SELECT column_name, data_type, is_nullable, col_description('subscriptions'::regclass, ordinal_position::int) AS description FROM information_schema.columns WHERE table_name = 'subscriptions' ORDER BY ordinal_position;

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

Key points

  • COMMENT ON stores descriptions
  • obj_description and col_description read them
  • information_schema describes columns
  • Tools and psql show comments
  • Document units and rules

Common mistakes

  • Keeping column meaning only in a wiki
  • Comments that drift from reality

Follow-ups

  • How would you check that every column has a comment?
  • What does regclass do?

Tips

  • Document units
29.postgresql-0029Easyfresher

Which psql meta-commands should every PostgreSQL developer know?

psql commands start with a backslash and are handled by the client, not the server. The everyday ones are \l (databases), \c (connect), \dt and \d name (tables and their structure), \dn (schemas), \df (functions), \x (expanded output), \timing, \e (edit the last query) and \i (run a file). \? lists them all.

Full answer

psql is the standard command-line client, and its meta-commands are processed by psql itself, so they do not work from application drivers. (The commands below were not run here; this bank's examples run through a driver.)

text
\l                 list databases
\c shop            connect to database shop
\dn                list schemas
\dt sales.*        list tables in schema sales
\d+ orders         columns, indexes, constraints and comments of orders
\di                list indexes
\df *refund*       list functions matching a pattern
\x auto            switch to expanded output for wide rows
\timing on         show how long each statement takes
\e                 edit the last query in $EDITOR
\i migrate.sql     run a file
\copy t FROM 'x.csv' CSV HEADER   client-side CSV import
\set ON_ERROR_STOP on             stop scripts at the first error

Two habits help in production work: run psql -X in scripts so personal settings in .psqlrc do not change behaviour, and set ON_ERROR_STOP so a failed statement does not let the rest of a migration continue. \copy reads files on the client machine, unlike the server-side COPY command, which reads files on the database server.

Key points

  • Meta-commands are handled by psql
  • \d family describes objects
  • \x and \timing aid reading and tuning
  • \copy reads client-side files
  • ON_ERROR_STOP for scripts

Common mistakes

  • Sending meta-commands through an application driver
  • Running scripts without ON_ERROR_STOP

Follow-ups

  • How does \copy differ from COPY?
  • What is .psqlrc used for?

Tips

  • Mention ON_ERROR_STOP
30.postgresql-0030Easyfresher

Explain how a PostgreSQL server is organised: cluster, database, schema, role and tablespace.

One PostgreSQL server process manages a cluster: a data directory holding several databases. Each database contains schemas, which contain tables, views and functions; queries cannot join tables across databases directly. Roles (users and groups) are global to the cluster, and tablespaces map storage to directories.

Full answer

The hierarchy, from the outside in:

  • Cluster: one running server (one port, one data directory) with shared configuration, WAL and roles. initdb creates it.
  • Database: an isolated set of schemas. A connection is always to one database, so cross-database queries need extensions such as postgres_fdw or dblink.
  • Schema: a namespace inside a database (public by default). Schemas can be joined across freely within the same database.
  • Objects: tables, indexes, views, sequences, functions and types live in schemas.
  • Roles: global to the cluster. A role with LOGIN acts as a user; roles can be members of other roles, which is how groups are built. Privileges are granted per object, schema or database.
  • Tablespaces: optional storage locations; most deployments use only the default.

A common design question is whether tenants or modules should be separate databases or separate schemas. Schemas allow joins and share one connection pool; databases give stronger isolation and separate backups but cannot be queried together. This item is descriptive and has nothing to run.

Key points

  • A cluster is one server with many databases
  • Connections target one database
  • Schemas are namespaces within a database
  • Roles are cluster-wide
  • Choose schemas versus databases deliberately

Common mistakes

  • Expecting cross-database joins to work
  • Granting everything to one superuser role

Follow-ups

  • How do you give a role read-only access to a schema?
  • When would you use postgres_fdw?

Tips

  • Draw the hierarchy
31.postgresql-0031Easyfresher

Copy a table's structure with CREATE TABLE ... LIKE, and explain what CREATE TABLE AS leaves out.

CREATE TABLE new (LIKE old INCLUDING ALL) copies columns, defaults, constraints, indexes, identity and comments, but no rows. CREATE TABLE new AS SELECT ... copies data and column types only, without primary keys, defaults, constraints or indexes. Choose LIKE for an empty twin such as a staging table, and CREATE TABLE AS for a quick snapshot.

Full answer

Setup for the example:

sql
CREATE TABLE customers (
  id    int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email text NOT NULL UNIQUE,
  tier  text DEFAULT 'free' CHECK (tier IN ('free', 'pro'))
);
INSERT INTO customers (email) VALUES ('a@x.in'), ('b@x.in');
sql
CREATE TABLE customers_stage (LIKE customers INCLUDING ALL); CREATE TABLE customers_snap AS SELECT * FROM customers;

Result on PostgreSQL 17:

text
SELECT 2
sql
SELECT c.relname AS table_name, (SELECT count(*) FROM pg_constraint k WHERE k.conrelid = c.oid) AS constraints, (SELECT count(*) FROM pg_index i WHERE i.indrelid = c.oid) AS indexes FROM pg_class c WHERE c.relname IN ('customers', 'customers_stage', 'customers_snap') ORDER BY c.relname;

Result:

text
    table_name   | constraints | indexes
-----------------+-------------+---------
 customers       | 3           | 2
 customers_snap  | 0           | 0
 customers_stage | 3           | 2
(3 rows)
sql
INSERT INTO customers_stage (email) VALUES ('c@x.in') RETURNING id, tier;

Output:

text
 id | tier
----+------
 1  | free
(1 row)
sql
SELECT count(*) AS snap_rows FROM customers_snap;

PostgreSQL returns:

text
 snap_rows
-----------
 2
(1 row)

The LIKE copy has the same constraints and indexes as the original: the primary key, the unique email and the CHECK. NOT NULL is copied as well, although PostgreSQL 17 does not list it in pg_constraint, so it is not in the count. The snapshot has no constraints or indexes at all, though it holds both rows. Inserting into the staging table applies the default tier and generates an id from its own new identity sequence, starting at 1. A snapshot made with CREATE TABLE AS needs keys and indexes added by hand if it will be queried heavily.

sql
CREATE TABLE customers (
  id    int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email text NOT NULL UNIQUE,
  tier  text DEFAULT 'free' CHECK (tier IN ('free', 'pro'))
);
INSERT INTO customers (email) VALUES ('a@x.in'), ('b@x.in');

CREATE TABLE customers_stage (LIKE customers INCLUDING ALL); CREATE TABLE customers_snap AS SELECT * FROM customers;

SELECT c.relname AS table_name, (SELECT count(*) FROM pg_constraint k WHERE k.conrelid = c.oid) AS constraints, (SELECT count(*) FROM pg_index i WHERE i.indrelid = c.oid) AS indexes FROM pg_class c WHERE c.relname IN ('customers', 'customers_stage', 'customers_snap') ORDER BY c.relname;

INSERT INTO customers_stage (email) VALUES ('c@x.in') RETURNING id, tier;

SELECT count(*) AS snap_rows FROM customers_snap;

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

Key points

  • LIKE INCLUDING ALL copies structure
  • CREATE TABLE AS copies data and types only
  • LIKE creates its own identity sequence
  • Snapshots need indexes added
  • Pick by purpose

Common mistakes

  • Using CREATE TABLE AS and expecting constraints
  • Assuming the copy shares the original sequence

Follow-ups

  • What do INCLUDING DEFAULTS and INCLUDING INDEXES control individually?
  • How would you copy a table between databases?

Tips

  • Count constraints and indexes
32.postgresql-0032Easyfresher

Why can CREATE OR REPLACE VIEW fail when a column is removed, and how is a view changed safely?

CREATE OR REPLACE VIEW can add new columns at the end but cannot remove, rename or retype existing ones. Changing those requires DROP VIEW and CREATE VIEW, and objects that depend on the view must be dropped and recreated too. Doing it in one transaction keeps the change atomic for readers.

Full answer

Tables and rows used here:

sql
CREATE TABLE staff (id int, name text, salary int, dept text);
INSERT INTO staff VALUES (1, 'Asha', 90000, 'eng'), (2, 'Ben', 60000, 'ops');
CREATE VIEW staff_public AS SELECT id, name, salary FROM staff;
CREATE VIEW eng_staff AS SELECT id, name FROM staff_public WHERE id = 1;
sql
CREATE OR REPLACE VIEW staff_public AS SELECT id, name FROM staff;

Result:

text
ERROR:  cannot drop columns from view
sql
CREATE OR REPLACE VIEW staff_public AS SELECT id, name, salary, dept FROM staff; SELECT * FROM staff_public ORDER BY id;

Output:

text
 id | name | salary | dept
----+------+--------+------
 1  | Asha | 90000  | eng
 2  | Ben  | 60000  | ops
(2 rows)
sql
DROP VIEW staff_public;

PostgreSQL returns:

text
ERROR:  cannot drop view staff_public because other objects depend on it
sql
BEGIN; DROP VIEW eng_staff; DROP VIEW staff_public; CREATE VIEW staff_public AS SELECT id, name, dept FROM staff; CREATE VIEW eng_staff AS SELECT id, name FROM staff_public WHERE dept = 'eng'; COMMIT; SELECT * FROM eng_staff;

Result on PostgreSQL 17:

text
 id | name
----+------
 1  | Asha
(1 row)

Removing salary with CREATE OR REPLACE fails with 'cannot drop columns from view'. Appending dept at the end is allowed. A plain DROP VIEW fails because eng_staff depends on staff_public; DROP ... CASCADE would remove the dependent view silently, which is risky. The final transaction drops both views and recreates them without salary, so no reader sees a moment where either is missing. Migration tools should script dependent views explicitly for this reason.

sql
CREATE TABLE staff (id int, name text, salary int, dept text);
INSERT INTO staff VALUES (1, 'Asha', 90000, 'eng'), (2, 'Ben', 60000, 'ops');
CREATE VIEW staff_public AS SELECT id, name, salary FROM staff;
CREATE VIEW eng_staff AS SELECT id, name FROM staff_public WHERE id = 1;

CREATE OR REPLACE VIEW staff_public AS SELECT id, name FROM staff;

CREATE OR REPLACE VIEW staff_public AS SELECT id, name, salary, dept FROM staff; SELECT * FROM staff_public ORDER BY id;

DROP VIEW staff_public;

BEGIN; DROP VIEW eng_staff; DROP VIEW staff_public; CREATE VIEW staff_public AS SELECT id, name, dept FROM staff; CREATE VIEW eng_staff AS SELECT id, name FROM staff_public WHERE dept = 'eng'; COMMIT; SELECT * FROM eng_staff;

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

Key points

  • OR REPLACE can only append columns
  • Removing columns needs DROP and CREATE
  • Dependent views block DROP
  • CASCADE silently removes dependents
  • Recreate in one transaction

Common mistakes

  • Using DROP ... CASCADE without listing what it removes
  • Changing views outside a transaction

Follow-ups

  • How do you list objects that depend on a view?
  • When are views updatable?

Tips

  • Show the dependency error
33.postgresql-0033Mediummid

What does PostgreSQL print when the same document is stored as json and as jsonb?

json stores the input text exactly, keeping whitespace, key order and duplicate keys. jsonb stores a parsed binary form: whitespace is dropped, keys are sorted by length and then bytes, and only the last of duplicate keys survives. jsonb is slower to write but faster to query and can be indexed, so it is the default choice.

Full answer

Test data:

sql
CREATE TABLE docs (j json, jb jsonb);
INSERT INTO docs VALUES ('{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}', '{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}');
sql
SELECT j::text AS as_json, jb::text AS as_jsonb FROM docs;

Output:

text
                    as_json                    |               as_jsonb
-----------------------------------------------+--------------------------------------
 {"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]} | {"a": 3, "b": 1, "long_key": [1, 2]}
(1 row)
sql
SELECT j->>'a' AS json_a, jb->>'a' AS jsonb_a, jb = '{"a": 3, "b": 1, "long_key": [1, 2]}'::jsonb AS jsonb_equal FROM docs;

PostgreSQL returns:

text
 json_a | jsonb_a | jsonb_equal
--------+---------+-------------
 3      | 3       | t
(1 row)
sql
SELECT j = j FROM docs;

Result on PostgreSQL 17:

text
ERROR:  operator does not exist: json = json

The json column returns the text unchanged, double space and duplicate key included, while jsonb shows a normalised document with one "a" whose value is 3. Looking up 'a' in json returns the last duplicate as well, but the stored text still has both, which can confuse other consumers. jsonb values compare by content regardless of key order. json has no equality operator at all, so comparing json values fails with 'could not identify an equality operator for type json'; this also blocks DISTINCT and GROUP BY on json columns.

sql
CREATE TABLE docs (j json, jb jsonb);
INSERT INTO docs VALUES ('{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}', '{"b": 1,  "a": 2, "a": 3, "long_key": [1, 2]}');

SELECT j::text AS as_json, jb::text AS as_jsonb FROM docs;

SELECT j->>'a' AS json_a, jb->>'a' AS jsonb_a, jb = '{"a": 3, "b": 1, "long_key": [1, 2]}'::jsonb AS jsonb_equal FROM docs;

SELECT j = j FROM docs;

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

Key points

  • json keeps text exactly
  • jsonb normalises and deduplicates keys
  • jsonb compares by content
  • json has no equality operator
  • Prefer jsonb for querying and indexing

Common mistakes

  • Using json and then trying to GROUP BY it
  • Relying on key order in jsonb

Follow-ups

  • When is json the better choice?
  • How large can a jsonb value be?

Tips

  • Show the duplicate key
34.postgresql-0034Mediummid

Query nested JSONB with SQL/JSON path expressions: jsonb_path_query, @? and @@.

A jsonpath such as '$.items[*] ? (@.qty > 2)' navigates and filters inside a document. jsonb_path_query returns each match as a row, @? tests whether any match exists, and @@ evaluates a path predicate, with variables passed safely through the vars argument.

Full answer

Schema and sample rows:

sql
CREATE TABLE carts (id int, doc jsonb);
INSERT INTO carts VALUES
  (1, '{"user": "asha", "items": [{"sku": "PEN", "qty": 3, "price": 10}, {"sku": "INK", "qty": 1, "price": 45}]}'),
  (2, '{"user": "ben", "items": [{"sku": "PAD", "qty": 1, "price": 60}]}'),
  (3, '{"user": "chen", "items": []}');
sql
SELECT id, jsonb_path_query(doc, '$.items[*] ? (@.qty > 2).sku') AS bulk_sku FROM carts ORDER BY id;

PostgreSQL returns:

text
 id | bulk_sku
----+----------
 1  | "PEN"
(1 row)
sql
SELECT id, doc @? '$.items[*] ? (@.price >= 50)' AS has_premium, doc @@ '$.items.size() == 0' AS empty FROM carts ORDER BY id;

Result on PostgreSQL 17:

text
 id | has_premium | empty
----+-------------+-------
 1  | f           | f
 2  | t           | f
 3  | f           | t
(3 rows)
sql
SELECT id, jsonb_path_query_array(doc, '$.items[*] ? (@.price > $min).sku', '{"min": 20}') AS above_min FROM carts ORDER BY id;

Result:

text
 id | above_min
----+-----------
 1  | ["INK"]
 2  | ["PAD"]
 3  | []
(3 rows)

Only Asha's cart has an item with quantity above 2, so jsonb_path_query returns one row, the JSON string "PEN". The @? test finds Ben's 60-rupee pad, and @@ evaluates the size check, which is true only for the empty cart. The third query passes the threshold as a variable, avoiding string-built paths, and collects matches into an array per cart, giving an empty array where nothing matches. Path queries with @? and @@ can use a GIN index on the column.

sql
CREATE TABLE carts (id int, doc jsonb);
INSERT INTO carts VALUES
  (1, '{"user": "asha", "items": [{"sku": "PEN", "qty": 3, "price": 10}, {"sku": "INK", "qty": 1, "price": 45}]}'),
  (2, '{"user": "ben", "items": [{"sku": "PAD", "qty": 1, "price": 60}]}'),
  (3, '{"user": "chen", "items": []}');

SELECT id, jsonb_path_query(doc, '$.items[*] ? (@.qty > 2).sku') AS bulk_sku FROM carts ORDER BY id;

SELECT id, doc @? '$.items[*] ? (@.price >= 50)' AS has_premium, doc @@ '$.items.size() == 0' AS empty FROM carts ORDER BY id;

SELECT id, jsonb_path_query_array(doc, '$.items[*] ? (@.price > $min).sku', '{"min": 20}') AS above_min FROM carts ORDER BY id;

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

Key points

  • jsonpath navigates and filters documents
  • jsonb_path_query returns rows
  • @? tests existence, @@ evaluates predicates
  • Pass variables via the vars argument
  • GIN indexes support @? and @@

Common mistakes

  • Building path strings from user input
  • Unnesting arrays by hand for simple filters

Follow-ups

  • What do lax and strict modes change?
  • How would you index for @? queries?

Tips

  • Use vars for parameters
35.postgresql-0035Mediummid

Turn a JSON array into a relational result with JSON_TABLE in PostgreSQL 17.

JSON_TABLE (new in PostgreSQL 17) maps parts of a JSON document to columns and rows using path expressions, with typed columns, defaults and nested paths. It replaces chains of jsonb_array_elements and ->> casts with one declarative clause, and it is part of the SQL standard.

Full answer

Sample schema and data:

sql
CREATE TABLE api_responses (id int, body jsonb);
INSERT INTO api_responses VALUES (1, '{"orders": [
  {"id": 501, "total": "1250.50", "placed": "2026-11-30", "tags": ["gift"]},
  {"id": 502, "total": "80", "placed": "2026-12-01"},
  {"id": 503, "placed": "2026-12-02", "tags": ["bulk", "b2b"]}]}');
sql
SELECT jt.* FROM api_responses r, JSON_TABLE(r.body, '$.orders[*]' COLUMNS (row_no FOR ORDINALITY, order_id int PATH '$.id', total numeric(10,2) PATH '$.total' DEFAULT 0 ON EMPTY, placed date PATH '$.placed', tag_count int PATH '$.tags.size()' DEFAULT 0 ON EMPTY)) AS jt ORDER BY row_no;

Result on PostgreSQL 17:

text
 row_no | order_id |  total  |   placed   | tag_count
--------+----------+---------+------------+-----------
 1      | 501      | 1250.50 | 2026-11-30 | 1
 2      | 502      | 80.00   | 2026-12-01 | 0
 3      | 503      | 0.00    | 2026-12-02 | 2
(3 rows)
sql
SELECT jt.order_id, jt.tag FROM api_responses r, JSON_TABLE(r.body, '$.orders[*]' COLUMNS (order_id int PATH '$.id', NESTED PATH '$.tags[*]' COLUMNS (tag text PATH '$'))) AS jt ORDER BY order_id, tag NULLS FIRST;

Result:

text
 order_id | tag
----------+------
 501      | gift
 502      | NULL
 503      | b2b
 503      | bulk
(4 rows)

Each order becomes a row with typed columns: the text total '1250.50' is converted to numeric, order 503's missing total falls back to the default 0, and FOR ORDINALITY numbers the rows. The tag count uses a path method; for order 502, which has no tags, the default applies. NESTED PATH expands the tags array: orders with tags produce one row per tag, and order 502 still appears once with a NULL tag. On PostgreSQL 16 and earlier the same result needs jsonb_array_elements plus casts.

sql
CREATE TABLE api_responses (id int, body jsonb);
INSERT INTO api_responses VALUES (1, '{"orders": [
  {"id": 501, "total": "1250.50", "placed": "2026-11-30", "tags": ["gift"]},
  {"id": 502, "total": "80", "placed": "2026-12-01"},
  {"id": 503, "placed": "2026-12-02", "tags": ["bulk", "b2b"]}]}');

SELECT jt.* FROM api_responses r, JSON_TABLE(r.body, '$.orders[*]' COLUMNS (row_no FOR ORDINALITY, order_id int PATH '$.id', total numeric(10,2) PATH '$.total' DEFAULT 0 ON EMPTY, placed date PATH '$.placed', tag_count int PATH '$.tags.size()' DEFAULT 0 ON EMPTY)) AS jt ORDER BY row_no;

SELECT jt.order_id, jt.tag FROM api_responses r, JSON_TABLE(r.body, '$.orders[*]' COLUMNS (order_id int PATH '$.id', NESTED PATH '$.tags[*]' COLUMNS (tag text PATH '$'))) AS jt ORDER BY order_id, tag NULLS FIRST;

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

Key points

  • JSON_TABLE is new in PostgreSQL 17
  • Columns are typed with paths
  • DEFAULT ... ON EMPTY handles missing keys
  • NESTED PATH expands inner arrays
  • FOR ORDINALITY numbers rows

Common mistakes

  • Hand-written element loops for simple mapping
  • Ignoring conversion errors on bad values

Follow-ups

  • What do ON ERROR clauses do?
  • How would you write this on PostgreSQL 15?

Tips

  • Mention the version
36.postgresql-0036Mediummid

Which GIN operator class should index a JSONB column queried with @>, and how do you confirm the index is used?

The default jsonb_ops GIN class supports @>, ?, ?| and ?& (containment and key existence). jsonb_path_ops supports only @> and path operators but is smaller and usually faster for containment. Confirm with EXPLAIN that the plan shows a Bitmap Index Scan on the index.

Full answer

Setup for the example:

sql
CREATE TABLE events (id int, payload jsonb);
INSERT INTO events SELECT g, jsonb_build_object('type', CASE WHEN g % 10 = 0 THEN 'purchase' ELSE 'view' END, 'user', g % 100) FROM generate_series(1, 5000) g;
CREATE INDEX events_payload_path ON events USING gin (payload jsonb_path_ops);
ANALYZE events;
sql
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload @> '{"type": "purchase"}';

Result:

text
Aggregate
  ->  Bitmap Heap Scan on events
        Recheck Cond: (payload @> '{"type": "purchase"}'::jsonb)
        ->  Bitmap Index Scan on events_payload_path
              Index Cond: (payload @> '{"type": "purchase"}'::jsonb)
sql
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload ? 'user';

Output:

text
Aggregate
  ->  Seq Scan on events
        Filter: (payload ? 'user'::text)
sql
SELECT count(*) AS purchases FROM events WHERE payload @> '{"type": "purchase", "user": 50}';

PostgreSQL returns:

text
 purchases
-----------
 50
(1 row)

The containment query uses the jsonb_path_ops index through a bitmap scan. The key-existence query with ? cannot use that operator class, so it falls back to a sequential scan; it would need a default jsonb_ops index. Containment with several keys narrows the match; 50 rows here. A filter on one scalar field, such as payload->>'type' = 'purchase', is not helped by either GIN class; an expression B-tree index on (payload->>'type') serves that form.

sql
CREATE TABLE events (id int, payload jsonb);
INSERT INTO events SELECT g, jsonb_build_object('type', CASE WHEN g % 10 = 0 THEN 'purchase' ELSE 'view' END, 'user', g % 100) FROM generate_series(1, 5000) g;
CREATE INDEX events_payload_path ON events USING gin (payload jsonb_path_ops);
ANALYZE events;

EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload @> '{"type": "purchase"}';

EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE payload ? 'user';

SELECT count(*) AS purchases FROM events WHERE payload @> '{"type": "purchase", "user": 50}';

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

Key points

  • jsonb_ops supports @> and key existence
  • jsonb_path_ops supports @> and paths only
  • path_ops is smaller and faster
  • Check plans with EXPLAIN
  • Use expression B-tree indexes for ->> equality

Common mistakes

  • Indexing with path_ops and querying with ?
  • Expecting GIN to help ->> comparisons

Follow-ups

  • How big do GIN indexes get compared with the table?
  • What does fastupdate do?

Tips

  • Show the fallback plan
37.postgresql-0037Mediummid

Use a partial index for a small, frequently queried subset of rows.

A partial index (CREATE INDEX ... WHERE condition) indexes only rows matching a predicate, such as open tickets. It is smaller and cheaper to maintain than a full index, and the planner uses it when the query's WHERE clause implies the index predicate. Partial unique indexes also enforce rules such as one active row per user.

Full answer

Tables and rows used here:

sql
CREATE TABLE tickets (id int, status text, assignee text);
INSERT INTO tickets SELECT g, CASE WHEN g % 50 = 0 THEN 'open' ELSE 'closed' END, 'agent' || (g % 7) FROM generate_series(1, 20000) g;
CREATE INDEX tickets_open_assignee ON tickets (assignee) WHERE status = 'open';
CREATE INDEX tickets_all_assignee ON tickets (assignee);
ANALYZE tickets;
sql
SELECT indexrelid::regclass::text AS index_name, pg_relation_size(indexrelid) < pg_relation_size('tickets_all_assignee') AS smaller_than_full FROM pg_index WHERE indrelid = 'tickets'::regclass ORDER BY 1;

Output:

text
       index_name      | smaller_than_full
-----------------------+-------------------
 tickets_all_assignee  | f
 tickets_open_assignee | t
(2 rows)
sql
EXPLAIN (COSTS OFF) SELECT id FROM tickets WHERE status = 'open' AND assignee = 'agent3';

PostgreSQL returns:

text
Bitmap Heap Scan on tickets
  Recheck Cond: ((assignee = 'agent3'::text) AND (status = 'open'::text))
  ->  Bitmap Index Scan on tickets_open_assignee
        Index Cond: (assignee = 'agent3'::text)
sql
CREATE UNIQUE INDEX one_open_per_assignee ON tickets (assignee) WHERE status = 'open' AND id > 20000; INSERT INTO tickets VALUES (20001, 'open', 'agent1');

Result on PostgreSQL 17:

text
INSERT 0 1
sql
INSERT INTO tickets VALUES (20002, 'open', 'agent1');

Result:

text
ERROR:  duplicate key value violates unique constraint "one_open_per_assignee"

The partial index holds only the 400 open tickets, so it is a fraction of the full index's size. The query that filters on status = 'open' uses it. The planner can only choose it when the query states the same condition; a query on assignee alone could not use it. The partial unique index, here restricted to new rows so the demo data does not conflict, allows one open ticket per assignee and rejects a second with a duplicate key error.

sql
CREATE TABLE tickets (id int, status text, assignee text);
INSERT INTO tickets SELECT g, CASE WHEN g % 50 = 0 THEN 'open' ELSE 'closed' END, 'agent' || (g % 7) FROM generate_series(1, 20000) g;
CREATE INDEX tickets_open_assignee ON tickets (assignee) WHERE status = 'open';
CREATE INDEX tickets_all_assignee ON tickets (assignee);
ANALYZE tickets;

SELECT indexrelid::regclass::text AS index_name, pg_relation_size(indexrelid) < pg_relation_size('tickets_all_assignee') AS smaller_than_full FROM pg_index WHERE indrelid = 'tickets'::regclass ORDER BY 1;

EXPLAIN (COSTS OFF) SELECT id FROM tickets WHERE status = 'open' AND assignee = 'agent3';

CREATE UNIQUE INDEX one_open_per_assignee ON tickets (assignee) WHERE status = 'open' AND id > 20000; INSERT INTO tickets VALUES (20001, 'open', 'agent1');

INSERT INTO tickets VALUES (20002, 'open', 'agent1');

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

Key points

  • Partial indexes cover a subset
  • Smaller and cheaper to maintain
  • Queries must imply the predicate
  • Partial unique indexes enforce conditional rules
  • Good for hot subsets such as open items

Common mistakes

  • Writing a query condition that differs from the index predicate
  • Indexing every row when queries touch 2%

Follow-ups

  • How would you enforce one default address per user?
  • Do parameterised queries use partial indexes?

Tips

  • Match the predicate
38.postgresql-0038Mediummid

Why does WHERE lower(email) = ... ignore an index on email, and how does an expression index fix it?

An index on email stores the raw values, so a condition on lower(email) cannot use it. CREATE INDEX ON users (lower(email)) indexes the expression, and queries that use exactly the same expression can use it. A unique expression index also enforces case-insensitive uniqueness.

Full answer

Test data:

sql
CREATE TABLE users (id int, email text);
INSERT INTO users SELECT g, 'User' || g || '@Example.com' FROM generate_series(1, 20000) g;
CREATE INDEX users_email ON users (email);
ANALYZE users;
sql
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE lower(email) = 'user42@example.com';

PostgreSQL returns:

text
Seq Scan on users
  Filter: (lower(email) = 'user42@example.com'::text)
sql
CREATE UNIQUE INDEX users_email_lower ON users (lower(email)); ANALYZE users; EXPLAIN (COSTS OFF) SELECT id FROM users WHERE lower(email) = 'user42@example.com';

Result on PostgreSQL 17:

text
Index Scan using users_email_lower on users
  Index Cond: (lower(email) = 'user42@example.com'::text)
sql
INSERT INTO users VALUES (99999, 'USER42@example.COM');

Result:

text
ERROR:  duplicate key value violates unique constraint "users_email_lower"

Before the fix, the plan is a sequential scan with a filter on lower(email), checking all 20,000 rows. After creating the expression index, the same query uses an index scan on users_email_lower. Because that index is unique, inserting the same address in different case is rejected. The query must use the identical expression; lower(trim(email)) would not match. The citext extension is an alternative that makes the column itself case-insensitive.

sql
CREATE TABLE users (id int, email text);
INSERT INTO users SELECT g, 'User' || g || '@Example.com' FROM generate_series(1, 20000) g;
CREATE INDEX users_email ON users (email);
ANALYZE users;

EXPLAIN (COSTS OFF) SELECT id FROM users WHERE lower(email) = 'user42@example.com';

CREATE UNIQUE INDEX users_email_lower ON users (lower(email)); ANALYZE users; EXPLAIN (COSTS OFF) SELECT id FROM users WHERE lower(email) = 'user42@example.com';

INSERT INTO users VALUES (99999, 'USER42@example.COM');

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

Key points

  • Functions on columns bypass plain indexes
  • Expression indexes index the computed value
  • Queries must match the expression
  • Unique expression indexes enforce case-insensitive uniqueness
  • citext is an alternative

Common mistakes

  • Wrapping indexed columns in functions
  • Storing mixed-case emails without a uniqueness rule

Follow-ups

  • How would you index a date part of a timestamp?
  • What are the trade-offs of citext?

Tips

  • Show both plans
39.postgresql-0039Mediummid

Get an index-only scan with a covering index using INCLUDE.

An index-only scan answers a query from the index without visiting the table, which needs every selected column in the index and pages marked all-visible by VACUUM. INCLUDE adds extra columns to the index leaf entries without making them part of the search key. It suits queries that look up by one column and return a few others.

Full answer

Schema and sample rows:

sql
CREATE TABLE orders (id int PRIMARY KEY, customer_id int, status text, total numeric(10,2), notes text);
INSERT INTO orders SELECT g, g % 500, CASE WHEN g % 3 = 0 THEN 'paid' ELSE 'new' END, g % 1000, repeat('x', 50) FROM generate_series(1, 20000) g;
CREATE INDEX orders_customer ON orders (customer_id);
sql
VACUUM ANALYZE orders;

Result on PostgreSQL 17:

text
VACUUM
sql
EXPLAIN (COSTS OFF) SELECT customer_id, total FROM orders WHERE customer_id = 42;

Result:

text
Bitmap Heap Scan on orders
  Recheck Cond: (customer_id = 42)
  ->  Bitmap Index Scan on orders_customer
        Index Cond: (customer_id = 42)
sql
CREATE INDEX orders_customer_cov ON orders (customer_id) INCLUDE (total);

Output:

text
CREATE INDEX
sql
VACUUM ANALYZE orders;

PostgreSQL returns:

text
VACUUM
sql
EXPLAIN (COSTS OFF) SELECT customer_id, total FROM orders WHERE customer_id = 42;

Result on PostgreSQL 17:

text
Index Only Scan using orders_customer_cov on orders
  Index Cond: (customer_id = 42)
sql
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT customer_id, total FROM orders WHERE customer_id = 42;

Result:

text
Index Only Scan using orders_customer_cov on orders (actual rows=40 loops=1)
  Index Cond: (customer_id = 42)
  Heap Fetches: 0

VACUUM runs as a separate statement because it cannot run inside a transaction block, and a multi-statement script is one implicit transaction. With only customer_id indexed, the plan must fetch table rows to read total. After adding the covering index, the plan becomes an Index Only Scan. EXPLAIN ANALYZE shows 'Heap Fetches: 0' because VACUUM marked every page all-visible; on a table with many recent changes, heap fetches rise and the benefit shrinks until autovacuum catches up. INCLUDE columns cannot be used for searching or ordering, and every included column makes the index larger, so include only what hot queries need.

sql
CREATE TABLE orders (id int PRIMARY KEY, customer_id int, status text, total numeric(10,2), notes text);
INSERT INTO orders SELECT g, g % 500, CASE WHEN g % 3 = 0 THEN 'paid' ELSE 'new' END, g % 1000, repeat('x', 50) FROM generate_series(1, 20000) g;
CREATE INDEX orders_customer ON orders (customer_id);

VACUUM ANALYZE orders;

EXPLAIN (COSTS OFF) SELECT customer_id, total FROM orders WHERE customer_id = 42;

CREATE INDEX orders_customer_cov ON orders (customer_id) INCLUDE (total);

VACUUM ANALYZE orders;

EXPLAIN (COSTS OFF) SELECT customer_id, total FROM orders WHERE customer_id = 42;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF) SELECT customer_id, total FROM orders WHERE customer_id = 42;

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

Key points

  • Index-only scans skip the table
  • All selected columns must be in the index
  • INCLUDE adds non-key columns
  • The visibility map decides heap fetches
  • Keep included columns few

Common mistakes

  • Expecting index-only scans on freshly changed tables
  • Including wide columns

Follow-ups

  • How does the visibility map work?
  • When is a multicolumn key better than INCLUDE?

Tips

  • Show Heap Fetches
40.postgresql-0040Mediummid

Does an index on (customer_id, created_at) help a query that filters only on created_at?

A B-tree on (a, b) is sorted by a first, so it serves filters on a, or on a and b, and ORDER BY a, b. A filter on b alone can at best scan the whole index, so a separate index on b is much cheaper. Order columns with equality filters first and the range or sort column last.

Full answer

Sample schema and data:

sql
CREATE TABLE orders (id int, customer_id int, created_at date);
INSERT INTO orders SELECT g, g % 1000, date '2026-01-01' + (g % 300) FROM generate_series(1, 30000) g;
CREATE INDEX orders_cust_created ON orders (customer_id, created_at);
ANALYZE orders;
sql
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE customer_id = 7 AND created_at >= '2026-06-01';

Result:

text
Bitmap Heap Scan on orders
  Recheck Cond: ((customer_id = 7) AND (created_at >= '2026-06-01'::date))
  ->  Bitmap Index Scan on orders_cust_created
        Index Cond: ((customer_id = 7) AND (created_at >= '2026-06-01'::date))
sql
EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';

Output:

text
Bitmap Heap Scan on orders
  Recheck Cond: (created_at = '2026-06-01'::date)
  ->  Bitmap Index Scan on orders_cust_created
        Index Cond: (created_at = '2026-06-01'::date)
sql
CREATE INDEX orders_created ON orders (created_at); ANALYZE orders; EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';

PostgreSQL returns:

text
Bitmap Heap Scan on orders
  Recheck Cond: (created_at = '2026-06-01'::date)
  ->  Bitmap Index Scan on orders_created
        Index Cond: (created_at = '2026-06-01'::date)

With customer_id fixed, the composite index narrows to one customer and then a date range, giving an efficient index scan. Filtering on created_at alone still uses the composite index here, but the condition can only be checked by reading the index under every one of the 1,000 customers, because the dates are spread through it; it wins over a table scan only because the index is smaller than the table. A dedicated index on created_at lets the same query jump straight to the matching entries. PostgreSQL 18 adds skip scans that help some of these cases, but on version 17 column order decides usability.

sql
CREATE TABLE orders (id int, customer_id int, created_at date);
INSERT INTO orders SELECT g, g % 1000, date '2026-01-01' + (g % 300) FROM generate_series(1, 30000) g;
CREATE INDEX orders_cust_created ON orders (customer_id, created_at);
ANALYZE orders;

EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE customer_id = 7 AND created_at >= '2026-06-01';

EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';

CREATE INDEX orders_created ON orders (created_at); ANALYZE orders; EXPLAIN (COSTS OFF) SELECT id FROM orders WHERE created_at = '2026-06-01';

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

Key points

  • Composite B-trees sort by the first column first
  • Leading-column filters use the index well
  • Filters on later columns alone must read the whole index
  • Equality columns first, range columns last
  • Add a separate index for other access paths

Common mistakes

  • Adding composite indexes in arbitrary column order
  • Assuming any column of an index is usable alone

Follow-ups

  • How would you order columns for WHERE a = ? ORDER BY b?
  • When is a bitmap AND of two indexes chosen?

Tips

  • Explain the sort order