VIDHAIX / DATA & DEVOPS / INTERVIEW PREP

Top 43 SQL Interview Questions & Answers (2026)

Joins, window functions, indexing, transactions and PostgreSQL production scenarios asked in 2026.

43 questions with answersUpdated 22 October 2026Reviewed by VidhaiX trainers

This page is for freshers, backend and full-stack developers, testers who write data checks, and engineers with a few years of experience preparing for SQL rounds. Examples use PostgreSQL, the default choice at most Indian startups and product companies today, and we call out MySQL differences where they trip people up in interviews.

Service companies still open with joins, GROUP BY and the Nth highest salary. Product companies and startups go further: they want you to read an EXPLAIN ANALYZE plan, choose the right index, explain why two transactions deadlocked, and paginate a large table without killing the database. The questions are grouped into freshers, intermediate, experienced (3+ years) and scenario-based rounds. VidhaiX trainers compiled them from the mock interviews we run, and each answer notes what a strong candidate says and where weak answers usually stop.

How to Prepare for a SQL Interview

  • Install PostgreSQL 17 or 18 locally or in Docker, load a sample dataset with a few million rows, and practise every query here against real data instead of reading answers.
  • Write the classic queries from memory without help: Nth highest salary, delete duplicates, running totals, top N per group and employees earning more than their manager.
  • Run EXPLAIN (ANALYZE, BUFFERS) on slow queries, add and drop indexes, and learn to explain Seq Scan, Index Scan, Bitmap Heap Scan, Hash Join and Nested Loop in plain words.
  • Open two psql sessions side by side and reproduce a lost update, a deadlock and a serialization failure so you can describe isolation levels from experience, not definitions.
  • Be ready to sketch a schema for a familiar domain such as orders, bookings or a learning platform, with keys, constraints and indexes, and justify every denormalization you choose.
  • Revise NULL behaviour carefully: NOT IN with NULLs, COUNT(*) versus COUNT(column), NULL in UNIQUE constraints and ordering. Interviewers use these as quick filters.
  • Prepare one real story about a slow query, migration or data bug you fixed, including how you measured it before and after. Experienced rounds almost always ask for one.

SQL Interview Questions for Freshers

12 questions

Q1.Explain the different types of joins with an example of when you would use each.

INNER JOIN returns rows that match in both tables, such as orders with their customers. LEFT JOIN keeps every row from the left table and fills NULLs where nothing matches, which is how you find customers with no orders. RIGHT JOIN is the mirror image and is rarely used. FULL OUTER JOIN keeps unmatched rows from both sides, useful when reconciling two data sources. CROSS JOIN produces every combination.

A strong answer also mentions self joins (employee to manager) and the classic trap: a filter on the right table placed in WHERE silently turns a LEFT JOIN into an inner join. Note that MySQL has no FULL OUTER JOIN.

Q2.What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping, so it cannot reference aggregates. HAVING filters groups after GROUP BY and aggregation, so it can use COUNT(*) or SUM(amount). Logically the order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.

Interviewers like to hear the performance point: put every condition that does not need an aggregate in WHERE, because it reduces the rows the database has to group. Writing HAVING city = 'Chennai' works but filters late.

sql
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) > 10000;

Q3.How does GROUP BY work, and why does selecting a non-grouped column fail?

GROUP BY collapses rows that share the same values in the grouping columns into one output row, and aggregates compute a value per group. Any column in the SELECT list must be either grouped or wrapped in an aggregate, otherwise the database cannot know which of many values to return.

PostgreSQL relaxes this when you group by a primary key, because other columns of that table are functionally dependent on it. Older MySQL versions without ONLY_FULL_GROUP_BY returned an arbitrary value, which is a real source of bugs in legacy code.

Q4.How does NULL behave in comparisons, aggregates and NOT IN?

NULL means unknown, so NULL = NULL is not true but unknown, and rows where a condition is unknown are filtered out. Use IS NULL, IS NOT NULL or IS DISTINCT FROM. COUNT(*) counts rows while COUNT(col) skips NULLs, and SUM/AVG ignore NULLs too.

The trap interviewers look for: WHERE id NOT IN (SELECT manager_id FROM employees) returns zero rows if any manager_id is NULL. Use NOT EXISTS instead. Also mention COALESCE for defaults and that PostgreSQL sorts NULLs last in ascending order by default.

Q5.What is the difference between DELETE, TRUNCATE and DROP?

DELETE removes selected rows, supports WHERE, fires row triggers and is fully logged. TRUNCATE empties the whole table quickly by discarding its storage, does not scan rows and can reset identity sequences with RESTART IDENTITY. DROP removes the table definition itself along with data, indexes and constraints.

A common wrong claim is that TRUNCATE cannot be rolled back. In PostgreSQL it is transactional; in MySQL it causes an implicit commit. TRUNCATE also takes an exclusive lock and fails on tables referenced by foreign keys unless you use CASCADE.

Q6.What are primary keys, foreign keys, unique and check constraints used for?

A primary key uniquely identifies each row and cannot be NULL. A foreign key enforces that a referenced row exists, with actions such as ON DELETE CASCADE or RESTRICT. UNIQUE prevents duplicates but allows NULLs (multiple, unless PostgreSQL 15+ NULLS NOT DISTINCT is used). CHECK validates a row-level rule such as price >= 0, and NOT NULL is the simplest constraint of all.

Strong candidates say constraints belong in the database, not only in application code, because data gets written by scripts, admin tools and other services. Mention that PostgreSQL does not auto-index foreign key columns.

Q7.What is normalization, and when would you deliberately denormalize?

Normalization organises tables so each fact is stored once. 1NF means atomic values with no repeating groups, 2NF removes partial dependency on part of a composite key, and 3NF removes transitive dependency, such as storing a city name derived from a pincode. The payoff is no update anomalies and smaller writes.

Denormalization trades that for read speed: storing an order_total or a cached comment_count, or building a reporting table. A good answer says you denormalize after measuring, and you own the consistency cost through triggers, transactions or background jobs.

Q8.What is the difference between UNION and UNION ALL?

UNION combines result sets and removes duplicate rows, which requires a sort or hash step. UNION ALL simply appends results and is faster. Both need the same number of columns with compatible types, and column names come from the first query.

Interviewers want you to default to UNION ALL unless you genuinely need de-duplication, because people use UNION out of habit and pay for an expensive sort on large data. Related set operators are INTERSECT and EXCEPT; MySQL only added them in 8.0.31.

Q9.How would you find the second or Nth highest salary?

The cleanest approach uses DENSE_RANK(), which handles ties correctly so two people sharing the top salary do not hide the second highest value. ORDER BY salary DESC OFFSET n-1 LIMIT 1 on DISTINCT salaries also works for a single value.

Weak answers use MAX(salary) WHERE salary < (SELECT MAX(salary)...), which does not generalise to N. Also handle the edge case where fewer than N distinct salaries exist: your query should return no row or NULL, not crash. Mention per-department variants with PARTITION BY.

sql
SELECT DISTINCT salary
FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) ranked
WHERE rnk = 3;

Q10.What is an index, and why not index every column?

An index is a separate data structure, usually a B-tree, that lets the database find rows by a key without scanning the whole table, much like a book index. It speeds up lookups, joins, sorting and uniqueness checks.

Every index costs disk space and slows down inserts, updates and deletes because each one must be maintained, and it adds vacuum work. Indexes on low-selectivity columns such as a boolean are often ignored by the planner. A good answer says you add indexes based on real query patterns and verify them with EXPLAIN.

Q11.What does ACID mean for a transaction?

Atomicity: all statements in the transaction succeed or none do. Consistency: the database moves from one valid state to another, with constraints enforced. Isolation: concurrent transactions do not see each other's intermediate work, to a degree set by the isolation level. Durability: once committed, data survives a crash, which PostgreSQL guarantees through the write-ahead log.

Use a concrete example such as a bank transfer debiting one account and crediting another. Strong candidates add that isolation is not absolute by default, which leads into isolation levels and anomalies.

Q12.What is the difference between CHAR, VARCHAR and TEXT in PostgreSQL?

CHAR(n) pads values with spaces to a fixed length, VARCHAR(n) enforces a maximum length, and TEXT has no limit. In PostgreSQL all three use the same underlying storage, so TEXT is not slower, and CHAR(n) is usually a mistake because of padding surprises in comparisons.

Many teams use TEXT with a CHECK (length(name) <= 100) constraint, which is easier to change than altering a column type. In MySQL the choice matters more, since TEXT columns have indexing and in-memory temp table limitations that VARCHAR does not.

SQL Intermediate Interview Questions

12 questions

Q13.When would you use a subquery, a CTE or a join, and does the choice affect performance?

A correlated subquery runs conceptually per outer row and suits EXISTS checks. A join is natural when you need columns from both tables. A CTE with WITH names an intermediate result, making multi-step logic readable and allowing recursion.

On performance, the answer is version-specific. Since PostgreSQL 12, non-recursive CTEs referenced once are inlined, so they optimise like subqueries. Before that they were optimisation fences. You can still force either behaviour with MATERIALIZED or NOT MATERIALIZED. Interviewers want you to check the plan rather than assume.

Q14.How does a recursive CTE work? Write one for an org chart.

A recursive CTE has an anchor query that produces the starting rows and a recursive part, joined with UNION ALL, that references the CTE itself. PostgreSQL repeats the recursive part on the newly produced rows until it returns nothing.

Typical uses are org charts, category trees, bill of materials and graph walks. A strong answer mentions cycle protection, either with a depth limit, a visited path array or the CYCLE clause available since PostgreSQL 14, because bad data with a loop otherwise runs forever.

sql
WITH RECURSIVE reports AS (
  SELECT id, name, manager_id, 1 AS depth
  FROM employees WHERE id = 42
  UNION ALL
  SELECT e.id, e.name, e.manager_id, r.depth + 1
  FROM employees e
  JOIN reports r ON e.manager_id = r.id
  WHERE r.depth < 10
)
SELECT * FROM reports;

Q15.Explain ROW_NUMBER, RANK and DENSE_RANK with ties.

All three are window functions that number rows within a partition by an order. For salaries 100, 90, 90, 80: ROW_NUMBER gives 1, 2, 3, 4 with ties broken arbitrarily, RANK gives 1, 2, 2, 4 leaving a gap, and DENSE_RANK gives 1, 2, 2, 3 without gaps.

Pick ROW_NUMBER when you need exactly one row per group, such as the latest order per customer, and add a tiebreaker column to the ORDER BY so results are deterministic. Pick DENSE_RANK for "Nth highest" questions. Window functions do not collapse rows, unlike GROUP BY.

Q16.How do you calculate a running total and month-over-month change in SQL?

Use window functions. SUM(amount) OVER (ORDER BY month) gives a running total, and LAG(amount) OVER (ORDER BY month) fetches the previous row so you can compute the difference or percentage change. LEAD looks forward.

The subtle point: with ORDER BY and no frame clause, the default frame is RANGE UNBOUNDED PRECEDING, which treats rows with equal sort keys as peers and adds them together. Specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when you want strict row-by-row behaviour. Also guard against division by zero with NULLIF.

sql
SELECT month, revenue,
  SUM(revenue) OVER (ORDER BY month
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
  revenue - LAG(revenue) OVER (ORDER BY month) AS change,
  ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
    / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS pct
FROM monthly_revenue;

Q17.How would you find and delete duplicate rows while keeping one copy?

First define what a duplicate is, usually a set of business columns such as email, not every column. Then number rows within each duplicate group with ROW_NUMBER() and delete everything except the first, choosing which row survives with an explicit order such as the oldest id.

In production, run the SELECT first, count the affected rows, do it in a transaction and batch it on large tables. Finish by adding a UNIQUE constraint so duplicates cannot come back; otherwise you will be running the same cleanup next quarter.

sql
DELETE FROM users
WHERE id IN (
  SELECT id FROM (
    SELECT id, ROW_NUMBER() OVER (
      PARTITION BY lower(email) ORDER BY id) AS rn
    FROM users
  ) d WHERE rn > 1
);

Q18.How does column order matter in a composite index?

A B-tree on (customer_id, created_at) is sorted by customer_id first and then by created_at within each customer. It serves queries filtering on customer_id alone, or on both, and can return rows already sorted by created_at for one customer. A filter on created_at alone generally cannot use it efficiently.

The rule of thumb is equality columns first, then range or sort columns. Selectivity matters less than query shape. PostgreSQL 18 added skip scan for some leading-column cases, but you should still design indexes around the queries you actually run.

Q19.What are covering indexes and index-only scans?

An index-only scan answers a query entirely from the index without visiting the table heap, which is much faster for hot queries. It requires every referenced column to be in the index. PostgreSQL lets you add non-key payload columns with INCLUDE, so the key stays small while the index still covers the query.

The catch candidates often miss: PostgreSQL must check the visibility map, so on a table with many recently modified pages it still visits the heap. Watch Heap Fetches in EXPLAIN ANALYZE, and make sure autovacuum keeps up.

sql
CREATE INDEX orders_customer_created_idx
  ON orders (customer_id, created_at DESC)
  INCLUDE (status, amount);

Q20.How do you read an EXPLAIN ANALYZE plan?

EXPLAIN shows the planned tree; EXPLAIN ANALYZE actually runs the query and adds real time and row counts. Read it bottom-up and inside-out. For each node, compare estimated rows with actual rows: a large mismatch usually means stale statistics or correlated columns, and leads the planner to the wrong join method.

Add BUFFERS to see how much data came from cache versus disk. Look for sequential scans on large tables, nested loops with huge outer counts, sorts spilling to disk and high Rows Removed by Filter. Remember that ANALYZE executes writes too, so wrap DML in a transaction and roll back.

Q21.What is an upsert, and how does ON CONFLICT work in PostgreSQL?

INSERT ... ON CONFLICT inserts a row or, if a unique constraint is violated, either does nothing or updates the existing row atomically. The EXCLUDED pseudo-table holds the values you tried to insert. It needs a unique index or constraint matching the conflict target.

Strong answers compare it with the racy "select then insert" pattern, which breaks under concurrency. MySQL uses INSERT ... ON DUPLICATE KEY UPDATE instead. PostgreSQL also has MERGE since version 15, useful for more complex sync logic, though ON CONFLICT is still the simplest safe upsert.

sql
INSERT INTO product_stock (sku, qty)
VALUES ('VX-101', 5)
ON CONFLICT (sku)
DO UPDATE SET qty = product_stock.qty + EXCLUDED.qty,
              updated_at = now();

Q22.When would you use JSONB columns, and how do you index them?

JSONB stores parsed binary JSON, supports operators like ->>, @> and ?, and suits genuinely variable data such as webhook payloads, user preferences or product attributes that differ per category. JSON keeps the raw text and is rarely the better choice.

Index containment queries with a GIN index, using jsonb_path_ops when you only need @>, or create a B-tree expression index on a single extracted key you filter often. The trap is putting core relational fields inside JSONB: you lose constraints, types, foreign keys and good planner statistics.

Q23.Why is OFFSET pagination slow on large tables, and what is keyset pagination?

OFFSET 100000 LIMIT 20 still reads and discards 100,000 rows, so deep pages get slower. It also skips or repeats rows when data changes between page loads.

Keyset (seek) pagination remembers the last row's sort key and asks for rows after it, which an index on (created_at, id) serves directly no matter how deep you go. The id tiebreaker keeps ordering unique. The trade-off is no random jumps to page 50, which most infinite-scroll and API cursors do not need anyway.

sql
SELECT id, title, created_at
FROM posts
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;

Q24.What is the N+1 query problem, and how do you fix it?

N+1 happens when code fetches a list with one query and then runs one more query per item, for example loading 50 orders and then each customer separately. Each query is fast, but 51 round trips add up, and ORMs hide it behind lazy-loaded properties.

Fix it with a join, a single WHERE id = ANY($1) batch query, ORM eager loading such as Prisma include or Django select_related, or a DataLoader in GraphQL. Detect it with query logging, pg_stat_statements call counts or APM traces showing repeated identical statements per request.

SQL Interview Questions for Experienced (3+ Years)

11 questions

Q25.Explain the isolation levels and the anomalies each one prevents in PostgreSQL.

The SQL standard defines dirty reads, non-repeatable reads, phantoms and serialization anomalies. PostgreSQL never allows dirty reads, so READ UNCOMMITTED behaves like READ COMMITTED, the default, where each statement sees a fresh snapshot. REPEATABLE READ uses one snapshot for the whole transaction and also prevents phantoms in PostgreSQL. SERIALIZABLE uses SSI to detect write skew and aborts one transaction.

The key point: stronger levels raise serialization errors (SQLSTATE 40001) that the application must retry. MySQL InnoDB defaults to REPEATABLE READ with gap locking, so behaviour differs between the two engines.

Q26.How does MVCC work in PostgreSQL, and why does VACUUM exist?

PostgreSQL never updates a row in place. An UPDATE writes a new tuple version and marks the old one with the transaction ID that replaced it, so readers keep seeing the version valid for their snapshot without blocking writers. Readers and writers do not block each other.

The cost is dead tuples. VACUUM reclaims them for reuse, updates the visibility map for index-only scans and freezes old transaction IDs to prevent wraparound. Autovacuum does this automatically, but long-running transactions or idle-in-transaction sessions pin old snapshots and stop cleanup, causing bloat. VACUUM FULL rewrites the table under an exclusive lock.

Q27.What causes deadlocks, and how do you prevent them?

A deadlock happens when transaction A holds a lock B needs while B holds a lock A needs. PostgreSQL detects the cycle after deadlock_timeout and aborts one transaction with an error. Typical causes are updating the same rows in different orders, or foreign key checks taking share locks on parent rows.

Prevention: lock rows in a consistent order (for example ORDER BY id with FOR UPDATE), keep transactions short, avoid user interaction or HTTP calls inside them, and retry on deadlock errors. Turn on log_lock_waits and read the server log, which records both conflicting statements.

Q28.How would you build a job queue on PostgreSQL using SELECT FOR UPDATE SKIP LOCKED?

FOR UPDATE locks the selected rows, and SKIP LOCKED makes other workers skip rows already locked instead of waiting. Multiple workers can therefore each claim a different pending job safely, without a separate broker.

Claim and mark the job in one statement, commit, then process, or process inside the transaction if jobs are short. Add a partial index on pending jobs, a locked_at timeout for crashed workers, and retries with attempt counts. Mention that libraries like pg-boss and Solid Queue use this pattern, and that very high throughput may still justify a dedicated queue.

sql
UPDATE jobs SET status = 'running', locked_at = now()
WHERE id = (
  SELECT id FROM jobs
  WHERE status = 'pending'
  ORDER BY run_at
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING id, payload;

Q29.Compare B-tree, GIN, GiST, BRIN and partial indexes. When do you use each?

B-tree is the default for equality, ranges and sorting. GIN indexes values containing many elements: JSONB, arrays and full-text tsvector. GiST suits geometric data, ranges and exclusion constraints, such as preventing overlapping bookings. BRIN stores min/max per block range and is tiny, ideal for huge append-only tables ordered by time.

A partial index covers only rows matching a predicate, for example WHERE status = 'pending' or WHERE deleted_at IS NULL, keeping it small and hot in memory. A partial unique index can enforce rules like one active subscription per user. The query must match the predicate for the planner to use it.

sql
CREATE UNIQUE INDEX one_active_sub_per_user
  ON subscriptions (user_id)
  WHERE status = 'active';

Q30.How do you add an index or change a column on a large production table without downtime?

Use CREATE INDEX CONCURRENTLY, which avoids blocking writes but cannot run inside a transaction and can leave an invalid index if it fails, so check and drop it. For new constraints, add them NOT VALID and then VALIDATE CONSTRAINT separately, which takes a weaker lock.

Set a short lock_timeout so a migration waiting behind a long query does not queue every other request behind it. Column type changes that rewrite the table need an expand and contract approach: add a new column, backfill in batches, switch reads, then drop the old one.

Q31.When would you partition a table, and what are the trade-offs?

Declarative partitioning splits one logical table into child tables by range (usually time), list or hash. It pays off when tables grow to hundreds of millions of rows and queries filter on the partition key, so the planner prunes irrelevant partitions, or when you need to drop old data instantly by detaching a partition instead of a massive DELETE.

Trade-offs: primary and unique keys must include the partition key, queries that do not filter by it touch every partition, and too many partitions slow planning. Tools like pg_partman automate creating future partitions. Partitioning is not a substitute for proper indexing.

Q32.Explain streaming and logical replication, and what replication lag means for the application.

Streaming (physical) replication ships WAL to standbys that are byte-for-byte copies, used for high availability and read replicas. Logical replication publishes row changes for selected tables, enabling cross-version upgrades, partial copies and feeding other systems.

Replicas are usually asynchronous, so a user who writes and then reads from a replica may not see their own change. Strong answers discuss read-your-writes routing to the primary after a write, synchronous replication costs, monitoring lag through pg_stat_replication, and that failover tools such as Patroni or managed services handle promotion.

Q33.How do you find the slowest queries in a production PostgreSQL database?

Enable the pg_stat_statements extension and sort by total_exec_time, not just mean time, because a 5 ms query called a million times can cost more than a 3 second report. Check calls, rows and shared block reads too.

Then use auto_explain or log_min_duration_statement to capture actual plans for slow executions, pg_stat_activity for queries running right now and lock waits, and pg_stat_user_tables for sequential scan counts and dead tuples. A senior answer ties fixes to measurement: reset stats, deploy the change, compare.

sql
SELECT calls, round(total_exec_time) AS total_ms,
       round(mean_exec_time, 1) AS mean_ms, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Q34.How do you prevent SQL injection, and what cannot be parameterized?

Never build SQL by concatenating user input. Use parameterized queries or prepared statements, where values travel separately from the SQL text, through drivers like node-postgres with $1 placeholders or ORMs. Escaping by hand is fragile.

Identifiers and keywords, such as a sort column or direction, cannot be bound as parameters. Map them against an allow-list in code, or quote them with format('%I') inside PL/pgSQL. Defence in depth: the app user should not own the schema, should have least privilege, and raw-query escape hatches in ORMs deserve code review attention.

Q35.How do you handle connection limits and pooling with PostgreSQL?

Each PostgreSQL connection is a separate backend process using memory, so thousands of direct connections from autoscaled app servers or serverless functions degrade performance long before max_connections is hit.

Use an application-side pool sized sensibly (often a small multiple of CPU cores at the database) and a server-side pooler such as PgBouncer in transaction mode. Transaction pooling breaks session features like SET, advisory session locks and, in older PgBouncer versions, named prepared statements, so code must respect that. Monitor pg_stat_activity for idle-in-transaction connections.

SQL Scenario-Based Interview Questions

8 questions

Q36.A query that ran in 50 ms last week now takes 8 seconds. How do you investigate?

First confirm it is the query and not lock waits: check pg_stat_activity for wait_event. Then run EXPLAIN (ANALYZE, BUFFERS) and compare with the old plan if auto_explain captured it. The usual culprits are a plan flip after data growth, stale statistics, a dropped or invalid index, table bloat, or a parameter value with very different selectivity.

Run ANALYZE on the table, check estimated versus actual rows, and look at dead tuples. Fix the root cause, such as better statistics with CREATE STATISTICS or a new index, rather than pinning a workaround.

Q37.Two users bought the last item in stock at the same time and both orders succeeded. How do you fix it?

This is a lost update or race: both read qty = 1, both decided to sell, and both wrote. The fix is to make the check and write atomic. A conditional update such as UPDATE stock SET qty = qty - 1 WHERE sku = $1 AND qty > 0 and checking the affected row count is the simplest.

Alternatives are SELECT ... FOR UPDATE before deciding, or SERIALIZABLE with retries. Add a CHECK (qty >= 0) constraint as a final guard. Then write a concurrency test that fires parallel requests, because this bug never appears in single-user manual testing.

Q38.Disk usage on the database keeps growing even though row counts are stable. What is happening?

Stable row counts with growing size usually means bloat from dead tuples that vacuum is not cleaning. Check n_dead_tup and last autovacuum time in pg_stat_user_tables, then look for blockers: long-running transactions, idle-in-transaction sessions, abandoned replication slots holding WAL, or old prepared transactions.

Fix the blocker first, then tune autovacuum per table for hot tables. To reclaim space already lost, VACUUM FULL locks the table, so in production teams use pg_repack. Also check for WAL accumulation and unused indexes, which grow too.

Q39.A report on a 200 million row events table times out. What options would you consider?

Start with the plan and the question being asked. Options in rough order: a targeted index or BRIN on the timestamp, rewriting the query to filter earlier, a pre-aggregated summary table or materialized view refreshed on a schedule with REFRESH MATERIALIZED VIEW CONCURRENTLY, and partitioning by month so old data is pruned.

Also run heavy reports on a read replica so they do not hurt transactional traffic. If analytics needs keep growing, a columnar store or warehouse may be the right home. Interviewers like candidates who ask how fresh the report must be before choosing.

Q40.An API endpoint fires 300 queries per request in production. How do you find and fix it?

Confirm with query logging or APM traces for that request, then look for repeated statements with different IDs, the signature of N+1, usually from an ORM lazy-loading relations inside a loop or a serializer.

Fix with eager loading, a batched WHERE id = ANY(...) query, or a join that returns everything in one or two queries. Then lock it in with a test that asserts the query count for the endpoint, so a future change to the serializer does not quietly bring it back. Measure latency before and after.

Q41.A migration added a column with a default and the whole site went down. What went wrong?

Since PostgreSQL 11, adding a column with a constant default is metadata-only, so the likely cause is the lock itself. ALTER TABLE needs an ACCESS EXCLUSIVE lock; if a long-running query holds a conflicting lock, the migration waits, and every new query on that table queues behind the waiting migration. The site appears down.

Prevent it with SET lock_timeout = '5s' and retries, running migrations at low traffic, and checking for long transactions first. Volatile defaults or type changes still rewrite the table, so those need the expand and contract approach.

Q42.Your nightly job deletes old rows with one big DELETE and it causes replication lag and lock waits. How would you redesign it?

A single huge DELETE produces a massive WAL burst that replicas struggle to apply, holds locks for long, and leaves millions of dead tuples for vacuum. Delete in batches of a few thousand rows by primary key in a loop, commit between batches, and pause briefly if lag rises.

Better still, if the table is time-based, partition it by day or month and drop or detach old partitions, which is nearly instant and leaves no bloat. Make sure the deletion predicate is indexed, and monitor replica lag while the job runs.

sql
DELETE FROM audit_logs
WHERE id IN (
  SELECT id FROM audit_logs
  WHERE created_at < now() - interval '90 days'
  LIMIT 5000
);

Q43.Production shows intermittent "could not serialize access" and deadlock errors after a release. What do you do?

These are expected concurrency outcomes, not database bugs, so first check whether the application retries them. Serialization failures (40001) and deadlocks (40P01) should be retried with backoff by wrapping the whole transaction, not just the failed statement.

Then reduce frequency: read the server log for the conflicting statements, find what the release changed, and look for inconsistent lock ordering, longer transactions or new hot rows such as a shared counter. Fixes include ordering updates by id, moving external calls outside transactions and replacing hot counters with append-and-aggregate patterns.

From answers to offers

Prepare for SQL interviews with practicing engineers

If you can answer the basics but freeze on query plans, locking or schema design, this sprint has you work through those on real PostgreSQL databases with trainer review.