Technology

PostgreSQL Interview Questions and Answers

PostgreSQL is the most advanced open-source relational database and a favourite of modern product teams. These PostgreSQL interview questions cover data types, constraints and basic SQL for freshers, then MVCC, VACUUM, index types, JSONB, query plans, partitioning and replication for experienced developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise PostgreSQL questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
PostgreSQL Interview Questions with answers. Examples: What is PostgreSQL, and why choose it? What is the difference between SERIAL and IDENTITY columns? What is the difference between JSON and JSONB? What is MVCC in PostgreSQL?
PostgreSQL Interview Questions: 30 questions with model answers on this page.

Basic PostgreSQL interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is PostgreSQL, and why choose it?

PostgreSQL is an open-source, object-relational database known for standards compliance, reliability and extensibility. It supports advanced data types such as JSONB, arrays and ranges, full-text search, powerful indexing, window functions and CTEs, and extensions such as PostGIS for geospatial data and pgvector for AI embeddings.

2. What is the difference between SERIAL and IDENTITY columns?

Answer flow · 4 steps
  1. Both create auto-incrementing integers.

  2. SERIAL is older PostgreSQL-specific shorthand that creates a sequence and a default value.

  3. GENERATED ALWAYS AS IDENTITY is the SQL-standard approach introduced in PostgreSQL 10, with clearer ownership and permissions, and it is recommended for new tables.

  4. UUIDs are another option for distributed systems.

3. What is the difference between JSON and JSONB?

Answer flow · 3 steps
  1. JSON stores the exact text, keeping whitespace, key order and duplicate keys, and must be parsed each time it is read.

  2. JSONB stores a decomposed binary format, which is slightly slower to write but much faster to query, and supports GIN indexes and operators such as @> for containment.

  3. JSONB is the usual choice.

4. Which psql commands do you use often?

\l lists databases, \c dbname connects to one, \dt lists tables, \d table describes a table with its columns and indexes, \dn lists schemas, \du lists roles, \x toggles expanded output, \timing shows query time, \i file runs a SQL file and \q quits. \? shows all meta-commands.

5. What are schemas in PostgreSQL?

Answer flow · 3 steps
  1. A schema is a namespace inside a database that contains tables, views and functions.

  2. Every database has a public schema by default.

  3. Schemas organise objects (for example separate schemas for app data and reporting), control access with privileges, and allow the same table name in different schemas. search_path decides which schemas are searched when a name is not qualified.

6. Which PostgreSQL data types do you use most?

integer and bigint, numeric for exact money values, text (with no performance difference from varchar), boolean, timestamptz for points in time (stored in UTC), date, uuid, jsonb, arrays such as text[], and enums. timestamptz should be preferred over timestamp without time zone for events, to avoid time zone bugs.

7. What does the RETURNING clause do?

RETURNING returns values from rows affected by INSERT, UPDATE or DELETE in the same statement, such as INSERT INTO orders (...) VALUES (...) RETURNING id, created_at. It saves a second query to read generated IDs, defaults or updated values, and works well with upserts and bulk operations.

8. How do you do an upsert in PostgreSQL?

Answer flow · 3 steps
  1. INSERT ... ON CONFLICT (column) DO UPDATE SET ... updates the existing row when a unique constraint would be violated, using EXCLUDED to refer to the new values, for example ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name.

  2. ON CONFLICT DO NOTHING skips duplicates.

  3. PostgreSQL 15 also added the SQL-standard MERGE statement.

9. How do roles and privileges work in PostgreSQL?

Answer flow · 3 steps
  1. Users and groups are both roles.

  2. CREATE ROLE app LOGIN PASSWORD '...' creates a login role, and GRANT gives privileges such as SELECT, INSERT and UPDATE on tables, or USAGE on schemas.

  3. Roles can be members of other roles to share privileges, ALTER DEFAULT PRIVILEGES applies grants to future tables, and row-level security policies can restrict which rows each role sees.

10. What constraints are available in PostgreSQL?

NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY with ON DELETE actions, CHECK for conditions such as price >= 0, and EXCLUDE constraints, which prevent overlapping values, for example two bookings for the same room in overlapping time ranges using a GiST index. Constraints can be deferred until commit, which helps with circular references.

11. What is the difference between OFFSET and keyset pagination?

OFFSET pagination (LIMIT 20 OFFSET 1000) is simple but the database still reads and discards all skipped rows, so later pages get slower, and rows can be missed or repeated when data changes. Keyset pagination filters on the last seen value, such as WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20, which uses an index and stays fast on any page.

Intermediate PostgreSQL interview questions

Applied problems, trade-offs and questions about your own projects.

12. What is MVCC in PostgreSQL?

Answer flow · 3 steps
  1. Multi-Version Concurrency Control means updates create new row versions instead of overwriting rows, and each transaction sees a consistent snapshot of data.

  2. Readers never block writers and writers never block readers.

  3. The old row versions (dead tuples) remain until VACUUM cleans them up.

13. What does VACUUM do?

Answer flow · 3 steps
  1. VACUUM removes dead tuples left by updates and deletes so the space can be reused, updates the visibility map, and prevents transaction ID wraparound.

  2. VACUUM FULL rewrites the table to return space to the operating system but locks it.

  3. Autovacuum runs automatically; on busy tables its settings may need tuning to avoid table bloat.

14. What index types does PostgreSQL support?

B-tree (the default, for equality and range queries), Hash (equality only), GIN (for JSONB, arrays and full-text search), GiST and SP-GiST (for geometric data, ranges and nearest-neighbour search) and BRIN (very small indexes for huge tables with naturally ordered data, such as timestamps). Partial indexes and expression indexes add flexibility.

15. How do you read an EXPLAIN ANALYZE output?

Answer flow · 3 steps
  1. It shows the plan tree with each node, such as Seq Scan, Index Scan, Bitmap Heap Scan, Hash Join or Nested Loop, with estimated and actual rows, time and loops.

  2. I look for the slowest nodes, sequential scans on large tables, and big differences between estimated and actual row counts, which suggest outdated statistics.

  3. Adding BUFFERS shows I/O.

16. What are materialized views?

Answer flow · 3 steps
  1. A materialized view stores the result of a query physically, so expensive aggregations for dashboards and reports are read instantly.

  2. The data does not update automatically; REFRESH MATERIALIZED VIEW recalculates it, and adding CONCURRENTLY (which requires a unique index) refreshes without blocking readers.

  3. Refreshes are usually scheduled or triggered after data loads.

17. How does full-text search work in PostgreSQL?

Text is converted into a tsvector of normalised words (lexemes) using a language configuration, and searches use a tsquery, matched with the @@ operator, such as to_tsvector('english', body) @@ websearch_to_tsquery('english', 'fast cars'). A GIN index on the tsvector, often in a generated column, makes it fast, and ts_rank orders results by relevance. pg_trgm helps with fuzzy and partial matching.

18. Which isolation levels does PostgreSQL support?

Answer flow · 4 steps
  1. The default is Read Committed, where each statement sees data committed before it began.

  2. Repeatable Read gives the whole transaction one snapshot.

  3. Serializable uses Serializable Snapshot Isolation, which detects conflicts and aborts one transaction with a serialization failure, so the application must retry.

  4. Read Uncommitted behaves like Read Committed in PostgreSQL.

19. What are row locks and advisory locks?

SELECT ... FOR UPDATE locks selected rows until the transaction ends, so other transactions cannot change them; FOR UPDATE SKIP LOCKED lets several workers take different rows from a jobs table without blocking each other. Advisory locks are application-defined locks on a number, such as pg_advisory_lock(42), used to make sure only one process runs a job or migration at a time.

20. Which PostgreSQL extensions have you used?

pg_stat_statements to find the most expensive queries, PostGIS for geospatial data, pgvector for storing and searching AI embeddings, pg_trgm for fuzzy text search, pgcrypto for hashing and encryption functions, uuid-ossp (now mostly replaced by the built-in gen_random_uuid()), hstore, and TimescaleDB or pg_partman for time-series data and partitions.

21. How do functions and triggers work in PostgreSQL?

Answer flow · 4 steps
  1. Functions can be written in SQL or PL/pgSQL, which adds variables, conditions, loops and error handling, and are called in queries.

  2. Procedures (CALL) can manage transactions.

  3. A trigger calls a trigger function before or after INSERT, UPDATE or DELETE, for example to update an updated_at column or write an audit record.

  4. Logic in triggers should stay small and well documented.

22. What is a LATERAL join?

Answer flow · 3 steps
  1. A LATERAL subquery can refer to columns from tables earlier in the FROM clause, so it runs for each row, like a for-each loop.

  2. A classic use is fetching the latest three orders for every customer: FROM customers c CROSS JOIN LATERAL (SELECT * FROM orders o WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 3) recent.

  3. It is also used with set-returning functions.

High level PostgreSQL interview questions

System design, deep internals, leadership and tough follow-ups.

23. How does table partitioning work in PostgreSQL?

Answer flow · 3 steps
  1. Declarative partitioning splits a large table into smaller partitions by range (for example by month), list (by region) or hash.

  2. Queries that filter on the partition key only scan the relevant partitions (partition pruning), and old data can be dropped instantly by detaching a partition.

  3. It suits very large time-series or log tables.

24. How does replication and high availability work in PostgreSQL?

Answer flow · 4 steps
  1. Streaming replication sends the write-ahead log (WAL) from the primary to standby servers, which can serve read queries (hot standby).

  2. It can be asynchronous or synchronous.

  3. Logical replication replicates selected tables and allows different versions, useful for upgrades.

  4. Tools such as Patroni manage automatic failover, and PgBouncer handles connection pooling.

25. What are common causes of PostgreSQL performance problems?

Missing or unused indexes, table bloat from poorly tuned autovacuum, outdated statistics, too many connections without a pooler like PgBouncer, long-running transactions that block vacuum and hold locks, N+1 queries from the application, and settings such as shared_buffers, work_mem and effective_cache_size left at defaults. pg_stat_statements helps find the most expensive queries.

26. Why use PgBouncer, and what are its pooling modes?

Answer flow · 4 steps
  1. Each PostgreSQL connection is a separate process using memory, so thousands of application connections overload the server.

  2. PgBouncer keeps a small pool of real connections and shares them.

  3. Session mode assigns a server connection for the whole client session, transaction mode (the most common) assigns one only for each transaction, and statement mode per statement.

  4. Transaction mode limits session-level features such as session variables.

27. How do WAL, backups and point-in-time recovery work?

Every change is first written to the write-ahead log (WAL), which makes crash recovery possible and powers replication. pg_dump creates logical backups of a database, good for smaller databases and migrations. Physical backups with pg_basebackup or tools such as pgBackRest, combined with archived WAL files, allow point-in-time recovery to any moment, for example just before an accidental DELETE.

28. How do you upgrade PostgreSQL to a new major version?

Answer flow · 3 steps
  1. Major versions change the storage format, so you cannot simply replace the binaries. pg_upgrade upgrades in place quickly, especially with --link, but needs downtime. pg_dump and restore is simple but slow for large databases.

  2. Logical replication from the old to the new version allows near-zero downtime: replicate, test, then switch applications over.

  3. Always test extensions and queries on the new version first.

29. How do you use PostgreSQL for AI vector search?

Answer flow · 3 steps
  1. The pgvector extension adds a vector column type for embeddings created by AI models, and distance operators such as <=> for cosine distance to find the most similar items, for example for semantic search or retrieval-augmented generation.

  2. HNSW or IVFFlat indexes make approximate nearest-neighbour search fast.

  3. Combining it with normal SQL filters and full-text search in one database is a major advantage.

30. How do you run schema migrations safely on a busy PostgreSQL database?

Answer flow · 3 steps
  1. Create indexes with CREATE INDEX CONCURRENTLY so writes are not blocked.

  2. Adding a column with a constant default is instant in modern versions, but adding NOT NULL or changing types can rewrite or lock the table, so add constraints as NOT VALID and validate them separately.

  3. Set lock_timeout so a migration fails fast instead of queueing behind long transactions and blocking everything, and keep changes backward compatible.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a database engineer interview?

See all Database Engineer interview questions, covering SQL, MySQL, PostgreSQL, Oracle, SQL Server and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields