Questions 341–360 of 501 · 0 of 20 on this page marked learned
341.sql-0341Easyfresher
A query using an alias in WHERE fails. Explain the error and fix it.
WHERE is evaluated before SELECT aliases exist and before grouping, so it cannot filter on an aggregate alias. Filter aggregates in HAVING, repeating the expression or, in SQLite, using the alias there.
Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
The query as written:
sql
SELECT dept_id, AVG(salary) AS avg_sal FROM employees WHERE avg_sal > 60000 GROUP BY dept_id; -- error on purpose
text
Error: misuse of aggregate: AVG()
SQLite resolves the alias to the AVG() expression and reports a misuse of aggregate, because WHERE filters individual rows before any average is computed. PostgreSQL gives a 'column does not exist' error for the same reason (not run here).
A corrected version:
sql
SELECT dept_id, ROUND(AVG(salary), 1) AS avg_sal FROM employees GROUP BY dept_id HAVING AVG(salary) > 60000 ORDER BY dept_id;
dept_id
avg_sal
1
103333.3
2
66000.0
HAVING runs after grouping, so the average exists. Departments 1 and 2 pass; department 3 averages 51500, and Lena's NULL department has a NULL average and is dropped. Repeating AVG(salary) in HAVING is portable; PostgreSQL does not accept the alias there.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
-- error on purpose
SELECT dept_id, AVG(salary) AS avg_sal FROM employees WHERE avg_sal > 60000 GROUP BY dept_id;
SELECT dept_id, ROUND(AVG(salary), 1) AS avg_sal FROM employees GROUP BY dept_id HAVING AVG(salary) > 60000 ORDER BY dept_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
WHERE runs before grouping and aliases
HAVING filters groups
Repeat the aggregate for portability
Common mistakes
Wrapping the query in a subquery only to reuse an alias, when HAVING suffices
Using HAVING for row filters that belong in WHERE
Follow-ups
In what order are SELECT clauses evaluated?
Can ORDER BY use the alias?
Tips
Explain logical evaluation order
342.sql-0342Mediummid
An API endpoint that lists orders became slow after the table grew. Walk through how you would investigate.
Capture the exact slow SQL and its parameters, then run EXPLAIN (ANALYZE in PostgreSQL) to see whether it scans the whole table, sorts large sets or loops badly. Compare estimated and actual row counts, add or adjust an index that matches the filter and sort, and confirm the plan and timing improve. Also check that the endpoint is not issuing one query per row.
Full answer
A practical order of work:
Find the query. Use slow query logs or pg_stat_statements to see the statement, how often it runs and its average time. Endpoint slowness is sometimes a hundred fast queries, not one slow one.
Reproduce with real parameters. A plan for customer_id = 5 can differ from one for a customer with a million orders.
Read the plan. Look for sequential scans on large tables, sorts spilling to disk, nested loops over many rows and big gaps between estimated and actual rows.
Fix the cause. Typical fixes are a composite index matching WHERE customer_id = ? ORDER BY placed_at DESC, keyset pagination instead of large OFFSETs, selecting fewer columns, or refreshing statistics with ANALYZE.
Verify. Rerun EXPLAIN ANALYZE, then watch the production metric after release.
Also check for lock waits, because a fast query blocked by a long transaction looks slow from the outside.
Key points
Measure before changing anything
Use real parameters when reading plans
Compare estimated and actual rows
Match indexes to filter plus sort
Check for lock waits and N+1 patterns
Common mistakes
Adding indexes at random
Testing plans on a tiny development database
Follow-ups
What does a large estimate error suggest?
How does OFFSET pagination slow down?
Tips
Give the steps in order
343.sql-0343Easyfresher
Code that loads 50 orders and then queries each order's customer separately is slow. What is the problem and the fix?
This is the N+1 query problem: one query for the list plus one query per row, so 51 round trips. Fetch the related data in one go, either with a JOIN or with a second query using WHERE id IN (...) for all needed customers. ORMs offer eager loading options for this.
Full answer
Each round trip costs network latency and parsing even when the query itself is fast. At 2 ms per query, 51 queries take about 100 ms, and the number grows with the page size.
Fixes:
One JOIN: SELECT o.*, c.name FROM orders o JOIN customers c ON c.id = o.customer_id WHERE ... LIMIT 50.
Two queries: load the orders, collect distinct customer ids, then SELECT * FROM customers WHERE id IN (...) and stitch in code. This avoids repeating wide customer rows.
ORM settings: eager loading (for example select_related or includes) turns lazy per-row loads into one of the forms above.
Detect it by counting queries per request in logs or tests. A test that asserts a maximum query count per endpoint stops regressions.
Key points
N+1 = one list query plus one per row
Latency per round trip dominates
Use a JOIN or a batched IN query
Count queries per request in tests
Common mistakes
Caching each per-row query instead of batching
Assuming fast individual queries mean a fast page
Follow-ups
When is the two-query approach better than a join?
How would you detect N+1 in production?
Tips
Quantify the round trips
344.sql-0344Hardsenior
Production logs show occasional deadlock errors between two transactions that update accounts. How would you fix it?
A deadlock occurs when two transactions lock rows in opposite orders and each waits for the other; the database aborts one. Make every transaction lock rows in a consistent order (for example by ascending account id), keep transactions short, and retry the aborted transaction on deadlock errors.
Full answer
Typical cause: a transfer from A to B locks A then B, while a transfer from B to A locks B then A. Each holds one lock and waits for the other. PostgreSQL detects the cycle after deadlock_timeout and aborts one transaction with SQLSTATE 40P01.
Fixes:
Consistent ordering: update the lower account id first, or lock both rows up front with SELECT ... FROM accounts WHERE id IN (a, b) ORDER BY id FOR UPDATE.
Short transactions: no network calls or user waits while holding row locks.
Retries: deadlocks can never be ruled out entirely, so the application should retry the whole transaction a few times with a small random delay.
Investigation: PostgreSQL logs both statements involved in the deadlock, which shows the conflicting order.
Indexes matter too: an UPDATE without a supporting index can lock more than expected in some engines, widening the conflict.
Key points
Deadlocks come from opposite lock orders
Lock rows in a consistent order
Keep transactions short
Retry on deadlock errors
Read the deadlock log details
Common mistakes
Raising lock timeouts, which only delays the failure
No retry logic for serialization and deadlock errors
Follow-ups
How does a deadlock differ from a long lock wait?
What is SQLSTATE 40001?
Tips
Describe the opposite-order cycle
345.sql-0345Mediummid
An application starts failing with 'too many connections' under load. What is happening and what would you change?
Each application process opens its own connections until the server's max_connections is reached, and new requests fail. Use a connection pool (in the app and often a server-side pooler such as PgBouncer), cap pool sizes so the total stays below the limit, and look for leaked connections or long transactions holding them.
Full answer
PostgreSQL uses a process per connection, so thousands of connections waste memory and slow the server even before the limit. Raising max_connections is rarely the right fix.
What to change:
Pool in the application with a fixed size per instance; total = instances x pool size must fit the server limit with headroom for admin access.
Add PgBouncer in transaction mode when there are many app instances or serverless functions; many client connections then share a few server connections. Session features such as prepared statements and advisory locks need care in that mode.
Find leaks: connections that are never returned, or sessions left idle in transaction, visible in pg_stat_activity. Set idle_in_transaction_session_timeout.
Reduce hold time: shorter transactions free connections faster.
A small pool often gives better throughput than a large one, because the database works best with roughly as many active queries as it has CPU cores and disks to serve them.
Key points
Connections are expensive in PostgreSQL
Pool in the app and cap totals
Use PgBouncer for many clients
Find idle-in-transaction leaks
Smaller pools often perform better
Common mistakes
Raising max_connections to thousands
Opening a connection per request without pooling
Follow-ups
What breaks under PgBouncer transaction pooling?
How would you size a pool?
Tips
Explain why raising the limit is a poor fix
346.sql-0346Mediummid
Should a new table use an auto-incrementing integer or a UUID as its primary key?
Integers are small, fast to index and easy to read, but they are guessable and need a central generator. UUIDs can be generated anywhere and hide row counts, at the cost of larger indexes; random UUIDv4 values also scatter inserts across the index. Time-ordered UUIDv7 gives most UUID benefits with insert locality.
Full answer
Considerations:
Size: bigint is 8 bytes; a UUID is 16 bytes in a native type (36 if stored as text, which should be avoided). Every foreign key and secondary index carries the key.
Insert pattern: sequential keys append to the right edge of the B-tree. Random UUIDv4 values land anywhere, causing more page splits and cache misses on large tables.
Generation: UUIDs can be created by clients, offline devices or several services without coordination, which helps merges and idempotent inserts.
Exposure: sequential ids in URLs reveal growth and invite enumeration; a UUID or a separate public id avoids that.
A common compromise is a bigint primary key internally plus a unique random public id for URLs, or UUIDv7 as the single key. PostgreSQL 18 adds a built-in uuidv7() function; on older versions it comes from an extension or the application (stated from documentation, not run here).
Key points
bigint keys are compact and sequential
UUIDs allow decentralised generation
Random UUIDs hurt index locality
UUIDv7 is time ordered
Store UUIDs in a native type, not text
Common mistakes
Storing UUIDs as 36-character text
Exposing sequential ids where enumeration matters
Follow-ups
How would you add a public id to an existing table?
Do UUID keys prevent all enumeration attacks?
Tips
Weigh size, locality and generation
347.sql-0347Mediummid
Design an audit log that records who changed what in important tables.
Write an append-only audit table with the table name, row key, action, old and new values (for example as JSON), the acting user and a timestamp. Fill it from triggers so no code path can skip it, pass the user through a session setting, and restrict UPDATE and DELETE on the audit table itself.
Triggers on each audited table capture changes from every client, including scripts and admin tools.
The application sets the acting user per transaction (SET LOCAL app.user_id = '42') and the trigger reads it with current_setting.
Store only changed columns on update if volume matters.
Make the log append-only: grant INSERT but not UPDATE or DELETE to the application role.
Index (table_name, row_pk, changed_at) for "history of this record".
Partition by month and archive old partitions if the log grows quickly.
Application-level logging is simpler to start but misses changes made outside the app. Change data capture from the write-ahead log is another option for streaming changes to other systems.
Key points
Append-only table with old and new values
Triggers make the log complete
Pass the acting user via a session setting
Restrict modification of the log
Index for per-record history
Common mistakes
Logging only in application code
Letting the application role edit audit rows
Follow-ups
How would you show a record's history in the UI?
How does change data capture differ from triggers?
Tips
Explain why triggers are used
348.sql-0348Hardsenior
How would you model product categories that can nest to any depth?
The simplest model is an adjacency list (parent_id on each category), queried with recursive CTEs. A materialized path ('1/4/9') makes subtree queries a prefix match, and a closure table stores every ancestor-descendant pair for fast queries at the cost of more writes. Choose based on how often the tree changes and which queries dominate.
Full answer
Options:
Adjacency list: categories(id, parent_id REFERENCES categories). Moves are a single update; subtree and path queries need WITH RECURSIVE. Works well for small and medium trees.
Materialized path: store path = '1/4/9/'. Subtree is WHERE path LIKE '1/4/%', which an index can serve. Moving a subtree rewrites the path of every descendant. PostgreSQL's ltree extension provides this with operators.
Closure table: category_paths(ancestor, descendant, depth). Any subtree or ancestor query is one join; inserts add a row per ancestor, and moves rewrite many rows.
Nested sets: left and right numbers; fast reads but painful writes, now rarely chosen.
For an online shop, an adjacency list plus a cached path or breadcrumb column is usually enough. Guard against cycles: a CHECK cannot do it, so validate moves in the application or a trigger.
Key points
Adjacency list with recursive CTEs is simplest
Materialized paths make subtree queries prefix matches
Closure tables trade writes for fast reads
Prevent cycles on moves
Common mistakes
Fixed columns for level1, level2, level3
Ignoring the cost of moving subtrees
Follow-ups
How would you count products in a category and all its children?
How would you detect a cycle?
Tips
Compare read and write costs
349.sql-0349Hardsenior
Design the tables for selling reserved seats at events without selling a seat twice.
Create a row per seat per event (event_seats) with a status and an optional hold expiry, and a unique constraint so each seat belongs to at most one ticket. Holding a seat is a conditional UPDATE from available to held; purchase changes held to sold in the same transaction as payment recording. Expired holds are released by a job or treated as available by queries.
UPDATE event_seats SET status = 'held', held_by = :cart, hold_expires_at = now() + interval '10 minutes'
WHERE event_id = :e AND seat_id = ANY(:seats)
AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()));
If the affected row count is less than the number requested, some seats were taken; roll back and tell the user. The atomic conditional update avoids a race between checking and holding.
The UNIQUE on tickets is the final guarantee against double sale. For very popular events, a queue in front of the hold step limits contention on the same rows.
Key points
One row per seat per event
Conditional UPDATE to hold seats atomically
Holds expire
A unique ticket constraint is the final guarantee
Compare affected rows with seats requested
Common mistakes
Checking availability and then updating in two steps without locks
Holds that never expire
Follow-ups
How would you support general admission tickets?
How would you handle payment failures after a hold?
Tips
Show the atomic hold
350.sql-0350Hardsenior
How would you use a database table as a job queue for background workers?
Store jobs with a status, run_at and attempts. Workers claim jobs with SELECT ... FOR UPDATE SKIP LOCKED inside a transaction, so concurrent workers take different rows without blocking each other. Mark jobs done or failed, retry with backoff, and delete or archive finished jobs to keep the table small.
Full answer
text
jobs(id bigserial PK, kind, payload jsonb, status DEFAULT 'queued',
run_at timestamptz DEFAULT now(), attempts int DEFAULT 0, locked_by, locked_at)
CREATE INDEX ON jobs (run_at) WHERE status = 'queued';
Claiming a job in PostgreSQL:
text
UPDATE jobs SET status = 'running', locked_by = :worker, locked_at = now()
WHERE id = (SELECT id FROM jobs WHERE status = 'queued' AND run_at <= now()
ORDER BY run_at LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING *;
SKIP LOCKED makes each worker skip rows another worker is claiming, instead of waiting. Then:
On success, set status 'done' (or delete the row).
On failure, increment attempts and set run_at = now() + backoff; after N attempts mark 'dead'.
A reaper resets jobs stuck in 'running' past a timeout.
This suits moderate volumes and gives transactional enqueueing with business data. Very high throughput is better served by a dedicated broker. SQLite has no SKIP LOCKED; a single writer claims jobs with an UPDATE ... RETURNING instead. The PostgreSQL statements here were not run here.
Key points
FOR UPDATE SKIP LOCKED lets workers claim different rows
Partial index on queued jobs
Retries with backoff and a dead state
Reap stuck jobs
Clean up finished jobs
Common mistakes
Polling with plain SELECT then UPDATE, so two workers take one job
Letting the jobs table grow forever
Follow-ups
Why enqueue in the same transaction as the business change?
When should you move to a message broker?
Tips
Explain SKIP LOCKED
351.sql-0351Mediummid
A payment request may be retried by the client after a timeout. How do you make sure the customer is charged only once?
Require an idempotency key on each payment request and store it with a unique constraint alongside the result. A retry with the same key finds the existing row and returns the stored result instead of charging again. Insert the key before calling the payment provider, inside a transaction or with a pending status.
Client sends the key (a UUID it generated) with the request.
Server does INSERT ... ON CONFLICT (idempotency_key) DO NOTHING. If a row already existed, return its stored status and response; if it is still pending, tell the client to retry later.
For a new row, call the provider, passing the same key if the provider supports it, and update the row with the outcome.
The unique constraint closes the race where two identical retries arrive at the same moment: only one insert succeeds. Also check that a reused key comes with the same amount and customer, rejecting mismatches. Keys can expire after a retention period such as 24 hours.
Key points
Client-generated idempotency keys
Unique constraint on the key
Return the stored result on retries
Reject a reused key with different parameters
Common mistakes
Deduplicating by amount and time window
Calling the provider before recording the key
Follow-ups
What if the server crashes after charging but before saving the result?
How long should keys be kept?
Tips
Say what the unique constraint prevents
352.sql-0352Mediummid
A user asks to have all of their personal data deleted. How would you handle that in the database?
Find every table that holds the user's data, using foreign keys and a maintained data inventory. Delete or anonymise rows in a transaction, keeping records that law requires (such as invoices) with personal fields scrubbed. Remember copies outside the main tables: backups, logs, search indexes, caches and analytics stores.
Full answer
Steps:
Inventory: list tables and columns with personal data. Foreign keys help find dependants; free-text columns and JSON need a manual check.
Decide per table: delete (sessions, preferences), anonymise (orders kept for accounting, with name and address replaced), or retain with a legal basis (invoices for tax periods).
Execute in one transaction where possible, with ON DELETE CASCADE only where cascading is clearly intended.
Downstream systems: queue deletions for search indexes, warehouses and third-party processors.
Backups: usually not edited, but expire on a schedule; record the request so restored data is deleted again after a restore.
Record that the request was completed, without keeping the deleted data.
Soft delete alone does not satisfy such a request, because the data is still stored. Legal requirements vary by jurisdiction, so the exact rules come from the organisation's privacy policy.
Key points
Maintain an inventory of personal data
Delete, anonymise or retain per table
Handle downstream copies
Plan for backups and restores
Soft delete is not deletion
Common mistakes
Deleting the user row and leaving orphans with personal data
Forgetting logs and analytics copies
Follow-ups
How does anonymisation differ from pseudonymisation?
How would you test that deletion is complete?
Tips
Separate delete, anonymise and retain
353.sql-0353Hardsenior
How would you choose a shard key when splitting a large database across several servers?
Pick a key that most queries filter on, so each request touches one shard, and that spreads data and load evenly, such as tenant_id or user_id. Avoid keys with hot values or time-based keys that send all new writes to one shard. Cross-shard queries, transactions and re-sharding become harder, so shard only when simpler options are exhausted.
Full answer
Criteria:
Query locality: if almost every request is "for tenant X", sharding by tenant keeps each request on one server.
Even distribution: hash the key (or use many virtual buckets mapped to servers) so no shard holds a giant share. A few huge tenants may need dedicated shards.
Growth: a timestamp key sends all inserts to the newest shard, creating a write hotspot.
Joins: tables that are joined together should share the shard key, so their related rows sit together.
Costs:
Queries without the shard key must fan out to every shard.
Transactions across shards need two-phase commit or application-level compensation.
Global unique constraints and sequences need special handling.
Rebalancing moves data while live; mapping keys to many logical buckets makes this easier.
Before sharding, consider indexes, read replicas, partitioning, caching and a larger server, which solve most growth problems with far less complexity.
Key points
Shard on the key most queries filter by
Distribute evenly, often by hashing
Avoid time-based hotspots
Co-locate related tables
Exhaust simpler options first
Common mistakes
Sharding by creation date
Sharding before simpler scaling options are tried
Follow-ups
How would you move one tenant between shards?
How do you generate unique ids across shards?
Tips
Tie the choice to the main query pattern
354.sql-0354Mediummid
Explain how a star schema for reporting differs from a normalised transactional schema.
A transactional (OLTP) schema is normalised to make small writes safe and consistent. A star schema for analytics has a central fact table of events with numeric measures, surrounded by denormalised dimension tables such as date, product and customer. It favours simple, fast aggregate queries over write efficiency.
Dimensions are denormalised: category and brand live on the product dimension instead of separate tables, so queries need one join per dimension.
The grain of the fact table is explicit, for example one row per order line.
Surrogate keys in dimensions allow history tracking, such as a customer moving city.
Loads happen in batches; updates to facts are rare.
Queries look like SUM(revenue) GROUP BY dim_date.month, dim_product.category, which columnar warehouses execute very quickly. A snowflake schema normalises dimensions further, trading simpler storage for more joins.
Key points
Fact tables hold measures at a stated grain
Dimensions are denormalised descriptive tables
OLTP schemas optimise writes and consistency
Star schemas optimise aggregate reads
Common mistakes
Running heavy analytics on the OLTP database
Leaving the fact table's grain undefined
Follow-ups
What is a slowly changing dimension?
How does a snowflake schema differ?
Tips
Define the grain
355.sql-0355Hardsenior
A customer moves city. How would a reporting dimension keep both the old and new city for historical sales?
Use a type 2 slowly changing dimension: instead of updating the customer row, close it with an end date and insert a new row with a new surrogate key, the new city and a start date. Facts recorded before the move keep pointing at the old row, so historical reports show the city at the time of sale.
Full answer
text
dim_customer(customer_key PK, customer_id, city, valid_from, valid_to, is_current)
When the customer moves on 2026-03-01:
UPDATE dim_customer SET valid_to = '2026-02-28', is_current = false WHERE customer_id = 7 AND is_current;
INSERT INTO dim_customer (customer_id, city, valid_from, valid_to, is_current) VALUES (7, 'Leeds', '2026-03-01', '9999-12-31', true);
New sales are loaded with the current customer_key. Reports grouped by city then attribute February sales to the old city and March sales to the new one.
Other types: type 1 overwrites (no history), type 3 adds a 'previous city' column (one step of history). Type 2 is the usual choice when attributes affect reporting. A unique partial index on customer_id WHERE is_current keeps one current row per customer.
Key points
Type 2 adds a new row per change
Surrogate keys link facts to the version at the time
valid_from, valid_to and is_current track versions
Type 1 overwrites, type 3 keeps one previous value
Common mistakes
Updating the city in place and rewriting history
Joining facts on the natural key instead of the surrogate key
Follow-ups
How would you query a customer's city on a given date?
Which attributes deserve type 2 tracking?
Tips
Show the close-and-insert step
356.sql-0356Mediummid
A stored backup turned out to be unusable during an incident. How should backups for a production database be set up?
Combine regular full backups with continuous archiving of the write-ahead log, which allows point-in-time recovery to just before a mistake. Keep copies in a separate location and account, encrypt them, and above all test restores on a schedule. A backup that has never been restored is an assumption, not a guarantee.
Full answer
Elements of a sound setup:
Physical base backups (for PostgreSQL, pg_basebackup or a tool such as pgBackRest) plus WAL archiving, enabling recovery to any moment, for example one minute before an accidental DELETE.
Logical dumps (pg_dump) for moving single databases or tables between versions; slower to restore at scale.
Off-site and separate credentials: a compromised production account should not be able to delete backups.
Retention matching business needs, such as daily for 30 days and monthly for a year.
Restore drills: automated restores into a scratch server, with row counts or checksums checked, and the time taken recorded against the recovery time objective.
Monitoring: alerts when a backup or WAL archive fails.
Replicas are not backups: a destructive statement replicates within seconds. For SQLite, the online backup API or VACUUM INTO produces consistent copies while the database is in use.
Key points
Full backups plus WAL archiving enable point-in-time recovery
Store backups off-site with separate credentials
Test restores regularly
Replicas are not backups
Monitor backup jobs
Common mistakes
Never testing restores
Treating a replica as a backup
Follow-ups
What are RPO and RTO?
How would you recover a single dropped table?
Tips
Stress restore testing
357.sql-0357Hardsenior
A PostgreSQL table with heavy updates keeps growing on disk although its row count is stable. What is going on?
PostgreSQL's MVCC writes a new row version on every UPDATE and leaves the old one as a dead tuple until VACUUM reclaims it. If autovacuum cannot keep up, or a long-running transaction prevents cleanup, dead tuples pile up and the table and its indexes bloat. Tune autovacuum for the table, end long transactions and, if needed, rebuild with pg_repack or VACUUM FULL.
Full answer
How to confirm:
pg_stat_user_tables shows n_dead_tup and the last autovacuum time for the table.
pg_stat_activity shows old transactions (xact_start) or sessions idle in transaction; their snapshot keeps dead rows visible, so VACUUM cannot remove them.
Abandoned replication slots and prepared transactions have the same effect.
Fixes:
Lower autovacuum_vacuum_scale_factor for the hot table so vacuum runs after a fixed number of changes rather than 20 percent of the table.
Kill or fix long transactions; set idle_in_transaction_session_timeout.
Reclaim existing bloat: plain VACUUM makes space reusable but rarely shrinks the file; VACUUM FULL rewrites the table under an exclusive lock, while pg_repack does it online.
Reduce churn: HOT updates (when no indexed column changes and the page has free space) avoid index bloat, so a lower fillfactor can help.
These are PostgreSQL-specific behaviours described here, not run.
Key points
UPDATE creates dead row versions
VACUUM reclaims them, unless old snapshots block it
Tune autovacuum per hot table
VACUUM FULL locks; pg_repack works online
HOT updates reduce index churn
Common mistakes
Running VACUUM FULL at peak time
Ignoring idle-in-transaction sessions
Follow-ups
What is transaction ID wraparound?
How does fillfactor help HOT updates?
Tips
Name the long-transaction cause
358.sql-0358Hardsenior
A simple ALTER TABLE ADD COLUMN froze the whole application for minutes. Why, and how do you avoid it?
ALTER TABLE needs an ACCESS EXCLUSIVE lock. It waited behind a long-running query or transaction, and every new query on the table queued behind the waiting ALTER, so the table became unusable. Set a short lock_timeout before DDL and retry, and make sure no long transactions are running when migrations deploy.
Full answer
The lock queue is the trap. Even if the ALTER itself would take milliseconds, it cannot start until existing readers release their locks. Meanwhile it sits first in the queue, and later SELECTs, which would normally share the table freely, wait behind it.
Safer migration habits:
SET lock_timeout = '3s'; before each DDL statement, with automatic retries, so a blocked ALTER gives up instead of stalling traffic.
Check pg_stat_activity for long transactions before deploying.
Prefer operations that do not rewrite the table: adding a nullable column or one with a constant default is fast in modern PostgreSQL; changing a type usually rewrites.
Build indexes with CREATE INDEX CONCURRENTLY.
Split migrations into small steps instead of one big transaction holding many locks.
Described from PostgreSQL's locking rules, not run here.
Key points
DDL needs strong locks
A waiting ALTER blocks later queries
Use lock_timeout and retries
Avoid table rewrites
Create indexes concurrently
Common mistakes
Assuming a fast DDL is safe at any time
Running migrations while reports hold long transactions
Follow-ups
Which ALTER operations rewrite the table?
Why can CREATE INDEX CONCURRENTLY not run inside a transaction?
Tips
Explain the lock queue
359.sql-0359Hardsenior
A 'likes' counter on a viral post causes lock waits because thousands of requests update the same row. How would you redesign it?
Every increment locks the same row, so updates serialise. Spread writes across several counter rows (sharded counters) and sum them on read, or append like events and aggregate periodically, or buffer increments in memory and flush in batches. A likes table with a unique (post_id, user_id) key also prevents double likes.
Full answer
Options:
Sharded counter: post_like_counts(post_id, shard, n, PRIMARY KEY (post_id, shard)). Each increment picks a random shard 0 to 15; reads do SUM(n). Contention drops roughly by the number of shards.
Event table plus rollup: insert into likes(post_id, user_id, created_at) (inserts do not contend on one row) and refresh a cached count every few seconds.
Buffered increments: collect counts in an in-memory store and apply UPDATE ... SET n = n + :batch periodically, accepting a small delay and possible loss on crash.
A unique key on likes(post_id, user_id) makes "like" idempotent and allows unliking. Displaying '12.4K likes' rarely needs exact real-time accuracy, which gives room for these trade-offs.
Key points
Single-row counters serialise writers
Sharded counters spread contention
Insert events and aggregate later
Batch increments
Exact real-time counts are rarely needed
Common mistakes
Adding more app servers, which increases contention
Counting likes with COUNT(*) on every page view at scale
Follow-ups
How would you show whether the current user liked the post?
How many shards are enough?
Tips
Quantify why one row serialises
360.sql-0360Hardsenior
A query that ran in 20 ms yesterday takes 30 seconds today, with no code change. What might have changed?
Most often the planner switched plans because table statistics or data distribution changed, for example after a bulk load, or a stale estimate made a nested loop look cheap. Compare the current plan with the old one, run ANALYZE, and check for parameter-specific plans, lock waits or a dropped index.
Full answer
Common causes:
Stale or skewed statistics: a bulk insert changed the data, autoanalyze has not run yet, and the planner misjudges row counts.
Plan flip at a threshold: as a table grows, a hash join or sequential scan becomes cheaper on paper, sometimes wrongly.
Generic prepared-statement plans: after several executions, PostgreSQL may switch to a generic plan that suits typical values but not skewed ones.
External factors: lock waits, a missing or invalid index after a failed concurrent build, or a cold cache after a restart.
Steps:
EXPLAIN (ANALYZE, BUFFERS) the slow query and compare estimates with actual rows.
ANALYZE the tables involved; if the plan changes back, set up better statistics (more default_statistics_target or extended statistics for correlated columns).
Keep a record of plans for critical queries (for example with auto_explain) so changes can be compared.
These are PostgreSQL-oriented descriptions, not run here.