PrepStack › Databases › PostgreSQL
PostgreSQL interview cheat sheet
Architecture, MVCC & VACUUM, JSONB, indexes, query tuning, replication and ops
PostgreSQL interviews go past plain SQL. Interviewers want to know how Postgres works inside: one process per connection, WAL, MVCC tuple versions and why VACUUM exists. Then they check practical skills: choosing an index type, reading EXPLAIN ANALYZE, JSONB, UPSERT, partitioning, replication and backups. Postgres-only snippets are shown without output; the few portable ones are run in SQLite to verify them. Read the 15-minute revision first, then switch to Quiz mode.
15-minute revision
- Process per connection: the postmaster forks one backend process for every client. Connections are expensive (MBs each), so use a pooler like PgBouncer in transaction mode.
- WAL (write-ahead log): every change is written to the WAL and flushed before commit returns. Data pages are written later by the checkpointer and background writer. WAL drives crash recovery, replication and PITR.
- MVCC: an UPDATE writes a new row version. Each tuple has
xmin(creating transaction) andxmax(deleting one). Readers never block writers and writers never block readers. - Old row versions become dead tuples. VACUUM makes their space reusable, updates the visibility map and freezes old XIDs.
VACUUM FULLrewrites the table under an exclusive lock. - XIDs are 32-bit. If old rows are never frozen, transaction ID wraparound forces Postgres to stop accepting writes. Watch
age(datfrozenxid)and kill long-running transactions. - Default isolation is Read Committed (new snapshot per statement). Repeatable Read is snapshot isolation with no phantoms. Serializable uses SSI and can fail with
40001, so retry. - JSONB is parsed binary (no key order, no duplicates, indexable with GIN). JSON keeps the exact text. Default to JSONB.
- Index types: B-tree (default, equality + range + sort), Hash (= only), GIN (jsonb, arrays, full-text), GiST (geometry, ranges, nearest neighbour), SP-GiST (partitioned spaces), BRIN (huge, naturally ordered tables).
- Partial index (
WHERE status = 'pending'), expression index (lower(email)), covering index (INCLUDE (total)) for index-only scans. Build in production withCREATE INDEX CONCURRENTLY. EXPLAIN ANALYZEruns the query. Compare estimated vs actual rows, multiply time byloops, and look for big Seq Scans, disk sorts and misestimates.- Since PG12, simple CTEs are inlined. Use
AS MATERIALIZEDto force a fence,NOT MATERIALIZEDto force inlining. - UPSERT:
INSERT ... ON CONFLICT (key) DO UPDATE SET col = EXCLUDED.colis atomic.RETURNINGgives back written rows.MERGE(PG15+) handles insert/update/delete from a source in one statement. - Use
GENERATED ALWAYS AS IDENTITYinstead ofserial. Sequences are not transactional, so gaps are normal. - Declarative partitioning by range, list or hash. The planner prunes partitions, and dropping an old partition is much cheaper than a big DELETE.
- Streaming replication copies WAL bytes (whole cluster, read-only replicas). Logical replication sends row changes per table (cross-version). Patroni automates failover.
- Backups:
pg_dumpis a logical snapshot of one database. A base backup plus archived WAL gives point-in-time recovery. Use pgBackRest, Barman or WAL-G in production.
Architecture & Connections
Process architecture, shared buffers & WAL
One OS process per connection, a shared buffer cache, and a write-ahead log that makes commits durable.
- The postmaster (the main
postgresprocess) listens on port 5432. For every new client it forks a backend process that serves only that connection. - All backends share memory: shared_buffers (the page cache, 8 KB pages), WAL buffers and lock tables. Per-backend memory such as
work_memis used for each sort or hash step, so it can be allocated many times per query. - WAL: a change is first written to the write-ahead log. At commit the WAL is flushed (
fsync) to disk. Changed data pages (dirty pages) stay in memory and are written later. - The checkpointer writes all dirty pages at a checkpoint (by
checkpoint_timeoutormax_wal_size). After that, older WAL is not needed for crash recovery. The background writer trickles dirty pages out between checkpoints. - Other background processes: walwriter, autovacuum launcher and workers, archiver (copies WAL for PITR), walsender/walreceiver (replication), the logical replication launcher, and parallel query workers. PG18 also added I/O worker processes for asynchronous I/O.
- Postgres also relies on the OS page cache, so data is often cached twice. A common start is about 25% of RAM for
shared_buffersandeffective_cache_sizeset near the total cache available.
Interview questions
- Describe the PostgreSQL process architecture.
- What is the WAL and why does it exist?
- What does a checkpoint do, and what goes wrong if checkpoints are too frequent?
- Why is shared_buffers not set to 80% of RAM like some other databases?
Connection pooling & PgBouncer
Backends are heavy, so put a pooler in front and share a small set of server connections among many clients.
- Each connection is a process using several MB, and many idle connections still slow down snapshots. Good throughput usually comes from a small number of active connections, often a few per CPU core.
- PgBouncer is a lightweight proxy. Clients connect to it, and it hands out real server connections from a pool.
- Session mode: a server connection belongs to the client until it disconnects. Everything works, but it saves little.
- Transaction mode: a server connection is lent only for one transaction. This gives the biggest win, but session state breaks:
SET,LISTEN, session advisory locks,WITH HOLDcursors and SQL-levelPREPARE. - Statement mode: like transaction mode, but multi-statement transactions are not allowed. It is rarely used.
- PgBouncer 1.21+ can track protocol-level prepared statements in transaction mode when
max_prepared_statementsis set above zero. App-side pools (HikariCP and similar) still help, but they do not share connections across app instances.
Interview questions
- Why does PostgreSQL need an external connection pooler?
- Compare PgBouncer's session, transaction and statement pooling.
- You switched to transaction pooling and see 'prepared statement does not exist' errors. Why, and how do you fix it?
MVCC, VACUUM & Transactions
MVCC, snapshots & isolation levels
Every UPDATE writes a new tuple version tagged with transaction IDs, and each transaction sees the versions its snapshot allows.
- Every row version (tuple) has hidden columns:
xmin(the XID that inserted it),xmax(the XID that deleted or locked it, 0 if none) andctid(its physical location). - INSERT creates a tuple with
xmin. DELETE setsxmax. UPDATE does both: it marks the old version withxmaxand inserts a new version. Old versions stay in the table until VACUUM. - A snapshot records which transactions were committed when it was taken. A tuple is visible if its
xmincommitted before the snapshot and itsxmaxdid not. - So readers do not block writers and writers do not block readers. Two writers on the same row still wait for each other through row locks.
- Read Committed (default) takes a new snapshot for every statement. Repeatable Read takes one snapshot for the whole transaction. Serializable adds SSI checks on top of Repeatable Read.
- Read Uncommitted behaves like Read Committed in Postgres, so dirty reads never happen. Repeatable Read also prevents phantoms, which is stronger than the SQL standard requires.
Interview questions
- How does MVCC work in PostgreSQL?
- What is the default isolation level, and what anomalies can happen in it?
- What is write skew and which level prevents it?
- What is a HOT update?
VACUUM, autovacuum, bloat & XID wraparound
VACUUM recycles dead tuples and freezes old ones. If it falls behind, you get bloat, and in the worst case a wraparound shutdown.
- Plain VACUUM marks dead tuple space as reusable, cleans index entries, updates the free space map and the visibility map. It runs alongside reads and writes and does not usually shrink the file.
- VACUUM FULL rewrites the table into a new file and gives space back to the OS, but it holds an ACCESS EXCLUSIVE lock. Online options: the
pg_repackextension, orREPACK (CONCURRENTLY)in PG19. - ANALYZE refreshes planner statistics. Autovacuum runs both. A table is vacuumed after about
autovacuum_vacuum_threshold(50) +autovacuum_vacuum_scale_factor(0.2) × rows dead tuples, which is too lazy for huge tables, so tune per table. - Bloat is dead or empty space that stays in tables and indexes. Causes: autovacuum that is too slow, long-running or idle-in-transaction sessions, forgotten replication slots and old prepared transactions. All of these hold back the cleanup horizon.
- XID wraparound: transaction IDs are 32-bit, and comparisons use a window of about 2 billion. Freezing marks old tuples as visible to everyone, so their XIDs can be reused. When a table's age reaches
autovacuum_freeze_max_age(200 million), an aggressive anti-wraparound vacuum runs, even if autovacuum is turned off. - If freezing still cannot keep up, Postgres warns, and close to the limit it refuses new XIDs (no writes) until you vacuum. This is a real production outage pattern.
- The visibility map marks all-visible pages. Index-only scans and vacuum use it to skip pages. Recent versions sped up vacuum: lower memory use for dead-tuple storage in PG17, and parallel index processing for autovacuum in PG19.
Interview questions
- Why does PostgreSQL need VACUUM?
- Difference between VACUUM and VACUUM FULL?
- What is transaction ID wraparound and how do you prevent it?
- Autovacuum is running but the table keeps growing. What do you check?
Data Types & JSON
Data types that interviewers ask about
Pick exact types: numeric for money, timestamptz for time, text for strings, jsonb for documents, uuid or bigint for keys.
- numeric is exact decimal with large precision, but slower. real/double precision are IEEE floats: fast, but
0.1 + 0.2is not exactly0.3. Store money asnumeric(12,2)or as integer cents. - text vs varchar(n) vs char(n):
textandvarcharare stored the same way and perform the same.varchar(n)only adds a length check.char(n)pads with spaces and is almost never what you want. - timestamptz stores an absolute instant (in UTC) and converts to the session time zone on display. Plain
timestamphas no zone. Default totimestamptz. - uuid is a 16-byte type.
gen_random_uuid()(v4) is built in since PG13.uuidv7()(PG18) gives time-ordered UUIDs that index much better than random v4. - enum types are ordered and small. Adding a value is easy (
ALTER TYPE ... ADD VALUE), but removing or renaming is painful. A lookup table or a CHECK constraint is more flexible. - Arrays (
int[],text[]) are good for tags. Query them withANY,@>and&&, and index them with GIN. Range types (int4range,tstzrange,daterange, and multiranges since PG14) model intervals. With a GiST exclusion constraint they can block overlapping bookings.
Interview questions
- numeric vs double precision: when do you use each?
- text vs varchar(n) vs char(n) in Postgres?
- UUID vs bigint identity as a primary key?
- How would you stop double-booking a meeting room in the database?
Sequences, serial & identity columns
Identity columns are the SQL-standard replacement for serial. Both use a sequence, and sequences never roll back.
- A sequence is a special one-row object that hands out numbers with
nextval(). It is fast because it is not transactional: a rolled-back insert still uses up its number, so gaps are normal. - serial / bigserial is shorthand: an int column, a sequence owned by it, and
DEFAULT nextval(...). It is not a real type, and its permissions and dumps behave a little oddly. - Identity columns (PG10+):
GENERATED ALWAYS AS IDENTITYrejects manual values unless you writeOVERRIDING SYSTEM VALUE.GENERATED BY DEFAULT AS IDENTITYlets you supply values. - Use bigint for keys on tables that can grow. Running out of int4 (about 2.1 billion) is a known outage story.
- After bulk loading explicit ids, move the sequence with
setvalorALTER TABLE ... ALTER COLUMN id RESTART WITH. Otherwise you get duplicate-key errors later. - Sequences are not replicated by logical replication before PG19, which added sequence replication. Before that, sync them by hand during cutovers.
Interview questions
- serial vs identity column?
- Why are there gaps in my ids?
- How do you get the id of a row you just inserted?
JSONB, operators & GIN indexes
JSONB stores parsed binary JSON that you can query with operators and index with GIN. JSON just keeps the text.
- json stores the input text exactly: whitespace, key order and duplicate keys. It is parsed again on every access. jsonb is decomposed binary: keys are sorted and deduplicated (the last one wins), it is a little slower to write and much faster to query.
- Access:
->returns jsonb,->>returns text,#>/#>>follow a path, and subscriptingdata['a']['b']works since PG14. - Tests:
@>contains,<@is contained by,?key exists,?|any key,?&all keys,@?/@@jsonpath. - Modify:
||merges,-removes a key,#-removes a path,jsonb_set()sets a path. Every update writes a whole new row version, so huge documents that change often are costly. - GIN with the default
jsonb_opssupports?,?|,?&,@>,@?and@@.jsonb_path_opssupports only@>,@?and@@, but it is smaller and faster for containment. - For one hot key, a B-tree expression index on
(data->>'email')beats GIN. PG17 added SQL/JSONJSON_TABLE()to turn JSON into rows and columns.
Interview questions
- JSON vs JSONB?
- Which index would you use to speed up queries on a JSONB column?
- When should data NOT go into JSONB?
Indexes & Query Performance
Index types: B-tree, Hash, GIN, GiST, SP-GiST, BRIN
B-tree for almost everything. GIN for 'contains', GiST for geometry and overlap, BRIN for huge append-only tables.
- B-tree (default):
= < <= > >= BETWEEN IN,IS NULL,LIKE 'abc%'(with the C collation ortext_pattern_ops), and ORDER BY. It is the only type that supports UNIQUE indexes. - Hash: equality only. It has been crash-safe (WAL-logged) since PG10 and can be smaller than B-tree for long keys. It is rarely chosen.
- GIN (Generalized Inverted Index) maps each element to the rows that contain it. Use it for jsonb, arrays, full-text
tsvectorand trigram search. Lookups are fast, writes are slower (it uses a pending list,fastupdate). - GiST is a balanced tree of bounding predicates. Use it for geometry (PostGIS), range overlap, nearest-neighbour
ORDER BY <->, and exclusion constraints. - SP-GiST is for space-partitioned structures (quadtrees, k-d trees, radix tries): points, IP ranges, text prefixes with uneven distribution.
- BRIN stores the min/max per block range. It is tiny (KBs for a TB table) and works when the column follows the physical order, such as
created_atin an append-only log.
Interview questions
- What index types does PostgreSQL support and when do you use each?
- When does BRIN beat B-tree?
- Why might Postgres ignore an index you created?
Partial, expression & covering indexes
Index only the rows you query, index the expression you filter on, and INCLUDE extra columns to get index-only scans.
- Partial index:
CREATE INDEX ... WHERE status = 'pending'. It is small and cheap to maintain. The query's WHERE must imply the index predicate. - Partial unique index solves soft delete:
UNIQUE (email) WHERE deleted_at IS NULLlets deleted rows reuse an email. - Expression index:
CREATE INDEX ON users (lower(email)). It is used only when the query uses the same expression. The function must be IMMUTABLE. - Covering index (PG11+):
CREATE INDEX ON orders (customer_id) INCLUDE (total). The extra columns are stored in the leaf pages but are not part of the key, which enables index-only scans. - Index-only scans still check the visibility map. If many pages are not all-visible (vacuum is behind), Postgres has to visit the heap anyway (
Heap Fetchesin EXPLAIN). - Every index slows down writes, takes space and can prevent HOT updates. Find unused ones with
pg_stat_user_indexes.idx_scan = 0.
Interview questions
- What is a partial index and give a real use case.
- What is a covering index and how does INCLUDE differ from adding columns to the key?
- Your index-only scan shows high 'Heap Fetches'. Why?
Reading EXPLAIN ANALYZE
Read the plan tree from the inside out, compare estimated with actual rows, and find where time and buffers go.
EXPLAINshows the plan with estimates.EXPLAIN (ANALYZE, BUFFERS)runs the query and adds actual times, rows, loops and buffer hits/reads. PG18 shows buffers by default with ANALYZE.cost=0.43..8.45is startup..total cost in planner units, not milliseconds.rowsis the estimate,actual rowsis the truth per loop. Multiply time and rows byloops.- A large estimate vs actual gap (10× or more) is the main clue. It usually leads to a wrong join type or join order. Fix with ANALYZE, a higher statistics target, or
CREATE STATISTICSfor correlated columns. - Scan nodes: Seq Scan, Index Scan, Index Only Scan, Bitmap Index + Bitmap Heap Scan (many rows from an index). Join nodes: Nested Loop (small outer side + indexed inner), Hash Join (large unsorted inputs), Merge Join (both sorted).
- Red flags:
Rows Removed by Filtermuch larger than rows returned (missing index),Sort Method: external merge Disk(raisework_mem),Heap Fetcheson index-only scans, and Nested Loop with a huge number of loops. - Wrap DML in
BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;because ANALYZE really executes the statement. Usepg_stat_statementsto find which queries are worth explaining.
Interview questions
- How do you read an EXPLAIN ANALYZE plan?
- Estimated rows = 1, actual rows = 50,000. What happened and what do you do?
- What is the difference between Index Scan, Index Only Scan and Bitmap Heap Scan?
- A query is fast in psql but slow from the app. Why?
Powerful SQL Features
CTEs, recursion & MATERIALIZED
WITH names a subquery. Since PG12 simple CTEs are inlined unless you write MATERIALIZED.
- A CTE (
WITH x AS (...)) makes complex queries readable and lets you reference a result more than once. - Before PG12 every CTE was materialized and acted as an optimization fence: filters from outside were not pushed in. Old advice to 'avoid CTEs for speed' comes from this.
- PG12+: a CTE that is non-recursive, has no side effects and is referenced once is inlined like a subquery. Write
AS MATERIALIZEDto force computing it once (for example an expensive function), orAS NOT MATERIALIZEDto force inlining. - Recursive CTEs (
WITH RECURSIVE) walk trees and graphs: an anchor queryUNION ALLa recursive part that joins back to the CTE. PG14 addedSEARCHandCYCLEclauses for ordering and cycle detection. - Data-modifying CTEs (
WITH moved AS (DELETE ... RETURNING *) INSERT INTO archive SELECT * FROM moved) run several writes in one statement and one snapshot.
Interview questions
- Are CTEs an optimization fence in PostgreSQL?
- How does a recursive CTE execute?
- CTE vs subquery vs temp table?
Window functions
Window functions compute over related rows (ranking, running totals, previous row) without collapsing them like GROUP BY.
- Syntax:
fn() OVER (PARTITION BY ... ORDER BY ... frame). PARTITION BY splits rows into groups and ORDER BY orders rows within each group. - ROW_NUMBER gives unique numbers, RANK leaves gaps after ties (1,1,3), DENSE_RANK does not (1,1,2). NTILE(n) splits rows into buckets.
- LAG / LEAD read the previous or next row (period-over-period changes). FIRST_VALUE, LAST_VALUE and NTH_VALUE read positions in the frame.
- Aggregates over a window:
SUM(x) OVER (ORDER BY d)is a running total. With ORDER BY, the default frame isRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so ties are summed together. UseROWSfor a strict row-by-row frame. - Window functions run after WHERE, GROUP BY and HAVING. To filter on them (top-N per group), wrap them in a subquery or CTE. PG supports a named
WINDOW w AS (...)clause.
Interview questions
- Difference between ROW_NUMBER, RANK and DENSE_RANK?
- How do you get the top 3 earners per department?
- GROUP BY vs window function?
UPSERT (ON CONFLICT), RETURNING & MERGE
ON CONFLICT is the atomic, race-free upsert. RETURNING hands back written rows. MERGE syncs a target from a source.
INSERT ... ON CONFLICT (cols) DO NOTHING | DO UPDATE SET ...needs a unique index or constraint as the arbiter.EXCLUDEDis the row that was proposed for insert.- It is atomic under concurrency: two sessions upserting the same key never both insert, and you never get a unique violation. Add
WHEREtoDO UPDATEto update conditionally. - One statement cannot update the same row twice: duplicate keys in one VALUES list raise 'ON CONFLICT DO UPDATE command cannot affect row a second time'. Deduplicate the input first.
- RETURNING works with INSERT, UPDATE, DELETE and MERGE and saves a round trip. PG18 added
OLDandNEWin RETURNING, so you can return values before and after the change. - MERGE (PG15+):
MERGE INTO target USING source ON ... WHEN MATCHED THEN UPDATE/DELETE WHEN NOT MATCHED THEN INSERT. PG17 addedRETURNINGandWHEN NOT MATCHED BY SOURCE. - MERGE is not a concurrency-safe upsert. Concurrent inserts can still cause unique violations. Use ON CONFLICT for high-concurrency upserts and MERGE for batch sync jobs.
Interview questions
- How do you do an upsert in PostgreSQL?
- Why not just SELECT, then INSERT or UPDATE?
- MERGE vs ON CONFLICT?
LISTEN / NOTIFY
A lightweight pub/sub built into Postgres. Notifications are sent on commit, but they are not stored if nobody is listening.
LISTEN channelsubscribes the session.NOTIFY channel, 'payload'orpg_notify(channel, payload)publishes to every listener in the same database.- Notifications are delivered only when the sending transaction commits, and they are dropped on rollback. Identical notifications in the same transaction can be merged into one.
- The payload must be shorter than 8000 bytes by default. Send an id and let the listener read the row.
- Not durable: listeners that are disconnected miss messages. Use it as a wake-up signal next to a table (outbox or job queue), not as the queue itself.
- Each listener needs its own long-lived session. LISTEN does not work through transaction-mode PgBouncer. Many busy notifiers can also cause contention at commit time.
- Typical uses: cache invalidation, waking job workers, pushing changes to WebSocket servers. For durable change streams use logical decoding (for example Debezium).
Interview questions
- How does LISTEN/NOTIFY work and what are its guarantees?
- How would you build a job queue on PostgreSQL?
- Why does LISTEN break behind PgBouncer?
Scale, Security & Operations
Row-level security (RLS)
Policies attach a hidden WHERE clause to every query on a table, enforced by the database for each role.
- Turn it on with
ALTER TABLE t ENABLE ROW LEVEL SECURITY. With no policy the default is deny all for normal roles. CREATE POLICY name ON t [FOR SELECT|INSERT|UPDATE|DELETE|ALL] [TO role] USING (expr) WITH CHECK (expr). USING filters rows you can see, update or delete. WITH CHECK validates new or changed rows.- Several permissive policies are combined with OR. Restrictive policies (
AS RESTRICTIVE) are combined with AND on top. - Superusers, roles with BYPASSRLS, and the table owner skip RLS. Use
FORCE ROW LEVEL SECURITYto apply it to the owner too, and connect as a non-owner app role. - Multi-tenant pattern:
USING (tenant_id = current_setting('app.tenant_id')::uuid), withSET LOCAL app.tenant_id = ...at the start of each transaction (safe with transaction pooling). - Performance: the policy expression is added to every query. Index
tenant_idand keep policy functions simple and STABLE.
Interview questions
- What is row-level security and when would you use it?
- Difference between USING and WITH CHECK?
- RLS is enabled but the app still sees every row. Why?
Table partitioning
Split one logical table into child tables by range, list or hash so queries prune partitions and old data can be dropped instantly.
- Declarative partitioning (PG10+):
CREATE TABLE t (...) PARTITION BY RANGE | LIST | HASH (key), thenCREATE TABLE t_2026_12 PARTITION OF t FOR VALUES FROM (...) TO (...). - Range for time series, list for discrete values (region, tenant tier), hash to spread rows evenly when there is no natural range. A DEFAULT partition catches rows that fit nowhere else.
- Partition pruning skips partitions that cannot match, at plan time and at execution time (for parameters). It only works if the query filters on the partition key.
- Primary keys and unique constraints must include the partition key, because there are no global indexes. An index created on the parent is created on every partition.
- Retention becomes
DETACH PARTITION ... CONCURRENTLY(PG14+) andDROP TABLE. That is instant compared with a huge DELETE that bloats the table and needs vacuum. - Do not over-partition. Thousands of tiny partitions slow planning and use memory. Tools like
pg_partmancreate future partitions automatically. For sharding across machines, look at Citus.
Interview questions
- When would you partition a table?
- What is partition pruning?
- Why must the primary key include the partition key?
- Partitioning vs sharding?
Replication & high availability
Physical streaming copies the WAL to read-only replicas. Logical sends table changes. Patroni turns replicas into automatic failover.
- Streaming (physical) replication: standbys receive WAL bytes from the primary's walsender and replay them. The copy is identical at block level, covers the whole cluster, needs the same major version, and replicas are read-only hot standbys.
- Asynchronous by default: commits do not wait for the replica, so a failover can lose the last few transactions. Synchronous: list standbys in
synchronous_standby_names(for exampleANY 1 (s1, s2)) and commits wait according tosynchronous_commit. synchronous_commitlevels:off,local,remote_write(in the standby's OS),on(flushed on the standby),remote_apply(replayed, visible to reads on the standby).- Logical replication:
CREATE PUBLICATION/CREATE SUBSCRIPTION. Row changes per table, across major versions, into writable targets. It needswal_level = logical. It does not copy DDL. Sequences are replicated only since PG19. - Replication slots make the primary keep WAL until a consumer has it. An abandoned slot fills the disk, so set
max_slot_wal_keep_sizeand monitor. - Patroni runs next to each node, stores the leader lock in a DCS (etcd, Consul, ZooKeeper or Kubernetes), promotes a replica when the leader lock expires, and fences the old primary (often with
pg_rewindto rejoin). Clients find the leader through HAProxy, a virtual IP, or multi-host connection strings.
Interview questions
- Streaming vs logical replication?
- Synchronous vs asynchronous replication trade-off?
- How does automatic failover work with Patroni?
- Can you read from replicas? What are the pitfalls?
Backups: pg_dump vs base backups & PITR
pg_dump gives a portable logical copy. A base backup plus archived WAL lets you restore to any second.
- pg_dump exports one database as SQL or an archive, from a consistent snapshot, without blocking writes. It is portable across versions and platforms.
pg_dumpalladds roles and tablespaces (globals). - Formats: plain SQL (
psqlto restore), custom-Fcand directory-Fd(usepg_restore, selective restore, parallel-j). Restore time grows with data size because indexes are rebuilt. - Physical backup:
pg_basebackup(or pgBackRest, Barman, WAL-G) copies the data directory while the server runs. Together with continuous WAL archiving (archive_mode,archive_command/archive_library) this gives PITR. - PITR restore: restore the base backup, set
restore_commandand a target (recovery_target_time,_lsnor_xid), createrecovery.signal, start the server. It replays WAL up to that moment, for example just before a badDELETE. - PG17 added incremental backups:
pg_basebackup --incremental(withsummarize_wal = on), then merge the chain withpg_combinebackup. - A replica is not a backup: a DROP TABLE replicates within milliseconds. Test restores regularly, because an untested backup is just a hope.
Interview questions
- pg_dump vs pg_basebackup?
- Someone ran DELETE without WHERE at 10:15. How do you recover?
- Is a streaming replica enough as a backup?
Full-text search & extensions
Built-in full-text search with tsvector and GIN, plus extensions such as pg_stat_statements, pgvector and PostGIS.
- Full-text search:
to_tsvector('english', text)stems words and removes stop words. A query is atsquery(to_tsquery,plainto_tsquery,websearch_to_tsqueryfor Google-like input). Match with@@, rank withts_rank, highlight withts_headline. - Store a generated tsvector column and add a GIN index. Use
setweightto rank title matches above body matches.LIKE '%term%'cannot use a B-tree; use FTS orpg_trgm. - Extensions add types, functions and index methods:
CREATE EXTENSION name. Some must be listed inshared_preload_librariesfirst (pg_stat_statements, auto_explain via LOAD or preload, pg_cron). - pg_stat_statements: normalized query stats (calls, total and mean time, rows, buffers). It is the first tool for finding which queries to optimize.
- pgvector: a
vector(n)type with distance operators<->(L2),<=>(cosine),<#>(negative inner product), and approximate HNSW and IVFFlat indexes. It brings semantic and RAG search next to your relational data. - PostGIS:
geometry/geographytypes,ST_DWithin,ST_Intersects, GiST indexes. Others:pg_trgm(fuzzy / ILIKE),postgres_fdw(query remote Postgres),pgcrypto,pg_partman,pg_cron, TimescaleDB, Citus.
Interview questions
- How does full-text search work in Postgres?
- How do you find the slowest queries in production?
- Would you use pgvector or a dedicated vector database?
- Why can't
LIKE '%term%'use a normal index, and how do you fix it?
PostgreSQL vs MySQL & what's new (17, 18, 19)
Postgres is strict, feature-rich and extensible; MySQL is simpler and widely hosted. Know the trade-offs and the headline features of recent releases.
- Postgres strengths: strict SQL standard support, rich types (jsonb, arrays, ranges), many index types, transactional DDL, CTEs, window functions, partial indexes, RLS, and a huge extension ecosystem.
- MySQL (InnoDB) strengths: simple to run, very common in hosting, mature replication tooling, clustered primary key storage that makes PK range scans fast, and thread-per-connection that handles more connections without a pooler.
- PG17 (Sept 2024):
JSON_TABLEand SQL/JSON functions,MERGE ... RETURNINGandWHEN NOT MATCHED BY SOURCE, incremental backups withpg_combinebackup, a lower-memory VACUUM, andCOPY ... ON_ERROR ignore. - PG18 (Sept 2025): asynchronous I/O subsystem,
uuidv7(), virtual generated columns (now the default),OLD/NEWin RETURNING, B-tree skip scan, temporal constraints (WITHOUT OVERLAPS), OAuth authentication, data checksums on by default,pg_upgradekeeps planner statistics, and MD5 passwords deprecated. - PG19 (Nov 2026): the
REPACKcommand (with CONCURRENTLY) to remove bloat, logical replication of sequences, aWAITcommand for read-your-writes on standbys, parallel index vacuuming in autovacuum with prioritization, and thepg_plan_adviceextension for steering plans. - Major releases come once a year and each is supported for 5 years. Minor releases (for example 18.x) contain only fixes and need just a restart.
Interview questions
- PostgreSQL vs MySQL: how would you choose?
- What are the notable features in recent PostgreSQL releases?
- What does 'transactional DDL' mean and why does it matter?
- How do you upgrade to a new major version?