PostgreSQL interview questions and answers, from MVCC to replication
PostgreSQL interview questions focus on how the engine behaves under load: MVCC and why VACUUM exists, which index type fits which query, reading EXPLAIN ANALYZE, JSONB, partitioning, replication, locks and connection pooling. Fundamentals rounds check that you know these words; senior rounds hand you a bloated table, a lagging replica or a migration that froze production and ask what you would do. Answer with the mechanism first, then the command you would run.
By Evin JohnPublished 12 min read
How PostgreSQL comes up in interviews
Three kinds of loops ask about Postgres by name. Backend developer interviews mix it into API and design questions: how you would model an entity, which index a slow endpoint needs, what isolation level a payment flow wants. Database administrator and SRE interviews go into internals and operations: autovacuum tuning, replication, backups, failover. Data engineering loops ask about bulk loading, partitioning and JSONB as a landing zone. In all three, the interviewer is listening for whether you know what the server actually does with your statement, not only the syntax.
- Screening questionsShort definitions: MVCC, VACUUM, WAL, index types, isolation default. Two sentences each, with one detail that shows hands-on use.
- Hands-on or whiteboard roundWrite a schema and a few queries, add the right indexes, then read an EXPLAIN plan the interviewer pastes in.
- Operations scenarioDisk is filling, a replica lags, connections are exhausted, or a migration locked a hot table. You narrate the diagnosis in order.
- Design discussionWhen to partition, when to add a read replica, when Postgres stops being the right store, and how you would scale writes.
PostgreSQL fundamentals: MVCC, storage and VACUUM
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is MVCC in PostgreSQL? | Concurrency model | Each row version carries the transaction IDs that created and deleted it (xmin and xmax). A reader uses a snapshot to decide which versions it can see, so readers do not block writers and writers do not block readers. |
| What physically happens on an UPDATE? | Storage internals | The old tuple is marked dead for future snapshots and a new tuple is written, often on another page. Every index pointing at the row may need a new entry unless the update qualifies as HOT. |
| What is a HOT update and why do you want it? | Write amplification | Heap-only tuple: when no indexed column changes and the page has free space, the new version stays on the same page and indexes are not touched. A lower fillfactor on update-heavy tables makes room for it. |
| What does VACUUM do, and how is VACUUM FULL different? | Maintenance | Plain VACUUM marks dead tuples' space reusable, updates the visibility map and freezes old rows, without blocking normal reads and writes. VACUUM FULL rewrites the table into a new file and holds an exclusive lock the whole time. |
| Why does autovacuum exist, and what makes it fall behind? | Operations | It runs VACUUM and ANALYZE when enough rows change. It falls behind on very large or very hot tables with default thresholds, and it cannot remove rows a long-running transaction might still see. |
| What is transaction ID wraparound? | Senior DBA knowledge | Transaction IDs are 32 bits, so after about two billion transactions old IDs would look like the future. Freezing old rows prevents it. If freezing cannot keep up, the server eventually refuses new writes to protect data. |
| What is the WAL, and what is it used for? | Durability | The write-ahead log records changes before data files are written. It provides crash recovery, physical replication and point-in-time recovery from a base backup plus archived WAL. |
| What is TOAST? | Large values | Large column values are compressed and/or moved to a side table automatically, so a wide JSONB or text column does not bloat every page read of the main table. |
| Database, schema, role: what is each? | Object model | A cluster holds databases; a database holds schemas; schemas hold tables. Roles are cluster-wide and act as both users and groups. Queries cannot join across databases without an extension such as postgres_fdw. |
| timestamp or timestamptz? | Data types | timestamptz stores an absolute instant (internally UTC) and displays it in the session time zone. Plain timestamp is a wall-clock value with no zone. Event times almost always want timestamptz. |
| SERIAL or an identity column? | Modern DDL | Identity columns (GENERATED ALWAYS AS IDENTITY) are standard SQL and tie the sequence to the column cleanly. Both use sequences, so values can have gaps after rollbacks. |
A quick way to prove you understand MVCC is to show it. The system columns ctid (physical location) and xmin (creating transaction) change on every update:
CREATE TABLE accounts (id int PRIMARY KEY, balance numeric NOT NULL);
INSERT INTO accounts VALUES (1, 100);
SELECT ctid, xmin, balance FROM accounts WHERE id = 1;
-- ctid | xmin | balance
-- (0,1) | 739 | 100
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
SELECT ctid, xmin, balance FROM accounts WHERE id = 1;
-- ctid | xmin | balance
-- (0,2) | 740 | 70Index questions: B-tree, GIN, GiST, BRIN and friends
| Index type | Good for | Interview follow-up |
|---|---|---|
| B-tree (default) | Equality, ranges, sorting, prefix LIKE with the right operator class | Column order in a multicolumn index: equality columns first, then the range column. |
| GIN | JSONB containment, arrays, full-text search on tsvector | Fast reads, slower writes; jsonb_path_ops is smaller but supports fewer operators than the default jsonb_ops. |
| GiST | Range types, geometry (PostGIS), nearest-neighbor, exclusion constraints | How an exclusion constraint stops two bookings of one room from overlapping in time. |
| SP-GiST | Partitioned search spaces such as IP ranges and some text patterns | Rarely needed; knowing it exists is enough for most roles. |
| BRIN | Very large tables whose physical order follows a column, such as append-only timestamps | Tiny index, but useless when rows are inserted out of order. |
| Hash | Equality lookups only | Usually no better than B-tree in practice; say why you would still pick B-tree. |
- What is a partial index? An index with a WHERE clause, such as only unprocessed jobs. It stays small and fast when queries always filter the same way.
- What is an expression index? An index on
lower(email)or another expression, used when the query filters on that exact expression. It is the fix for case-insensitive lookups without changing the column. - What does INCLUDE add to an index? Extra payload columns stored in the leaf entries, so a query can be answered by an index-only scan without making them part of the key.
- Why might an index-only scan still visit the table? It checks the visibility map; pages with recently changed rows are not marked all-visible until VACUUM runs, so the heap is read for those pages.
- How do you add an index to a busy table?
CREATE INDEX CONCURRENTLY. It takes longer and cannot run inside a transaction block, and a failed build leaves an INVALID index you must drop and retry. - How do you find unused or duplicate indexes?
pg_stat_user_indexesshows scan counts since the last stats reset; compare definitions for indexes that are prefixes of others. Every extra index slows writes and blocks HOT updates on its columns.
Query plans and EXPLAIN ANALYZE
Expect to read a plan out loud. EXPLAIN shows the planner's estimate; EXPLAIN ANALYZE runs the statement and adds actual times and row counts, so wrap writes in a transaction you roll back. Add BUFFERS to see how many pages came from cache versus disk.
CREATE INDEX orders_customer_created ON orders (customer_id, created_at);
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT id, total FROM orders
WHERE customer_id = 4242 AND created_at >= now() - interval '30 days';
-- Index Scan using orders_customer_created on orders
-- Index Cond: ((customer_id = 4242) AND (created_at >= ...))
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id, total FROM orders WHERE customer_id + 0 = 4242;
-- Gather
-- -> Parallel Seq Scan on orders
-- Filter: ((customer_id + 0) = 4242)
-- Rows Removed by Filter: 333327 (average per process, 3 processes)- Seq Scan, Index Scan, Index Only Scan, Bitmap Heap Scan: when does the planner pick each? Sequential for large shares of the table, index scan for few rows, bitmap when many rows are scattered or several indexes combine, index-only when the visibility map allows.
- Nested Loop, Hash Join, Merge Join? Nested loop for a small outer side with an indexed inner side; hash join for large unsorted inputs that fit in work_mem; merge join for inputs already sorted on the key.
- The estimate says 10 rows and the actual is 200,000. What now? Stale or too-coarse statistics. Run ANALYZE, raise the statistics target on that column, or create extended statistics when two columns are correlated.
- What does a sort spilling to disk look like, and how do you fix it? The plan shows an external merge sort. Add an index that delivers rows in order, reduce the rows earlier, or raise work_mem for that session rather than globally.
- How do you find the slowest queries in production? The pg_stat_statements extension ranks statements by total and mean time; auto_explain logs plans of statements over a threshold.
JSONB and partitioning questions
JSONB stores parsed binary JSON with keys deduplicated and reordered, so it is indexable and fast to query. Plain json keeps the exact input text, including whitespace and duplicate keys. The usual interview answer: JSONB for flexible attributes you query, regular columns for fields you filter, join or constrain on every day.
CREATE INDEX events_payload_gin ON events USING gin (payload jsonb_path_ops);
-- Uses the index: Bitmap Index Scan on events_payload_gin
SELECT count(*) FROM events
WHERE payload @> '{"type": "buy", "user": {"plan": "pro"}}';
-- Does not use it: Parallel Seq Scan with a Filter on (payload ->> 'type')
SELECT count(*) FROM events WHERE payload->>'type' = 'buy';
-- Fix for the second shape: a B-tree expression index
CREATE INDEX events_type ON events ((payload->>'type'));- What is the difference between -> and ->>? The first returns JSONB, so you can keep navigating; the second returns text, ready for comparison or display.
- When is JSONB the wrong choice? When every row has the same fields, when you need foreign keys or NOT NULL on them, or when updates rewrite a large document for a one-field change.
- What kinds of declarative partitioning exist? Range (usually by time), list (by region or tenant group) and hash (to spread load evenly). Each partition is a real table.
- What is partition pruning? The planner skips partitions whose bounds cannot match the WHERE clause, at plan time or at execution time for parameters.
- Why does adding a primary key on (id) to a partitioned table fail? Unique constraints on a partitioned table must include the partition key, because each partition enforces uniqueness only on its own rows.
- Why partition at all? Retention and maintenance more than speed: dropping or detaching a month is instant compared to deleting millions of rows, and vacuum works on smaller pieces.
CREATE TABLE measurements (
device_id int NOT NULL,
taken_at timestamptz NOT NULL,
reading double precision
) PARTITION BY RANGE (taken_at);
CREATE TABLE measurements_2026_11 PARTITION OF measurements
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE measurements_2026_12 PARTITION OF measurements
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
-- ERROR: unique constraint on partitioned table must include all partitioning columns
ALTER TABLE measurements ADD PRIMARY KEY (device_id);
-- Works
ALTER TABLE measurements ADD PRIMARY KEY (device_id, taken_at);
-- Retention without a giant DELETE
ALTER TABLE measurements DETACH PARTITION measurements_2026_11;Transactions, isolation and locking
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is the default isolation level in PostgreSQL? | Defaults | Read Committed: each statement sees data committed before that statement began. Read Uncommitted is accepted but behaves as Read Committed. |
| What does Repeatable Read give you in Postgres? | Snapshot isolation | One snapshot for the whole transaction, so repeated reads match and phantoms do not appear. A concurrent update to a row you then try to change raises a serialization error. |
| How does Serializable work, and what must the application do? | SSI | Serializable Snapshot Isolation tracks read and write dependencies and aborts one transaction when a cycle appears. The application must retry on SQLSTATE 40001. |
| How do you build a job queue on a table? | Row locks | SELECT ... FOR UPDATE SKIP LOCKED with a LIMIT, so workers grab different rows without waiting on each other. |
| Why did a quick ALTER TABLE take the site down? | Lock queue | ALTER needs an ACCESS EXCLUSIVE lock. If a long transaction holds any lock on the table, the ALTER waits, and every new query queues behind the ALTER. Set lock_timeout and retry. |
| What are advisory locks for? | Application coordination | Named locks the database does not attach to rows, used for things like making sure one cron instance runs a job. Session-level ones survive across transactions, which matters with poolers. |
| How does Postgres handle deadlocks? | Deadlock detection | After deadlock_timeout it checks for a cycle and cancels one transaction with an error. Prevent it by touching rows in a consistent order. |
WITH next_job AS (
SELECT id FROM jobs
WHERE status = 'queued' AND run_after <= now()
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running'
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.id;For migrations, the safe pattern is short and boring: SET lock_timeout = '2s' before DDL so a blocked ALTER fails fast instead of stalling traffic, retry it in a loop, build indexes concurrently, and split risky changes into add, backfill in batches, then switch. Adding a column with a constant default no longer rewrites the table (since version 11), but adding NOT NULL to an existing column still scans it.
Replication, backups and connection pooling
- Streaming versus logical replication? Streaming (physical) replication ships WAL and keeps a byte-for-byte copy of the whole cluster, used for standbys and read replicas. Logical replication publishes row changes for chosen tables, which allows different versions, partial copies and zero-downtime upgrades, but has historically not copied schema changes.
- Synchronous or asynchronous replicas? Asynchronous is the default and can lose the last commits on failover. Synchronous waits for a standby to confirm, trading commit latency for durability; synchronous_commit can be relaxed per transaction.
- What is a replication slot, and what can go wrong? It makes the primary keep WAL until a consumer has received it. An abandoned slot keeps WAL forever and fills the disk, so monitor slots and cap retained WAL with max_slot_wal_keep_size.
- Why is my query cancelled on the replica? A long read on a standby conflicts with VACUUM cleanup replayed from the primary. Options: hot_standby_feedback (which can bloat the primary), a longer max_standby_streaming_delay, or a dedicated reporting replica.
- How do you fail over? Promote a standby and repoint clients. In production this is usually automated by a tool such as Patroni with a consensus store, plus a virtual IP or a proxy so applications do not hard-code the primary.
- pg_dump or base backup? pg_dump is a logical, per-database export, fine for small databases and migrations. Physical base backups plus WAL archiving (with tools such as pgBackRest) give point-in-time recovery for large clusters.
- Why does Postgres need a connection pooler? Each connection is a separate server process with its own memory, so thousands of idle connections waste resources. PgBouncer in transaction mode lets many clients share a few server connections.
- What breaks in PgBouncer transaction mode? Anything that lives on the session: SET without LOCAL, session advisory locks, LISTEN, temporary tables, and, on older PgBouncer versions, named prepared statements.
- What does idle in transaction mean, and why is it dangerous? A client opened a transaction and stopped. It holds locks and keeps VACUUM from removing dead rows. Set idle_in_transaction_session_timeout and fix the code path.
Senior scenario questions
| Scenario | Likely cause | What you would check first |
|---|---|---|
| A table's size on disk tripled while the row count stayed flat. | Bloat from dead tuples | pg_stat_user_tables for n_dead_tup and last autovacuum, and pg_stat_activity for an old transaction holding back cleanup. |
| After a nightly bulk load, morning queries are slow. | Stale statistics | Run ANALYZE after loading; compare estimated and actual rows in the plan. |
| The app logs "too many connections" during traffic spikes. | No pooling, or leaked connections | Count connections by state in pg_stat_activity; add a pooler; fix clients that never return connections. |
| Disk on the primary keeps growing though data does not. | WAL retained | pg_replication_slots for an inactive slot, and the archiver status in pg_stat_archiver. |
| Monitoring warns about transaction ID age. | Freezing cannot keep up | Find the oldest xmin holder, kill it if safe, and run a manual VACUUM (FREEZE) on the oldest tables. |
| An UPDATE on one column became slow after adding an index. | Lost HOT updates | The new index covers the updated column, so every update now writes index entries. Question whether the index is needed. |
Fictional example
- Interviewer
- Our sessions table is updated constantly. Autovacuum runs on it every few minutes, yet the table has grown from 2 GB to 9 GB in a week. What is going on?
- Candidate
- Vacuum can only remove a dead row version once no running transaction could still need it. So my first suspect is something holding an old snapshot: a long report, a stuck migration, a connection idle in transaction, or a replica with hot_standby_feedback on. I would sort pg_stat_activity by xact_start and check backend_xmin, then look at replication slots. If I find a two-day-old idle transaction, terminating it lets the next vacuum reclaim space for reuse, though the file itself will not shrink. To get the 9 GB back without a long lock, I would use pg_repack rather than VACUUM FULL. Then I would prevent a repeat: an idle-in-transaction timeout, alerting on transaction age, and a lower fillfactor on that table so more updates stay HOT.
A two-week PostgreSQL practice plan
- Days 1 to 3: install Postgres locally, generate a million rows with generate_series, and watch ctid and xmin change as you update. Turn autovacuum off on one table, update it heavily, and see dead tuples pile up in pg_stat_user_tables.
- Days 4 to 6: build each index type on suitable data, then read EXPLAIN (ANALYZE, BUFFERS) before and after. Break a predicate on purpose and explain the new plan.
- Days 7 to 9: open two psql sessions and reproduce a lock queue, a deadlock, a SKIP LOCKED queue and a serialization failure under Serializable.
- Days 10 to 12: set up a streaming replica on another port, create a logical publication, and practice explaining failover and the slot disk-fill trap.
- Days 13 and 14: rehearse the scenario table out loud, two minutes per answer, starting from the view or command you would query first.
For neighboring topics: the MySQL interview questions page covers the InnoDB side, where the primary key is the table layout and gap locks behave very differently. Redis interview questions pairs with the caching questions that follow most Postgres scaling answers, and MongoDB interview questions is the document-store counterpart. For architecture rounds, see database sharding and SQL vs NoSQL in system design.
Postgres answers are easy to know and hard to say in order under pressure. When you run a mock round, Natively, an AI interview assistant for Mac and Windows, writes a live transcript on your computer, so afterwards you can check whether you named the mechanism before jumping to a fix. In practice sessions it can read a pasted EXPLAIN plan or schema from a screenshot and suggest what to look at, and with Pro or the free trial it can draw on the résumé and job description you add. The transcript and notes remain for review once the session ends.
Questions people ask
What PostgreSQL questions are asked in interviews?
Expect MVCC and VACUUM, the index types (B-tree, GIN, GiST, BRIN), reading EXPLAIN ANALYZE, isolation levels and row locks, JSONB, partitioning, replication and connection pooling. Senior rounds turn these into production scenarios such as table bloat or a migration that blocked traffic.
Why does PostgreSQL need VACUUM?
Because MVCC writes a new row version on every update and delete leaves the old one in place. VACUUM makes that dead space reusable, updates the visibility map for index-only scans and freezes old transaction IDs to prevent wraparound.
What is the difference between GIN and GiST indexes in PostgreSQL?
GIN is an inverted index, best for values containing many elements such as JSONB, arrays and full-text documents. GiST is a balanced tree of bounding predicates, used for ranges, geometry, nearest-neighbor search and exclusion constraints.
How do I prepare for a PostgreSQL DBA interview?
Practice on a local server: generate large tables, read plans, reproduce lock waits and deadlocks in two sessions, set up a streaming replica and a replication slot. Then rehearse bloat, wraparound, replica lag and connection exhaustion as spoken scenarios.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
