← All topics
Start ▶
SQL and databases
Indexes, transactions, isolation and query tuning.
200 questions
Level:
No questions match — try other words or turn a level back on.
1
What do table, row and column mean in a relational database, and where does the word "relational" come from?
A table is a collection of things of one kind (say, users), a row is one record, a column is one attribute of every record. "Relational" means tables are linked to each other through keys.
2
What is the difference between a PRIMARY KEY and a UNIQUE constraint?
Both reject duplicate values. But a table has only one PRIMARY KEY and it can't be NULL, while a table can have several UNIQUE constraints, and PostgreSQL doesn't treat NULLs as duplicates.
3
Why do we need a FOREIGN KEY, and what does ON DELETE CASCADE do?
A FOREIGN KEY guarantees, at the database level, that a value in one table really exists in another. ON DELETE CASCADE automatically deletes the dependent rows when the parent row is deleted.
4
How do the results of INNER JOIN and LEFT JOIN differ?
INNER JOIN returns only the rows that found a match in both tables. LEFT JOIN returns every row from the left table, and if there is no match on the right, those columns are NULL.
5
Explain the difference between WHERE and HAVING.
WHERE filters individual rows before grouping, while HAVING filters the finished groups after GROUP BY. That's why a condition on an aggregate function (COUNT, SUM) can only go in HAVING.
6
Which columns can you put in the SELECT list when you use GROUP BY?
Only the columns listed in GROUP BY and aggregate functions (count, sum, max...). If you list any other column, PostgreSQL raises an error, because it doesn't know which of the group's values of that column to take.
7
Why does `WHERE deleted_at = NULL` return no rows?
NULL means "unknown value", so any = or <> comparison with it yields NULL, not true. To test for NULL you write IS NULL or IS NOT NULL.
8
How do COUNT(*), COUNT(column) and COUNT(DISTINCT column) differ?
COUNT(*) counts all rows, COUNT(column) counts only the rows where that column is not NULL, and COUNT(DISTINCT column) gives the number of distinct non-NULL values.
9
How do the DELETE, TRUNCATE and DROP TABLE commands differ?
DELETE / TRUNCATE / DROP — Pick rows with WHERE: yes / no / no; Speed on a big table: slow / very fast / very fast; Triggers: ON DELETE fires / does not fire / —; Structure stays: yes / yes / no
10
What is an index and how does it speed up lookups?
An index is a separate sorted structure built from the column values (a B-tree by default in PostgreSQL) that points to where the row is. Without an index the database reads the whole table; with one it reaches the right spot in a few steps down the tree.
11
If an index speeds up lookups, why not put an index on every column?
Every index has a cost: it is updated on every INSERT, UPDATE and DELETE, takes up disk space, and competes with the table for the in-memory cache. An index that is never used only slows down writes.
12
What is a transaction, and what do the letters in ACID stand for?
A transaction is a group of operations executed as one unit: either everything is saved or nothing is. ACID is Atomicity, Consistency, Isolation, Durability: all-or-nothing execution, rules never being violated, concurrent transactions not interfering with each other, and no data loss after a commit.
13
What is autocommit mode in JDBC, and when do you turn it off?
With autocommit on, every SQL statement is its own transaction and is committed immediately. When several statements must succeed or fail together, you turn autocommit off and call commit or rollback yourself.
14
How does SQL injection happen, and how does PreparedStatement protect against it?
If user input is concatenated directly into the SQL string, it becomes part of the SQL code and changes the query's logic. With PreparedStatement the query and the values are sent separately, so a value is never executed as code.
15
How do UNION and UNION ALL differ in result and in speed?
UNION combines the results of two queries and removes duplicate rows, while UNION ALL appends everything as is. UNION ALL is faster because it doesn't need to sort or hash to look for duplicates.
16
You can write one task with either a subquery or a JOIN. How do you choose?
If you need columns from the other table in the result, use a JOIN. If you only need a "does it exist or not" check, an EXISTS subquery is clearer and doesn't produce duplicates. In many cases PostgreSQL turns both into the same plan, so choose by readability first.
17
How does pagination with LIMIT and OFFSET work, and why does it get slow when OFFSET is large?
LIMIT 20 OFFSET 40 skips 40 rows of the ordered result and takes the next 20. But the database still has to find and read those 40 skipped rows, so with OFFSET 1,000,000 it reads a million rows for nothing.
18
What is normalization, and what does the first normal form (1NF) require?
Normalization means splitting data across tables so that nothing is duplicated and no contradictions can appear. 1NF: every cell holds one atomic value, with no lists or repeating columns (phone1, phone2).
19
Explain the second and third normal forms (2NF, 3NF) with a simple example.
2NF: when the key is composite, every column must depend on the whole key, not just part of it. 3NF: a non-key column must not depend on another non-key column, that is, everything depends on "the key, the whole key and nothing but the key".
20
Which should you choose in PostgreSQL: `char(n)`, `varchar(n)` or `text`?
In PostgreSQL text and varchar are stored the same way internally and perform the same. varchar(n) only adds a length limit. char(n) pads the value with spaces and is almost never what you want.
21
What is the difference between `timestamp` and `timestamptz`, and which Java types match them?
timestamp stores a "wall clock" time with no time zone, while timestamptz stores an exact instant (internally in UTC) and displays it according to the session time zone. In Java, LocalDateTime matches the first, and OffsetDateTime or Instant the second.
22
How do `serial` and `GENERATED AS IDENTITY` columns differ in PostgreSQL?
Both hand out automatic numbers using a sequence underneath. serial is the old PostgreSQL-specific shorthand; IDENTITY is the SQL standard and causes fewer problems with permissions and sequence management. IDENTITY is recommended for new tables.
23
Which type should you use to store money amounts in the database, and why is `double` a bad idea?
For money use numeric(p, s) (for example numeric(15,2)) or an integer in the smallest unit (bigint in cents). double precision is a binary fraction, so it can't store numbers like 0.1 exactly, and rounding errors add up.
24
What does the `EXPLAIN` command show, and how is it different from `EXPLAIN ANALYZE`?
EXPLAIN shows the plan the planner chose and its estimated cost without running the query. EXPLAIN ANALYZE actually runs the query and adds the real time of each step and the number of rows returned.
25
If you see `Seq Scan` in `EXPLAIN` output, is that always bad?
No. On a small table, or when the query returns a large part of the table, Seq Scan is the cheapest path. The problem is only when a Seq Scan runs even though you need a few rows from a big table: that means there is no index, or it can't be used.
26
What is a VIEW, and does it store data separately?
A VIEW is a named, saved SELECT query. A regular VIEW stores no data: every time you query it, the query inside runs. The variant that stores the result is a MATERIALIZED VIEW.
27
Why do we need a connection pool, and what happens if we open a new connection on every request?
Opening a new database connection is expensive: TCP, authentication, and in PostgreSQL a separate backend process per connection. A pool keeps ready connections and hands them out again and again, so a request gets a connection in microseconds instead of milliseconds, and the database doesn't choke on the number of connections.
28
What is Flyway, and how are migration files named?
Flyway is a tool that manages the database structure through versioned SQL files. Files are named V<version>__<description>.sql, and when the application starts, the ones not yet applied run in order.
29
What happens if you edit a Flyway migration file that has already been applied on prod?
Flyway stores a checksum of every applied file. If the file changes, the application won't start on the next launch because of a validate error. The right way is to leave the old file alone and add the fix as a new versioned migration.
30
Why do we need NOT NULL and CHECK constraints, isn't it enough to do these checks in Java code?
NOT NULL guarantees a column isn't left empty, and CHECK guarantees a value follows a rule (for example price > 0), both at the database level. Validation in Java is needed, but people write to the database by other routes too (scripts, another service, hand-written SQL), and only a constraint catches those.
31
There is an index on the `email` column, but `WHERE email LIKE '%@gmail.com'` is slow. Why?
A B-tree index stores values sorted from the beginning, so it only helps when you search by a known prefix (LIKE 'ali%'). If the pattern starts with %, it doesn't know where to start and the whole table is read.
32
What does `SELECT DISTINCT` do, and how is it different from GROUP BY?
DISTINCT collapses completely identical rows in the result into one. GROUP BY also groups, but lets you compute an aggregate (count, sum) for each group. Written without an aggregate, the two often give the same result and the same plan.
33
Where is the `CASE` expression used in SQL? Give an example.
CASE is if/else inside SQL: it returns a different value for each row depending on a condition. You can use it in SELECT to compute a column, in ORDER BY for a custom sort order, and inside an aggregate for conditional counting.
34
How do aggregate functions like `SUM` and `AVG` treat NULL values?
Aggregates simply skip NULL values. So AVG is computed only over the non-NULL ones, and if there are no rows at all, or all of them are NULL, SUM returns NULL, not 0.
35
How are one-to-many and many-to-many relationships modeled in tables?
In one-to-many, the table on the "many" side gets an FK column holding the key of the "one" side. For many-to-many you create a separate junction table that stores the keys of both tables.
36
There is one composite index on the columns `(last_name, first_name)`. Will the query `WHERE first_name = 'Aziz'` use it?
Usually it won't use it efficiently. A composite B-tree is sorted by the first column, then by the second, so the index works well for conditions that start with the leftmost column(s). To search by the second column alone you need a separate index.
37
What is a self join? Show it with an employee and their manager.
A self join joins a table to itself. You need it when a row in a table refers to another row of the same table, for example an employee's manager_id column also points to another employee in the employees table.
38
Why do we need `INSERT ... ON CONFLICT` in PostgreSQL?
It's an "upsert": it tries to insert a row, and if there's a unique constraint conflict, instead of an error it either updates the existing row (DO UPDATE) or silently moves on (DO NOTHING). It all happens in one atomic statement.
39
What does the `RETURNING` clause give you in PostgreSQL?
RETURNING immediately returns the columns of the rows affected by an INSERT, UPDATE or DELETE. For example, you don't need a separate SELECT to get the newly generated id or the updated value.
40
When do you need FULL OUTER JOIN and CROSS JOIN?
FULL OUTER JOIN returns all rows from both tables and fills the side with no match with NULL, which is handy when comparing two lists. CROSS JOIN pairs every row with every other (a Cartesian product), and is used to generate combinations.
41
This query was supposed to show users with no orders too, but it doesn't. Where is the mistake?
The condition on the right table's column sits in WHERE. For rows with no matching order, o.status is NULL, NULL = 'PAID' isn't true, and those rows are dropped, so the LEFT JOIN effectively becomes an INNER JOIN. The condition has to move into ON.
42
A query that uses `NOT IN (subquery)` suddenly started returning an empty result. What could be the cause?
At least one NULL has appeared in the subquery result. x NOT IN (1, 2, NULL) is never true, because x <> NULL is unknown. So a single NULL empties the whole result. NOT EXISTS doesn't have this problem.
43
There is an index on the `email` column, but the query `WHERE lower(email) = lower(:email)` doesn't use it. Why, and how do you fix it?
The index is built on the values of email itself, and the result of lower(email) isn't in the index, so the planner can't use it. The fix is to create an expression index on exactly that expression, or to store the data already lowercased when you write it.
44
Two users decreased a product's stock at the same time and one decrement got lost. How does this happen, and how do you prevent it?
This is a "lost update": both transactions read the old value, computed in Java, and wrote their result, so the second overwrote the first's result. The fixes: an atomic UPDATE ... SET x = x - 1, SELECT ... FOR UPDATE, or optimistic locking with a version column.
45
What are dirty read, non-repeatable read and phantom read? Which ones does PostgreSQL protect against by default?
A dirty read is seeing another transaction's uncommitted change; a non-repeatable read is getting different values when you read the same row twice; a phantom is new rows appearing when you re-run the same condition. PostgreSQL's default Read Committed level protects only against dirty reads.
46
What does `SELECT ... FOR UPDATE` do, and what should you watch out for when you use it?
It locks the rows it read until the end of the transaction: other transactions can't modify them or run their own FOR UPDATE on them, so they wait. A plain SELECT isn't blocked. It's important to keep the transaction short and to lock rows in the same order.
47
After a few hours this JDBC code starts throwing "Connection is not available, request timed out". What is the problem?
When an error occurs or the ResultSet is empty, close() is never called and the connection doesn't go back to the pool: a connection leak. Over time every connection in the pool is left "hanging". The fix is try-with-resources.
48
What does the N+1 query problem look like from the database's side, and how do you solve it at the SQL level?
One query fetches N main records, then a separate query runs for each of them: N+1 in total. On the database it shows up as hundreds of small queries of the same shape that differ only in the parameter. The fix is to fetch the related data in one or two queries with a JOIN or IN (...).
49
Why is writing `SELECT *` in prod code a bad habit?
Unneeded columns still travel over the network and take memory, a covering index (Index Only Scan) stops working, and code can break unexpectedly when a column is added to the table or the column order changes. Listing the columns you need explicitly is safer.
50
What is a deadlock? Explain it with two transactions and say what PostgreSQL does about it.
A deadlock is when two transactions each wait for a resource the other has locked, so neither can move forward. PostgreSQL detects this after deadlock_timeout (1 s by default) and aborts one of the transactions with an error, and the other continues.
51
Why doesn't `created_at BETWEEN '2026-01-01' AND '2026-01-31'` show the orders from the last day of January?
If created_at is a timestamp, '2026-01-31' really means January 31 at 00:00:00, so the rest of that day falls outside the range. The right way is a half-open range: >= '2026-01-01' AND < '2026-02-01'.
52
What do `COALESCE` and `NULLIF` do? How do you use them to avoid a division by zero error?
COALESCE(a, b, c) returns the first non-NULL value, and NULLIF(a, b) returns NULL if a = b. x / NULLIF(y, 0) returns NULL instead of an error on division by zero, and you can then turn that into 0 with COALESCE.
53
How does `SUM(amount) OVER (ORDER BY day)` compute a running total, and how does that differ from GROUP BY?
A window function doesn't merge rows: each row stays in place and gets a value computed over its "window" next to it. GROUP BY squeezes a group into one row. For a running total you use a window with ORDER BY.
54
Does a query without `ORDER BY` always return rows in the same order?
No. Without ORDER BY, SQL guarantees no order at all. Today the rows may come back in insertion order, and tomorrow an UPDATE, a VACUUM or a different plan shuffles them.
55
Why do you need `SAVEPOINT` inside a transaction, and how do you "rescue" a transaction after an error in PostgreSQL?
In PostgreSQL, a single error inside a transaction puts the whole transaction into an "aborted" state, and every following query is rejected. If you set a SAVEPOINT and run ROLLBACK TO SAVEPOINT after the error, you undo only that part and can carry on.
56
You need to insert 10,000 rows through JDBC. How do separate `executeUpdate` calls, a batch, and a multi-row `INSERT` differ?
With separate inserts there is one network round trip per row, so it's the slowest. addBatch/executeBatch collects the statements and sends them together, and in PgJDBC reWriteBatchedInserts=true turns them into a multi-row INSERT, which speeds things up further.
57
How do you count orders per day, and how does the time zone affect the result on a `timestamptz` column?
You group by date_trunc('day', ...) or ::date, but for timestamptz the "day" is cut according to the session's TimeZone setting. To get the exact business day, I write AT TIME ZONE 'Asia/Tashkent'.
58
How do you write the condition "does the customer have at least one paid order?", and why is `COUNT(*) > 0` worse?
EXISTS (SELECT 1 FROM orders WHERE ...) stops as soon as it finds the first matching row. COUNT(*) > 0 counts all the matching rows, even though all we need is "yes or no".
59
How do you get an order and its line items as ready-made JSON in a single query?
In PostgreSQL, json_build_object builds one object, and json_agg collects the rows of a group into an array. Combine the two and you get "order + items array" as one row.
60
Why is sending 10,000 ids in a `WHERE id IN (...)` list a bad idea, and what do you do instead?
An IN list of a different length is a new SQL text every time: parsing and planning over and over, and the plan cache and pg_stat_statements fill up. In PostgreSQL a single array parameter, id = ANY(?), is much cleaner.
61
What is a materialized view, how does it differ from a regular VIEW, and how do you refresh it?
A regular VIEW is a saved query that runs again on every access. A materialized view stores the result on disk like a table, so it reads fast, but it goes stale and must be refreshed with REFRESH MATERIALIZED VIEW.
62
When are Seq Scan, Index Scan, Index Only Scan and Bitmap Heap Scan chosen?
If you need many rows, Seq Scan is cheap. For few rows, Index Scan. If all the needed columns are in the index and the pages are clean in the visibility map, Index Only Scan. For a medium number of rows, or when several indexes are combined, Bitmap Heap Scan.
63
How do you get the 3 most expensive products in each category with a single query?
With a window function: compute ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) and filter rn <= 3 in the outer query. If equal prices must be included too, use DENSE_RANK or RANK.
64
Is a CTE (WITH) faster or slower than a subquery?
Since PostgreSQL 12, a plain CTE is merged into the main query and optimized like a subquery, so the speed is the same. Before 12, a CTE was always computed separately and filters weren't pushed inside. Now you control this yourself with MATERIALIZED / NOT MATERIALIZED.
65
What is a `LATERAL` JOIN and when do you need it?
LATERAL lets a subquery see the columns of the tables to its left, so the subquery runs for each outer row with a "parameter". It's handy in "top-N per row" queries, like each customer's last 3 orders.
66
Duplicate rows have appeared in a table. How do you find them, and how do you keep one and delete the rest?
I find them with GROUP BY ... HAVING count(*) > 1, and to delete I mark everything except the first in each group with ROW_NUMBER() OVER (PARTITION BY ...) and run a DELETE. At the end I add a unique constraint, otherwise they'll show up again tomorrow.
67
How do you update rows based on data in another table with `UPDATE ... FROM` and `DELETE ... USING`?
In PostgreSQL, UPDATE t SET ... FROM other WHERE t.x = other.x updates by joining with another table, and DELETE ... USING does the same for deletes. The main trap: if the JOIN gives several matching rows for one target row, the result becomes unpredictable.
68
What is a partial index and when is it better than a regular one?
A partial index stores only the rows that match its WHERE condition. If queries always hit a small part of the table (say, only active or unprocessed records), the index is much smaller and faster.
69
What is a covering index, and what is INCLUDE for in PostgreSQL?
A covering index contains all the columns the query needs, so it becomes an Index Only Scan and doesn't go to the heap. INCLUDE stores extra columns only in the index leaf pages: they aren't part of the search key, but they are enough to answer the query.
70
Which isolation levels does PostgreSQL have, and what does the default READ COMMITTED actually guarantee?
Dirty read / Non-repeatable read / Phantom / Serialization anomaly — Read Committed (default): no / possible / possible / possible; Repeatable Read: no / no / not in PG / possible; Serializable: no / no / no / no
71
How do you build a job queue in the database with SELECT ... FOR UPDATE SKIP LOCKED?
Each worker takes a few free tasks with FOR UPDATE SKIP LOCKED: rows locked by another worker are skipped without waiting. As a result, workers don't block each other and no task is picked up twice.
72
How do optimistic and pessimistic locking differ, and when do you choose which?
Pessimistic locking locks the row with FOR UPDATE when you read it, and others wait. Optimistic locking takes no lock: it checks a version column at write time and raises an error on a conflict. If collisions are rare, use optimistic; if they are frequent, or waiting is cheaper, use pessimistic.
73
What does `@Transactional(readOnly = true)` actually give the database in Spring, and what doesn't it give?
In Hibernate, dirty checking and flush are switched off, which saves memory and CPU; the JDBC connection gets setReadOnly(true) and PostgreSQL makes the transaction read-only. But it doesn't speed up the query by itself and doesn't route to a replica: you have to configure that separately.
74
How do you store enum-like values such as a status in the database: the PostgreSQL `ENUM` type, `text` + `CHECK`, or a separate lookup table?
In most cases I choose text + CHECK: it's easy to read, and adding a new value is a simple migration. PostgreSQL ENUM is compact, but removing or renaming a value is awkward. A lookup table is good when a value needs extra data (a name, an order).
75
How do you connect Flyway to a prod database that is already running and was created without migrations? What does `baseline` do?
baseline tells Flyway "the database is at this version right now, don't apply the scripts before it", and adds one entry to the history table. I dump the current schema as V1__baseline.sql, set the baseline to 1 on prod, and later changes start from V2.
76
How do you choose the pool size in HikariCP, and what does the "Connection is not available, request timed out" error mean?
The pool size should be a small number close to the database's core count; a big pool doesn't make the database faster. The timeout error means a thread couldn't get a free connection within connectionTimeout: usually the cause is a slow query, a long transaction, or a leak.
77
Does PostgreSQL automatically create an index on a foreign key column, and what does that affect?
No. PostgreSQL requires an index only on the primary key or unique column in the parent table; it doesn't create an index on the FK column in the child table. Without an index, JOINs are slow, and deleting a parent row or changing its key makes a full scan of the child table.
78
What is a generated column (`GENERATED ALWAYS AS (...) STORED`) and when is it useful?
It's a column whose value is computed automatically from other columns and stored on disk. You can't write to it by hand, so even if the application forgets, the value is always right. It's handy when you need to filter and index by a computed value.
79
When do you use JSONB, and what indexes do you put on it?
JSONB is good for extra attributes whose structure varies or doesn't fit a table. For @> search over the whole document you put a GIN index, and for search on one specific field an expression B-tree index.
80
How do you find out which queries are slow on prod?
The pg_stat_statements extension collects the call count and total time for each query shape, and I start by sorting by total_exec_time. In addition, log_min_duration_statement writes slow queries to the log, and auto_explain adds their plans too.
81
How does MVCC work in PostgreSQL, and what does an UPDATE actually do on disk?
Each row version carries the IDs of the transaction that created it (xmin) and the one that deleted it (xmax). An UPDATE doesn't modify the old row in place: it sets xmax on it and writes a new version somewhere else. Each transaction decides which version it sees based on its snapshot.
82
The row count in a table hasn't changed, but its size has tripled. What is going on, and how do you fix it?
This is bloat: autovacuum isn't getting around to cleaning up the dead rows left by UPDATE/DELETE, or some long transaction is preventing the cleanup. I find the cause and tune autovacuum to be more aggressive for that table; to give the space back to the OS I'll need pg_repack.
83
A session has been sitting in "idle in transaction" for hours. How does that hurt the database?
Such a session holds an open transaction: the locks it took aren't released, and because of its snapshot VACUUM can't clean up dead rows across the whole cluster. As a result other queries wait on locks and tables bloat. You should limit it with idle_in_transaction_session_timeout.
84
How does REPEATABLE READ actually work in PostgreSQL, and how do you handle the error "could not serialize access due to concurrent update"?
Under REPEATABLE READ the snapshot is taken once, at the transaction's first query, and doesn't change until the end, so this is snapshot isolation. If another transaction has modified and committed a row you want to update after your snapshot, PostgreSQL raises error 40001 instead of waiting. The fix is to re-run the whole transaction.
85
What is write skew, and why does this code break even under REPEATABLE READ?
Write skew is when two transactions read the same data, each updates a different row, and together they violate an invariant. Because they didn't write to the same row, snapshot isolation doesn't notice the conflict. You need SERIALIZABLE or an explicit lock.
86
What is `work_mem`, how does it affect sorts and hashes, and what do you do when `external merge Disk` shows up in EXPLAIN?
work_mem is the memory a single sort or hash operation may use before spilling to disk. If it isn't enough, PostgreSQL writes to temporary files and the query slows down. Raising it globally is risky, because one query can have several such operations and many connections each take that much.
87
How do FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE differ?
These are four row-level lock modes, from strongest to weakest. FOR UPDATE prepares to delete a row or change its key, and FOR NO KEY UPDATE is for an UPDATE that doesn't touch the key. The FK check takes FOR KEY SHARE, and it blocks only a key change.
88
A small ALTER TABLE migration stopped the whole site for a few minutes. What happened, and how do you prevent it?
ALTER TABLE asks for an ACCESS EXCLUSIVE lock and waits for a long query to finish. While it waits, all the ordinary SELECTs queue up behind it, and that's how the site freezes. The protection: run the migration with lock_timeout and retry.
89
How do you add an index to a table with 200 million rows without stopping writes, and how do you write that in Flyway?
CREATE INDEX CONCURRENTLY doesn't lock writes to the table, but it can't run inside a transaction. In Flyway such a migration must be in its own file and run without a transaction. If it fails, an INVALID index is left behind, and you have to drop and recreate it.
90
The planner expected 10 rows and chose a Nested Loop, but 2 million rows actually came back. What is the cause, and what do you do?
The planner estimates the row count from statistics. If the statistics are stale, the columns are correlated, or the distribution is skewed, the estimate can be badly wrong and the wrong join type gets chosen. First ANALYZE, then raise the statistics precision or use extended statistics.
91
What is a HOT update, and how does fillfactor help it?
In a HOT (Heap-Only Tuple) update, if none of the updated columns is in any index and the page has room, the new version is written to the same page and the indexes aren't updated at all. Lowering fillfactor leaves free space on the pages and raises the share of HOT updates.
92
How does declarative partitioning work in PostgreSQL, and when does it really pay off?
The parent table is only logical, and the data lives in child tables split by a key (range, list or hash). The main benefits are instantly removing old data with DROP/DETACH, and partition pruning when a query filters on the key. If a query doesn't include the key, partitioning can even slow things down.
93
A user saved their profile, but after the page reloaded the old data showed up. Why does this happen with a read replica, and how do you fix it?
Streaming replication is usually asynchronous: after the master commits, the WAL reaches the replica a little later. If the write goes to the master and the next read lands on a replica that is still behind, the user doesn't see their own change. Reads that need read-your-writes must go to the master.
94
A long report on a replica is cut off with "canceling statement due to conflict with recovery". Why, and what are the options?
A row version that the master removed with VACUUM may still be read by a query on the replica. To apply the WAL, the replica cancels that query after max_standby_streaming_delay. The options: increase the delay, turn on hot_standby_feedback, or use a separate replica for reports.
95
What is an advisory lock, and when do you use it in a backend?
An advisory lock is a PostgreSQL lock taken on a numeric key, whose meaning the application defines itself. It isn't tied to any row. It's handy when only one of several instances should run a cron job, or to process one resource sequentially.
96
After putting PgBouncer between the application and PostgreSQL, "prepared statement S_1 does not exist" errors started. Why?
In transaction pooling mode, every transaction lands on an arbitrary server connection. The JDBC driver creates a prepared statement in one server session and then tries to use it in another. The fix: the prepared statement support in PgBouncer 1.21+, or turning off server-side prepare in the driver.
97
In psql the query takes 2 ms, but from the application the same query takes 3 seconds. Where do you start looking?
The most common causes: the application sends the parameter with a different type and the index isn't used, the prepared statement's generic plan is different, or the application session's settings differ. I take the exact query and parameters the application sent and run EXPLAIN under the same conditions.
98
Besides B-tree, when do you choose GIN, GiST and BRIN indexes?
Good for / Example — B-tree: equality, ranges, sorting / id, email, created_at; GIN: "is the element inside" / tags @> '{java}', JSONB, tsvector, pg_trgm; GiST: overlap, distance / tstzrange, PostGIS, EXCLUDE constraint; BRIN: a column correlated with physical order / created_at in an append-only log
99
You need to update or delete 30 million rows in a big table. How do you do it without taking prod down?
Instead of one huge query, I split it into small batches and run each in its own transaction. That keeps locks short, WAL and replica lag under control, and lets VACUUM work in between. I pause between batches and watch the job.
100
Even on a small table `SELECT count(*)` is slow, and `pg_stat_activity` shows the query waiting on a "Lock". How do you find out who is blocking whom?
The pg_blocking_pids(pid) function returns the processes blocking a waiting session. By joining pg_locks and pg_stat_activity, I find the session at the head of the chain, its query, and its transaction age. Often a DDL statement or a forgotten transaction sits at the head of the chain.
101
What is WAL, and why isn't committed data lost when the server suddenly goes down?
PostgreSQL first writes every change to the Write-Ahead Log, and at commit it only fsyncs the WAL to disk. The table pages are written later. After a crash, the database replays the WAL from the last checkpoint and recovers everything that was committed.
102
How does PostgreSQL use memory: how are `shared_buffers` and the OS page cache related, and how much do you set `shared_buffers` to?
shared_buffers is PostgreSQL's own page cache, shared by all processes. On top of that, files are also cached by the OS page cache, so the same data can sit in two places. The usual starting value is about 25% of RAM, leaving the rest for the OS cache.
103
What is transaction ID wraparound, and why might Postgres stop accepting writes in that situation?
Transaction IDs are 32-bit and wrap around; if old rows aren't "frozen", there's a risk they start to look like they belong to a future transaction. To prevent that, Postgres refuses new transactions when it gets close to the limit.
104
How do you detect index bloat, and when do you run `REINDEX CONCURRENTLY`?
B-tree indexes get swollen with empty space after UPDATEs/DELETEs, and VACUUM doesn't return that space to the OS. If an index is much bigger than expected, or pgstattuple shows low density, on PG12+ I rebuild it with REINDEX INDEX CONCURRENTLY without stopping writes.
105
When does an index-only scan really not touch the table, and what is the visibility map's role in that?
An index-only scan works when all the needed columns are in the index, but Postgres consults the visibility map to check row visibility. If a page isn't "all-visible", it still has to go to the table.
106
How do you find unused indexes, and is dropping them safe?
Indexes with idx_scan = 0 in pg_stat_user_indexes are candidates. But before dropping, I exclude unique/PK indexes and check how long the statistics have been collected and whether the replicas use the index. An unused index slows down every write and takes up space.
107
What kinds of queries need a GIN index, and how does it differ from a B-tree?
GIN is an "inverted index": for each element inside a value (an array element, a jsonb key, a word in text), it stores a list of rows. It suits "does it contain" queries, while a B-tree suits equality and ranges on the whole value.
108
What should the index look like for the query `ORDER BY created_at DESC LIMIT 20`, and how does `NULLS FIRST/LAST` affect it?
A B-tree can be read in both directions, so a plain (created_at) index works for DESC too. But if a multi-column order has mixed directions, or the NULLS order doesn't match the index's, the planner adds a sort and reads all the rows.
109
What do you look at first in EXPLAIN (ANALYZE, BUFFERS) output?
First I compare the estimated rows= with the actual rows: a big gap is the cause of a bad plan. Then I look at loops, the node that took the most time, the ratio of read (from disk) to hit (from cache) in Buffers, and Rows Removed by Filter.
110
When does the planner choose Nested Loop, Hash Join or Merge Join?
How it works / When it's good — Nested Loop: for each outer row, searches the inner side / tens of rows on the outer side, an index on the inner; Hash Join: builds an in-memory hash table from the smaller side, scans the larger / both sides large, only an = condition; Merge Join: walks two sorted streams in parallel /…
111
Why does the planner misestimate the row count when two columns are correlated, and how do you fix it?
By default the planner treats columns as independent and multiplies their selectivities. For correlated conditions like city='Toshkent' AND region='Toshkent' this cuts the estimate many times over; you can teach it the correlation with CREATE STATISTICS.
112
A column has an index, but the planner isn't using it. What causes do you check?
The most common causes: the column is inside a function or cast to another type, the condition returns too many rows and a seq scan is cheaper, the statistics are stale, or the LIKE pattern starts with %. I check each one with EXPLAIN.
113
Why can PostgreSQL slow down when a transaction uses many `SAVEPOINT`s (subtransactions)?
Each savepoint gets a subtransaction ID. If one backend has more than 64 open subtransactions, the snapshot can't hold them and other sessions have to check visibility through pg_subtrans. On replicas and with long transactions, this leads to a sharp slowdown.
114
When do you need to make a unique constraint `DEFERRABLE INITIALLY DEFERRED`?
By default a unique check happens immediately after every row, so an UPDATE that swaps values fails in the intermediate state. A deferred constraint postpones the check to commit: if the state is correct at the end of the transaction, everything passes.
115
When do you use triggers, and what hidden problems do they bring?
Triggers are good for simple rules that must live with the data: updating updated_at, an audit record, a denormalized counter. But if business logic goes into triggers, it's invisible from the code, hard to test, and slows down the write path.
116
When does PostgreSQL run a single query in parallel workers, and why does it sometimes not?
For queries that do a Seq Scan of a big table, a big Hash Join or an aggregation, the planner starts several workers under a Gather. But small tables, FOR UPDATE, writing queries, parallel-unsafe functions and worker limits all switch parallelism off.
117
What is Row-Level Security (RLS), and how do you use it in a multi-tenant Spring application?
RLS puts a policy on a table: for every query the database itself adds the condition tenant_id = current tenant. Even if the application forgets to write WHERE tenant_id, another tenant's data isn't visible. The current tenant is usually supplied at the start of the transaction with set_config.
118
Which commands take the table-level lock modes (`ACCESS SHARE`, `ROW EXCLUSIVE`, `SHARE`, `ACCESS EXCLUSIVE`), and which of them conflict with each other?
Every SQL command takes some lock on the table: SELECT takes the lightest, ACCESS SHARE, DML takes ROW EXCLUSIVE, and many ALTER TABLE forms and DROP take the heaviest, ACCESS EXCLUSIVE. Ordinary reads and writes don't block each other, but ACCESS EXCLUSIVE conflicts with everything.
119
What is an unlogged table, and when can you use it?
An unlogged table isn't written to the WAL, so writes are several times faster. But after a crash or an unclean shutdown it is emptied, and it never reaches the replicas. It suits temporary data you can rebuild.
120
What can you learn about table health from the `pg_stat_user_tables` view?
It gives counters for each table: how many seq scans and index scans there were, how many rows were inserted/updated, how many dead rows exist, when the last VACUUM and ANALYZE ran. It's the first place I look for missing indexes and autovacuum problems.
121
A Flyway migration failed halfway on prod. How do the consequences differ between Postgres and MySQL, and what do you do?
In Postgres, DDL is transactional, so the migration is rolled back completely, including its flyway_schema_history entry: no failed entry is left. In MySQL, DDL does an implicit commit, so half-applied changes stay and you have to clean them up by hand. In MySQL a failed entry does stay, and you need flyway repair afterward.
122
How do you rename a column or drop a column without stopping the application?
With the expand-contract method: first I add the new column and the application writes to both, I move the data over, then I switch reads to the new column and drop the old column only in the last release. Every stage is a separate deploy.
123
What are `maxLifetime`, `idleTimeout` and `keepaliveTime` in HikariCP for, and what errors do wrong values cause?
maxLifetime replaces a connection after a set time, idleTimeout closes surplus idle connections, and keepaliveTime periodically checks an idle connection. If maxLifetime isn't smaller than the timeout of the network devices or the database itself, the application gets a dead connection.
124
How does `spring.jpa.open-in-view` being enabled affect the connection pool, and why is it recommended to turn it off?
Open Session in View keeps the Hibernate session open for the whole HTTP request. After the first lazy load, the JDBC connection stays busy until the view is rendered and the response is sent. With a slow client or an external call, the pool runs out quickly.
125
What is JDBC `fetchSize`, and how do you read a million rows from PostgreSQL without filling up memory?
By default PgJDBC loads the whole result into memory. To fetch rows in chunks (with a cursor) you need to set fetchSize and turn autocommit off, otherwise fetchSize is ignored. In Spring, a query that returns a Stream inside @Transactional does this.
126
What does the `CLUSTER` command do, and how does the table's physical order (correlation) affect query speed?
CLUSTER physically rewrites the table in the order of a chosen index. Then range queries read the needed rows from fewer pages. But the order isn't maintained by later writes, and the command blocks the table completely for its whole run.
127
Why is `SELECT count(*)` slow on a big table, and how do you quickly get an approximate count?
Because of MVCC, PostgreSQL has to check whether each row is visible, so for an exact count it reads the whole table or index. For places like "about 12 million total" in a UI, pg_class.reltuples or the estimate in EXPLAIN is enough.
128
How do you produce subtotals and grand totals (`ROLLUP`, `GROUPING SETS`) in one query for a report?
GROUP BY ROLLUP (region, city) gives the per-city, per-region and grand totals in one query. GROUPING SETS lets you state exactly which combinations you need. The GROUPING() function tells which row is a total.
129
How does a recursive CTE work, and what are its risks on tree-like data?
A recursive CTE starts from the result of the initial (anchor) query and runs the recursive part again and again until no new rows come out. The main risks are an endless loop because of a cycle in the data, and slowness on a large tree.
130
After two JOINs, `SUM(amount)` came out several times larger than the real value. Why, and how do you fix it?
This is fan-out: if one order has 3 items and 2 payments, the JOIN produces 6 rows and each amount is added several times. You have to aggregate each "many" side separately and then JOIN.
131
What does the `MERGE` command in PostgreSQL 15 do, and how does it differ from `INSERT ... ON CONFLICT`?
MERGE compares a source table with the target: it does UPDATE/DELETE for matches and INSERT for non-matches, with several conditions. But unlike ON CONFLICT, it doesn't protect against unique violations on parallel inserts, because it doesn't rely on a unique index.
132
Why do gaps appear in a sequence, and how does `allocationSize` in Hibernate relate to the sequence?
A sequence isn't tied to the transaction: a value taken isn't returned even on rollback, and caching and crashes also leave gaps. If Hibernate's allocationSize=50, it reserves a block of 50 ids in one call, so the DB sequence's INCREMENT BY must also be 50.
133
When does partition pruning work in declarative partitioning, and what limitations will you run into?
Pruning is the planner or executor not reading unneeded partitions based on the query condition. It works only when there's a condition on the partition key. The main limitations: the primary key and unique indexes must include the partition key, and there is no global unique across partitions.
134
What is the difference between synchronous and asynchronous mode in streaming replication, and what problem does replica lag cause in the application?
In asynchronous mode the primary confirms a commit immediately and the WAL reaches the replica later: it's fast, but on failover the last transactions may be lost. In synchronous mode the commit waits for the replica's confirmation. Because of lag, a user who reads data they just wrote from a replica may not see it.
135
How do streaming (physical) and logical replication differ, and when do you choose which?
Physical (streaming) / Logical — What is copied: the whole cluster, all databases / selected tables; Replica: read-only / writable, can have its own indexes; Major version: must be the same / can differ; DDL: automatic / not copied; Sequences: copied / not copied
136
What is TOAST, and how do big text or jsonb columns affect query speed?
A Postgres page is 8 KB, so values larger than about 2 KB are compressed and moved in chunks into a separate TOAST table. That keeps the main table compact, but if SELECT * also pulls the big column, every row costs an extra read and decompression.
137
When does deliberately departing from normalization pay off, and what price do you pay?
Denormalization pays off when reads or aggregates are expensive and the data changes rarely: for example, a copy of the product price on an order, or comment_count on a post. The price is keeping the copies in sync, and the risk of inconsistency.
138
A composite natural key or a surrogate `id`: how do you choose a table's primary key?
In most cases I use a surrogate bigint PK and make the natural key (say, country_code + passport_no) a separate unique constraint. A natural key can change, makes FKs bigger, and is awkward with an ORM. The exception is pure link (many-to-many) tables, where a composite PK is natural.
139
What is the difference between `pg_cancel_backend` and `pg_terminate_backend`, and how do you safely stop a hung query on prod?
pg_cancel_backend(pid) cancels only the current query, and the session and connection stay alive. pg_terminate_backend(pid) drops the whole session, and an open transaction is rolled back. I cancel first, and terminate if that doesn't help.
140
A prepared statement suddenly got slow after it had run 5-6 times. What could be the cause?
Postgres plans a prepared statement with a custom plan (based on the actual parameters) for the first 5 runs, then switches to a generic plan if its cost looks similar. If the parameter values are unevenly distributed, the generic plan can be very bad for some values.
141
You need to add a NOT NULL column to a table with 500 million rows and fill in the old rows. How do you plan it without downtime?
I first add the column as nullable or with a constant default (PG11+ doesn't rewrite the table), then backfill in small batches, and set NOT NULL through CHECK ... NOT VALID and VALIDATE with only a short lock. I run every stage with lock_timeout and replica lag monitoring.
142
How do you protect personal data in the database (passport, phone, card): encryption, masking and layers of permissions?
I use several layers: disk encryption (at rest), TLS, application-side encryption of the most sensitive columns, limiting access with roles, and making sure PII doesn't end up in logs and backups. For fields that must be searchable, I store a hash next to the encrypted value.
143
How do you design routing read queries to replicas in a Spring Boot application, and where is it easy to make mistakes?
AbstractRoutingDataSource sends a readOnly transaction to the replica and everything else to the primary; LazyConnectionDataSourceProxy is needed so the decision is made once the readOnly flag is known. The main risks are stale data caused by replica lag and incorrectly marked readOnly.
144
How do you design storage and cleanup for an audit/event table that receives 50 million records a day?
I use time-based range partitioning (daily or weekly), create the partitions ahead of time automatically, and clean up old data with DETACH/DROP PARTITION, not DELETE. Indexes are kept minimal, and old partitions go to cheap storage or an archive.
145
Postgres CPU hit 100% on prod and the application slowed down. What do you do in the first 15 minutes?
First I determine who and what is eating the CPU: active queries in pg_stat_activity, recent changes in pg_stat_statements, whether a deploy or the traffic changed. Then I limit the damage (cancel the heavy query, a feature flag, a rollback), and I analyze the cause in depth later.
146
How do you choose data isolation for a multi-tenant SaaS: shared tables + tenant_id, a schema per tenant, or a separate database per tenant?
Shared tables / Schema per tenant / Database per tenant — Number of tenants: 100,000+ / hundreds to a few thousand / tens to hundreds; Isolation: logical / medium / strong; Migration: one / N times / N times; "Noisy neighbor": yes / yes (one server) / no; Exporting/deleting one tenant: hard / easy / easiest
147
You need to write data to the database and send an event to Kafka. How do you solve the dual write problem?
Writing to the database and sending to the broker is not one atomic operation: one can succeed while the other fails. With the transactional outbox, the event is written to an outbox table in the same DB transaction as the business data, and then a separate process (a poller or CDC) delivers it to Kafka.
148
The Postgres primary server went down. How do you build automatic failover, and what data can be lost?
Usually a tool like Patroni manages leader election through etcd/Consul and promotes the most advanced replica to primary. With asynchronous replication the last commits can be lost (RPO > 0); to prevent split brain, the old primary must be stopped with fencing.
149
A popular post's likes_count row receives thousands of UPDATEs per second and lock waits have increased. How do you solve it?
A single hot row is a bottleneck that serializes writes. The solutions: split the counter across several "slot" rows and sum them on read, accumulate changes in memory or Redis and flush to the database periodically, or use eventually consistent aggregation.
150
How do you build a backup strategy for Postgres, and why isn't pg_dump enough on its own?
pg_dump gives a logical snapshot: good for small databases and for migration, but it restores only to the moment of the dump and is slow on a big database. A serious system needs a physical base backup and a continuous WAL archive, which is what gives you restore to any second (PITR). And if you don't restore a backup regularly, you can't trust it.
151
How do you model a wallet or account balance: updating a `balance` column, or a ledger that records every change?
In a system that handles money, the foundation is immutable ledger entries (each credit/debit as its own row), with the balance derived from them. For speed I also keep a balance column, but I update it in the same transaction as the ledger entry and under a row lock.
152
The `GET /orders` endpoint has 8 optional filters (status, date, customer, amount...). How do you design the indexes and the query?
You can't put an index on every combination. I find the 2-3 most used filter patterns in real traffic and put composite indexes on them, and I build the query dynamically with only the filters that were given. A "universal" query like (:status IS NULL OR status = :status) confuses the planner.
153
How do you design the schema to keep product price history and answer the question "what was the price on March 15?"?
I store the price in a separate history table with a validity range: valid_during tstzrange. An exclusion constraint guarantees that ranges don't overlap, and a GiST index makes the "price at that time" query fast. I keep the current price in a separate column or fetch it with an upper_inf condition.
154
To store a category tree, which do you choose: an adjacency list, a materialized path (`ltree`), or a closure table?
adjacency list / ltree path / closure table — Parent: parent_id / path = 'elektronika.telefon.smartfon' / (ancestor, descendant, depth) pairs; All descendants: recursive CTE / path <@ 'elektronika' + GiST / a plain JOIN; Moving a node: 1 row / update the path of the whole branch / delete and insert many rows…
155
The payment provider sends the same callback twice. How do you process it only once in the database?
I put a unique constraint on the external ID and do INSERT ... ON CONFLICT DO NOTHING: if the row is inserted, I process it; if not, it's a duplicate. Since the check and the write are one atomic action, there's no race.
156
Deadlocks show up on prod from time to time. How do you find the cause from the log, and how do you fix it?
The "deadlock detected" entry in the PostgreSQL log has the two processes, the locks they waited for, and the queries. Usually the cause is two code paths locking the same rows in different orders. The fix: make the lock order the same, or sort the rows to be locked up front.
157
You need to load 50 million rows into a new table in one go. How do you do it fast and safely?
I load with COPY, not through JPA; I create the indexes and FKs after the load, split the work into chunks instead of one big transaction, and watch the replication lag. If the table is new, the fact that nobody is writing to it yet gives you a lot of freedom.
158
How do you reliably enforce a limit like "at most 5 SMS per user per day" with only the database when several instances are running?
"Count first, then write" breaks the limit under parallel requests. The reliable way is an atomic counter on a (user_id, day) row: INSERT ... ON CONFLICT DO UPDATE SET cnt = cnt + 1 WHERE cnt < 5 RETURNING cnt. If no row comes back, the limit is used up.
159
What do you look at when you code-review the database schema of a new service?
Types (money, time, id), constraints (NOT NULL, FK, unique, CHECK), indexes on FK columns, indexes that match the main queries, the growth and cleanup of big tables, and the lock risk of migrations. The goal is to catch decisions that will be expensive to change later, now.
160
How does the SERIALIZABLE level work in PostgreSQL, and what has to change in Java code if you use it?
PostgreSQL implements SERIALIZABLE through SSI: without taking locks, it tracks dangerous dependencies between transactions and, if there's a risk of an anomaly, cancels one with error 40001. So the application must have a retry mechanism that re-runs the whole transaction.
161
Run PostgreSQL yourself (on VMs or Kubernetes) or use a managed service (RDS, Cloud SQL): how do you evaluate it?
I usually choose managed: backups, PITR, failover, patches and monitoring come ready, and the team focuses on the product. I'd consider running it myself only with a concrete reason: a needed extension isn't available, you need superuser, the price differs a lot at large volume, or there's a data residency requirement.
162
How do you organize access rights to the database across an organization: roles, least privilege and password rotation?
Each service connects with its own role to only its own schema, migrations use a separate role, and people get access to prod only temporarily and with auditing. Passwords live in a secret manager and are rotated automatically, and where possible I use IAM or short-lived credentials.
163
The application sends the database a huge number of small queries and most of the response time goes to the network. How do you reduce that at the architecture level?
First I measure: how many times a single API request goes to the database. Then I remove N+1, combine queries (JOIN, = ANY, batch), cut the round trips in a single transaction, and if needed bring the application and database closer into one zone and cache reads.
164
You want to build event sourcing on PostgreSQL. How do you design the event store table, optimistic concurrency and snapshots?
I write events to a single append-only table with a unique key on (stream_id, version). The insert goes in with the expected version: a unique violation means a conflict. For long streams there's a snapshot table, and for read models you need a global sequence number and outbox/CDC.
165
When do you decide to shard PostgreSQL, and how do you choose the shard key?
Sharding is the last resort: only after vertical scaling, replicas, partitioning, archiving and query optimization are exhausted. The key should keep the most queries within a single shard and spread the load evenly, usually tenant_id or user_id.
166
Where do you draw the line between Hibernate/JPA and hand-written SQL (jOOQ, JdbcTemplate) on a team?
For writes and working with aggregates, JPA: dirty checking, optimistic locking and cascades are useful there. For complex reads, reports, bulk operations and PostgreSQL-specific features, SQL (jOOQ or JdbcTemplate). What matters is that the rule is written down and checked in review.
167
How do you catch a slow or dangerous query in a new release before it reaches prod?
I set several nets: tests in CI on a real PostgreSQL with data volume close to prod, assertions on the number of queries per endpoint, checking the EXPLAIN plan of the important queries, a migration linter, and a pg_stat_statements comparison on a canary deploy.
168
How do you keep data consistent between a Redis cache and PostgreSQL? How do you close the race conditions in cache-aside?
Usually cache-aside: on a read, if it's not in the cache I fetch from the database and write it to the cache; on a write, I update the database and then delete the cache key (I don't update it). But a parallel read and write can put a stale value back into the cache, so I add a TTL, deletion after commit, and sometimes a version or a delayed second delete.
169
40 microservice instances connect to one PostgreSQL and `too many clients` errors appear. How do you plan connections?
I add up the pool size of every instance and compare it with the number of active connections the database can really handle. Usually the fix is to shrink the instance pools and put PgBouncer in transaction mode in between. More connections don't give speed, quite the opposite.
170
How do you decide whether to adopt PostgreSQL extensions (PostGIS, pg_partman, TimescaleDB, pgvector) in an organization?
An extension is a dependency that becomes part of the database. I check whether it's available in the managed environment, whether it's supported through major upgrades, what its license is, who knows it, and whether there's a way out. I write the decision into an ADR and add the extension to an approved list.
171
How do you use prod data for test and staging environments: anonymization, subsets and keeping it fresh?
I don't copy a prod dump straight into staging. An automated pipeline deterministically anonymizes the PII in the copy, takes a subset without breaking FKs if needed, and runs regularly. The rules live in the same repo as the schema.
172
How do you bring optimistic locking up to the REST API level (ETag, `If-Match`), and how does it connect to the `version` column in the database?
The @Version value on the entity is returned in the response as an ETag, and the client sends it back in an If-Match header when updating. The server runs UPDATE ... WHERE version = ? with that version; if it doesn't match, it returns 412 Precondition Failed. That way the "last writer wins" problem is closed between users too.
173
In a system split across several databases or shards, how do you guarantee a globally unique value like `username` or email?
Each shard knows about uniqueness only within itself. For global uniqueness you need a separate "reservation" table (in one place, with a unique key), or you make the unique value the shard key. Because a write touches two places, I design it as reservation first, then the main record, and cleanup on failure.
174
Several services run on a single PostgreSQL cluster, and one service's heavy queries slow down the others. How do you detect the "noisy neighbor" and isolate it?
First I group pg_stat_statements and pg_stat_activity by role or application_name to see who takes how much CPU, I/O and connections. Then I use per-role limits (connections, timeouts, work_mem), move heavy reads to a replica, and eventually split the heavy service into its own cluster.
175
When is using PostgreSQL as a queue with `FOR UPDATE SKIP LOCKED` the right call, and when should you move to Kafka or RabbitMQ?
If the tasks run at hundreds to thousands per second, you need a transactional guarantee, and not adding infrastructure matters, a Postgres queue is good. If traffic is very large, or you need many consumer groups, replay or long retention, use a broker.
176
Order, payment and inventory are separate services with separate databases. How do you keep data consistent between them? Why not use XA/2PC?
I use a saga: each service does its own local transaction and emits an event, and on a failure the earlier steps are undone with compensation. For emitting events reliably, a transactional outbox. 2PC leaves resources locked when the coordinator dies and couples the services tightly.
177
You want to do CDC from PostgreSQL with Debezium. What risks come with a logical replication slot, and how do you manage them?
A slot doesn't let WAL be deleted until the consumer has read it. If Debezium stops, WAL grows until the disk is full and the primary goes down. So slot lag monitoring, a max_slot_wal_keep_size limit, and a plan for recovering from a lost slot are mandatory.
178
You need to upgrade PostgreSQL from 14 to 17, and the allowed downtime is a few minutes. What plan do you make?
Two main paths: pg_upgrade --link (fast, but a few minutes of downtime and rolling back is hard) or syncing to a new cluster with logical replication and then doing a switchover (downtime of seconds, but a lot of preparation). In both cases I do a full rehearsal on a copy first.
179
"Orphan" rows and impossible statuses are showing up in the database. At which layers do you protect data invariants?
The cheapest and most reliable protection is constraints in the database itself: NOT NULL, FK, unique, CHECK, exclusion. Application validation is for a clear error message to the user, and the database is the last barrier. Regular check jobs also reveal violations early.
180
The product team is asking for complex analytical reports and full-text search in PostgreSQL. When is Postgres enough, and when do you add ClickHouse or Elasticsearch?
At moderate volume, Postgres's full-text search, pg_trgm, materialized views and reports on a replica are enough. If you need OLAP over billions of rows, or relevance and faceted search, use a dedicated system, but at the price of synchronization.
181
Dashboard queries are slow because of heavy JOINs. How do you choose between denormalization, a materialized view, or a separate read model?
If the data being a few minutes stale is fine, REFRESH MATERIALIZED VIEW CONCURRENTLY. If you need real-time, a denormalized table updated by a trigger or the application, or a read model built from events. With each option you're choosing between consistency and the cost of writes.
182
Several microservices write directly to the tables of one shared database. What problems does this cause, and how do you separate them?
A shared database couples services tightly through the schema: one team's migration breaks another's, independent deploys and scaling are lost, and who is responsible for what becomes unclear. The separation is to give each table a single owner, with the others going through an API or events, step by step.
183
Users can build arbitrary queries through a generic filter API (GraphQL, admin search). How do you protect the database from heavy queries?
Several layers: at the API level a complexity limit and an allowed list of filter/sort fields, mandatory pagination, and building the query only on indexed fields; at the database level, statement_timeout with a separate role, a connection limit, and routing to a replica if possible.
184
How do you plan a migration project from MySQL to PostgreSQL?
I work on three fronts: matching the schema and types, finding MySQL-specific SQL and behavior in the application code, and moving the data continuously through CDC and doing a short switchover. Most of the time goes not to moving the data but to finding and testing behavior differences.
185
How do you choose a primary key strategy for a new system: a `bigint` sequence, UUIDv4, UUIDv7, or a Snowflake ID?
For a single database and an internal ID, a bigint identity is the most compact and fast. For an ID that is exposed externally or generated in a distributed way, UUIDv7: it's ordered by time, so it doesn't hurt a B-tree the way UUIDv4 does. I avoid making UUIDv4 the PK on a big table.
186
How do you reconcile soft delete (`deleted_at`) with the GDPR "delete my data" requirement in a single system?
Soft delete is a reversible business deletion, while GDPR erasure is truly destroying personal data. I keep them separate: on erasure the personal fields are anonymized, and there's a plan for the copies in backups, logs and CDC as well.
187
Financial tables need the history of every change. Which do you choose: a trigger, application-level audit, or CDC?
A trigger never misses a write but doesn't know the context; Envers is rich in context but doesn't see native SQL; CDC is asynchronous. In finance I combine a trigger with context supplied by the application (SET LOCAL).
188
How do you plan database resources for the coming year (capacity planning)?
I tie the current indicators (volume growth, TPS, CPU, IOPS, connections, hot data size) to business metrics and extrapolate from the business forecast. For each resource I calculate a "when it runs out" date, and put together a plan of measures several months before it.
189
Which metrics and alerts do you consider mandatory for PostgreSQL?
Whether the primary is alive, replica lag, connections, the oldest transaction and XID age, lock waits, disk/WAL growth, replication slots, and latency from pg_stat_statements. Alerts point at symptoms, and the dashboard points at causes.
190
Write latency spikes every few minutes. How do you check whether it's related to checkpoint and WAL settings?
If max_wal_size is small, checkpoints happen often, full page writes bloat the WAL, and IO waves appear. I confirm it with log_checkpoints, raise max_wal_size, and smooth out the writes.
191
The application has to run in two regions. How do you evaluate active-passive and active-active options with PostgreSQL?
Active-passive is simple and consistent, but writing from the far region is slow and a little data may be lost on failover. Active-active needs conflict resolution; with PostgreSQL I do it only when the data is partitioned by region.
192
How do you set the timeouts at the application, connection pool and PostgreSQL levels so they fit together?
Timeouts should shrink from the outside in: HTTP > transaction > statement > lock. Otherwise a query the client has given up on keeps running in the database. A short connectionTimeout in Hikari, and in the database statement_timeout and lock_timeout per role.
193
How do you prevent the same room from being booked twice for an overlapping time range in a hotel booking system?
The most reliable way is an exclusion constraint in the database itself: EXCLUDE USING gist (room_id WITH =, stay WITH &&). It rejects overlapping ranges at any isolation level and on any code path. A check in the application is only for a friendly error message.
194
The write volume is approaching what a single PostgreSQL primary can handle. What options do you consider before sharding?
First I make the writes themselves cheaper: drop unneeded indexes, batch and COPY, HOT updates, smaller rows. Then I split off the load: logs and events to another system, non-synchronous writes through a queue, functional splitting. Sharding comes after these.
195
How do you keep the versions, settings and extensions of 50 PostgreSQL clusters consistent and manageable?
I manage the clusters as code, not by hand: configuration templates (Terraform, Ansible or a Kubernetes operator), cluster profiles (small/medium/large), drift detection, a version policy and automatic upgrades. Every cluster must have an owner and an inventory record.
196
A mobile app works offline and syncs with the server later. How do you design the changes and conflicts in the server database?
The server gives every change a monotonically increasing sequence number, and the client asks "give me everything after the last number I saw". Deletes are stored as tombstones. Client writes arrive with an idempotency key and a base version; a conflict is resolved according to the business rule, often at the field level.
197
A Flyway migration that reached prod turned out to be wrong (data got corrupted or the application doesn't work). How do you roll back, and what rules do you set on the team?
On prod I fix forward: with a new V migration, because changing an applied file breaks the checksum. If data was lost, I restore a separate copy with PITR and bring back the needed rows.
198
20 teams work on one platform and each writes its own migrations. What do you do so a dangerous migration doesn't reach prod?
I put the rules into the pipeline, not into people's memory: a migration linter in CI (squawk, for example), an automatic trial on a prod copy, lock and duration checks, a mandatory lock_timeout, and a review by the DB owner for dangerous changes. For the rest, documentation and ready-made templates.
199
Repository tests use H2 while prod runs PostgreSQL. How do you build a database testing strategy at the organization level?
I don't trust testing PostgreSQL-specific code on H2. I switch to a real PostgreSQL with Testcontainers, in exactly the prod version and with exactly the Flyway migrations. For speed, container reuse and proper layering of tests, with a separate check for the migrations.
200
The team proposes stuffing many fields into a `jsonb` column: "no need to change the schema". When do you agree and when do you push back?
For truly variable, rarely queried attributes (settings, external API responses, type-specific properties of a product) jsonb is good. But fields that are filtered on, joined on, need a constraint, or are updated often should be in regular columns.
Sign up — studied questions get marked and your progress is saved.