Questions 461–480 of 501 · 0 of 20 on this page marked learned
461.sql-0461Hardsenior
Comments can belong to posts, photos or videos. How should the comments table reference its parent?
A 'polymorphic' design with parent_type and parent_id columns is common in ORMs, but the database cannot enforce a foreign key on it. Safer options are separate nullable foreign key columns (post_id, photo_id, video_id) with a CHECK that exactly one is set, or a shared parent table (commentables) that posts, photos and videos each reference.
Full answer
Option 1, polymorphic pair (no referential integrity):
Deleting a post leaves orphaned comments unless application code cleans up.
Option 2, exclusive foreign keys:
text
comments(id, post_id REFERENCES posts, photo_id REFERENCES photos, video_id REFERENCES videos, body,
CHECK ((post_id IS NOT NULL)::int + (photo_id IS NOT NULL)::int + (video_id IS NOT NULL)::int = 1))
Real foreign keys and cascades work; adding a new parent type needs a new column.
One foreign key, any number of parent kinds, at the cost of creating a commentables row with each parent.
Option 4, separate tables per parent (post_comments, photo_comments) is simple but duplicates logic.
The CHECK syntax shown casts booleans as in PostgreSQL; SQLite accepts the comparison results directly as 0 and 1. Not run here.
Key points
Polymorphic pairs lack foreign keys
Exclusive FKs with a CHECK enforce integrity
A supertype table generalises
Separate tables duplicate logic
Choose by how often parent types are added
Common mistakes
Relying on application code for integrity
Allowing several parent columns set at once
Follow-ups
How would you count comments per parent across types?
How do ORMs map each option?
Tips
Compare integrity across the options
462.sql-0462Hardsenior
How would you find friends-of-friends who are not already friends, for a 'people you may know' feature?
Store friendships as directed rows in both directions, friendships(user_id, friend_id). Join the table to itself (the friends of the user's friends), exclude the user and existing friends with NOT EXISTS, and rank candidates by the number of mutual friends. Precompute suggestions for large networks, because the second hop grows quickly.
Full answer
text
friendships(user_id, friend_id, PRIMARY KEY (user_id, friend_id)) -- both directions stored
SELECT f2.friend_id AS candidate, COUNT(*) AS mutual_friends
FROM friendships f1
JOIN friendships f2 ON f2.user_id = f1.friend_id
WHERE f1.user_id = :me
AND f2.friend_id <> :me
AND NOT EXISTS (SELECT 1 FROM friendships x WHERE x.user_id = :me AND x.friend_id = f2.friend_id)
GROUP BY f2.friend_id
ORDER BY mutual_friends DESC
LIMIT 20;
Storing both directions makes listing a user's friends a simple index range on user_id and keeps queries symmetric; a CHECK or trigger keeps pairs in sync.
Scaling: a user with 500 friends who each have 500 friends gives 250,000 rows to group. Batch jobs that precompute top suggestions nightly, sampling, or a graph database for deeper traversals are common answers. Blocked users and declined suggestions need their own exclusion tables. The query is illustrative and was not run here.
Key points
Store friendships in both directions
Self-join for the second hop
Exclude self and existing friends
Rank by mutual friends
Precompute at scale
Common mistakes
Storing each friendship once and writing OR conditions everywhere
Running deep traversals live for every page view
Follow-ups
How would you include third-degree connections?
When would a graph database be better?
Tips
Explain the growth of the second hop
463.sql-0463Easyfresher
How would you store postal addresses for customers in many countries?
Use flexible fields: address lines, locality, administrative area, postal code and an ISO country code, with most fields optional because formats differ by country. Validate per country in the application or with a postal service. Copy the address onto orders at purchase time so later edits do not rewrite history.
Not every country uses postal codes, states or the same order of fields.
Indian addresses often include landmarks; Japanese addresses order from large to small areas.
A strict zip CHAR(5) breaks for UK codes like 'SW1A 1AA'.
Decisions:
country_code uses ISO 3166-1 alpha-2 and drives validation and formatting.
Keep a customer's addresses in their own table (several per customer, with a default flag).
Snapshot the shipping address onto each order; an order must show where it was actually shipped.
Geocode (latitude, longitude) separately if delivery routing needs it.
Key points
Flexible, mostly optional fields
ISO country codes
Validate per country
Several addresses per customer
Snapshot addresses on orders
Common mistakes
US-only fields like ZIP and state for everyone
Orders that reference editable addresses
Follow-ups
How would you format an address for printing?
How would you deduplicate addresses?
Tips
Explain the snapshot on orders
464.sql-0464Mediummid
Walk through what a database does between receiving a SELECT and returning rows.
The statement is parsed into a syntax tree, checked against the catalog (tables, columns, permissions), rewritten (views expanded, rules applied), planned by the optimizer, which estimates costs of alternative access paths and join orders using statistics, and then executed by operators that read pages from cache or disk and stream rows back to the client.
Full answer
Stages in more detail:
Parse: text to a tree; syntax errors are reported here.
Rewrite: views replaced by their definitions; in PostgreSQL, row-level security policies are added.
Plan: the optimizer enumerates candidate plans (sequential scan versus index scan, nested loop versus hash join, join order) and estimates their cost from table statistics; the cheapest is chosen.
Execute: plan nodes pull rows from their children (scan, filter, join, aggregate, sort, limit), reading pages through the buffer cache.
Return: rows are sent to the client in batches; a cursor can fetch them gradually.
Why it matters in interviews: slow queries are usually a planning problem (bad estimates, missing index) or an execution problem (too much data read, sorts spilling to disk). EXPLAIN shows step 4's choice; EXPLAIN ANALYZE also runs step 5 and reports actual rows and times. SQLite follows the same broad stages with its own bytecode engine, visible with EXPLAIN.
Key points
Parse, analyse, rewrite, plan, execute
The planner uses statistics to estimate costs
Execution operators pull rows from children
EXPLAIN shows the plan; ANALYZE adds actuals
Views are expanded before planning
Common mistakes
Thinking the database runs SQL clauses in written order
Ignoring planning when diagnosing slow queries
Follow-ups
What statistics does the planner use?
Why can the same query get different plans?
Tips
Name each stage in order
465.sql-0465Hardsenior
When does a planner choose a nested loop, a hash join or a merge join?
Nested loops suit small outer inputs with an index on the inner side, since each outer row probes the index. Hash joins suit large unsorted inputs joined on equality: one side is built into an in-memory hash table and the other probes it. Merge joins suit inputs already sorted on the join key, or when sorting is cheap, and also support range-like merges.
Full answer
Nested loop: for each row of the outer input, look up matching rows of the inner. Cost is roughly outer rows x cost of one lookup, so it shines for '10 orders and their customers by primary key' and degrades badly when the outer side is large and the inner has no index.
Hash join: build a hash table on the smaller input's join key, then scan the larger input and probe. Linear in both inputs; needs memory (work_mem in PostgreSQL) and spills to disk in batches if the table does not fit. Only equality joins.
Merge join: walk two inputs sorted by the join key in step, like merging two sorted lists. Good when both come sorted from indexes, or for very large inputs where sorting beats hashing.
SQLite's planner uses nested loops almost exclusively, relying on indexes and automatic temporary indexes; PostgreSQL and other server databases choose among all three. A bad row estimate commonly leads to a nested loop over far more rows than expected, which is a classic cause of sudden slowness. These are described behaviours, not run here.
Key points
Nested loops: small outer, indexed inner
Hash joins: large inputs, equality keys, memory
Merge joins: sorted inputs
SQLite mostly uses nested loops
Bad estimates lead to bad join choices
Common mistakes
Assuming one join algorithm is always best
Ignoring work_mem when hash joins spill
Follow-ups
How would you spot a nested loop over too many rows in EXPLAIN ANALYZE?
What is an automatic index in SQLite?
Tips
Tie each algorithm to input sizes
466.sql-0466Mediummid
CPU on the database server is at 100 percent and the application is slow. How do you find the cause?
Look at what is running now (pg_stat_activity: active queries, their duration and wait events) and at cumulative query statistics (pg_stat_statements sorted by total time). Usually a few query shapes dominate, often because of a missing index, a plan change or a sudden increase in call volume. Fix the top offender, and cancel runaway queries if needed.
Full answer
Steps:
Current activity: SELECT pid, now() - query_start AS runtime, state, wait_event, left(query, 80) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY runtime DESC;
Top statements: from pg_stat_statements, order by total_exec_time to find the shapes consuming most CPU overall, and by calls to spot a query that suddenly runs thousands of times per second (often an N+1 or a cache outage).
Plans: EXPLAIN (ANALYZE, BUFFERS) the top shape with realistic parameters.
Recent changes: deploys, new indexes dropped, statistics, traffic spikes, a batch job started.
Relief: pg_cancel_backend(pid) stops a query; pg_terminate_backend(pid) ends the session. Rate-limit the offending endpoint if needed.
Then fix: add the missing index, rewrite the query, restore the cache, or move the batch job off-peak. CPU-bound databases are rarely solved by more CPU alone. These views are PostgreSQL-specific; described here, not run.
Key points
Check current activity first
Rank query shapes by total time
Look for call volume spikes
Explain the top offender
Cancel before terminate
Common mistakes
Restarting the database without finding the cause
Optimising rare queries while a frequent one dominates
Follow-ups
What does pg_stat_statements normalise?
When would you terminate instead of cancel?
Tips
Sort by total time, not average
467.sql-0467Hardsenior
The database disk is filling up fast although data volume has not grown much. Where would you look?
Check the write-ahead log directory first: an inactive replication slot or failing WAL archiving makes PostgreSQL keep WAL indefinitely. Then look for table and index bloat from heavy updates, large temporary files from big sorts and hashes, and growing server logs. Find the largest relations with pg_total_relation_size and remove the cause rather than only adding disk.
Full answer
Checklist:
Replication slots: SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) FROM pg_replication_slots; An inactive slot from a decommissioned replica or CDC tool retains WAL forever. Drop it if it is no longer needed.
Bloat: dead tuples in hot tables and indexes, blocked by long transactions.
Temporary files: queries spilling sorts and hashes; log_temp_files shows them.
Logs: verbose statement logging can produce gigabytes per day.
Largest objects: SELECT relname, pg_size_pretty(pg_total_relation_size(oid)) FROM pg_class ORDER BY pg_total_relation_size(oid) DESC LIMIT 10;
Set alerts on disk usage and on slot lag (max_slot_wal_keep_size caps retained WAL in PostgreSQL 13+). Running out of disk can stop the database entirely, so treat a fast-growing disk as urgent. Described here, not run.
Key points
Inactive replication slots retain WAL
Failing archiving accumulates WAL
Bloat and temp files consume space
Find the largest relations
Cap slot retention and alert early
Common mistakes
Deleting WAL files by hand
Only adding disk without finding the cause
Follow-ups
What does max_slot_wal_keep_size do?
How would you safely remove an old slot?
Tips
Start with WAL and slots
468.sql-0468Mediummid
A read replica has fallen hours behind the primary. What could cause it, and what would you do?
Common causes are a burst of writes on the primary (bulk loads, mass updates), a replica too weak to replay changes at the primary's rate, long queries on the replica that delay replay (hot_standby_feedback or max_standby_streaming_delay settings), or network limits. Measure lag, find what the replica is waiting on, and reduce the write burst or strengthen the replica.
Full answer
Diagnose:
Lag: on the primary, pg_stat_replication shows sent, written, flushed and replayed positions; on the replica, now() - pg_last_xact_replay_timestamp() approximates time lag.
Replay conflicts: queries on the replica can block replay when max_standby_streaming_delay allows waiting; check for long reporting queries.
Resources: replay is single-threaded for much of the work in PostgreSQL, so a replica with slow disks falls behind under heavy writes.
Write bursts: a large batch job or index build on the primary generates WAL faster than replay.
Actions:
Throttle or batch bulk jobs on the primary.
Move long analytics off the replica or allow them to be cancelled.
Give the replica comparable disk performance.
Route lag-sensitive reads to the primary while the replica catches up.
Alert on replication lag so it is noticed in minutes, not hours. Described here, not run.
Key points
Write bursts outpace replay
Replica queries can delay replay
Replay needs fast disks
Measure lag at both ends
Route sensitive reads to the primary meanwhile
Common mistakes
Ignoring lag until users report stale data
Running heavy reports on a replica configured to wait for them
Follow-ups
What does hot_standby_feedback trade off?
How would you detect lag from the application?
Tips
List causes on both sides
469.sql-0469Hardsenior
You must add a NOT NULL column with a default value to a 200-million-row PostgreSQL table. Is that dangerous?
Since PostgreSQL 11, adding a column with a constant (non-volatile) default is a fast metadata change: existing rows return the default without being rewritten, so ADD COLUMN ... NOT NULL DEFAULT 'x' is quick apart from the brief exclusive lock. A volatile default such as random() or clock_timestamp() forces a full table rewrite. Older versions rewrite in all cases.
Full answer
Fast path (PostgreSQL 11+):
text
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN channel text NOT NULL DEFAULT 'web';
The default is stored in the catalog, and existing rows read it until they are next updated. The lock is still ACCESS EXCLUSIVE, so a lock timeout and retry protect against waiting behind long transactions.
Slow cases:
Volatile defaults (DEFAULT gen_random_uuid(), clock_timestamp()) rewrite every row.
Adding NOT NULL later to an existing column requires a scan; use ADD CONSTRAINT ... CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT, and in PostgreSQL 12+ SET NOT NULL can use that validated check to skip the scan.
Changing a column's type usually rewrites.
For SQLite, ALTER TABLE ADD COLUMN with a constant default is also a quick schema change; NOT NULL requires a non-NULL default. These PostgreSQL details are stated from documentation, not run here.
Key points
Constant defaults are metadata-only in PostgreSQL 11+
Volatile defaults rewrite the table
The ALTER still needs a brief exclusive lock
NOT VALID then VALIDATE avoids long locks for NOT NULL on existing columns
Common mistakes
Assuming every ADD COLUMN rewrites the table
Using a volatile default on a huge table
Follow-ups
How would you backfill a computed value instead?
Which ALTER operations still rewrite?
Tips
Separate constant from volatile defaults
470.sql-0470Mediummid
A startup asks whether to use PostgreSQL or a document database such as MongoDB for its new product. How would you advise?
Start from the data and queries: if entities are related (users, orders, payments) and need joins, constraints and transactions, a relational database fits, and PostgreSQL's jsonb covers flexible attributes too. Document stores suit data read and written as self-contained documents with varying shape, and scale out writes more easily, but cross-document consistency and ad-hoc joins are weaker.
Full answer
Questions to ask:
Relationships: will reports join customers, orders and products? Relational wins.
Integrity: must the database reject orphans, duplicates and invalid states? Constraints are a relational strength.
Transactions: multi-entity atomic changes (money, inventory) are natural in SQL; document stores support them now but with more caveats.
Shape: if each record is a self-contained aggregate (a product catalogue entry with nested variants) read whole, documents fit well.
Scale: horizontal write scaling is built into many document stores; PostgreSQL scales far vertically and with read replicas, and further with extensions or sharding layers.
Team skills and tooling: SQL skills and BI tools are widespread.
For most early-stage products, PostgreSQL with some jsonb columns is a safe default that keeps options open; move parts to specialised stores when a concrete need appears.
Key points
Choose by relationships and queries
Constraints and transactions favour relational
Self-contained aggregates suit documents
jsonb covers flexible attributes
Defer specialised stores until needed
Common mistakes
Choosing by popularity
Assuming schema-less means no schema work
Follow-ups
How would you model a product catalogue in each?
When would you add a second database?
Tips
Ask about the queries first
471.sql-0471Easyfresher
Results come back in a different order in production than in development, and a page shows items shuffled. Why?
Without ORDER BY, SQL makes no promise about row order. The order you see depends on the plan, physical layout, parallelism and caching, which differ between environments and over time. Add an ORDER BY with a unique tiebreaker wherever order matters, including inside pagination.
Full answer
Why order changes:
A different plan (index scan versus sequential scan versus hash aggregate) returns rows in a different order.
Updates move rows physically in PostgreSQL, so a table scan's order drifts.
Parallel workers return rows as they finish.
Synchronized scans in PostgreSQL can start a scan in the middle of a table when another scan is already running.
Rules:
Any user-visible list needs ORDER BY.
Ties need a tiebreaker (ORDER BY created_at DESC, id DESC), or rows with equal keys can swap between requests, duplicating or hiding items across pages.
ORDER BY inside a subquery or view does not guarantee the order of the outer result.
GROUP BY does not imply sorted output.
SQLite offers PRAGMA reverse_unordered_selects = ON to reverse the order of unordered queries, a cheap way to find code that relies on accidental order in tests.
Key points
No ORDER BY means no guaranteed order
Plans and layout change order
Add unique tiebreakers
Subquery ORDER BY does not carry outward
reverse_unordered_selects finds hidden reliance
Common mistakes
Relying on insertion order
Assuming GROUP BY sorts
Follow-ups
How do ties break pagination?
Can a view's ORDER BY be trusted?
Tips
Mention the SQLite testing pragma
472.sql-0472Easyfresher
A runaway query has been running for an hour and is slowing everything. How do you stop it safely and prevent a repeat?
Find its process id in pg_stat_activity and call pg_cancel_backend(pid), which cancels the current query and keeps the session; use pg_terminate_backend(pid) only if cancel does not work. The query's transaction rolls back. Prevent repeats with statement_timeout for application and reporting roles, and fix the query or its index.
Full answer
text
SELECT pid, usename, now() - query_start AS runtime, left(query, 80)
FROM pg_stat_activity WHERE state = 'active' ORDER BY runtime DESC;
SELECT pg_cancel_backend(12345);
Notes:
Cancelling a long UPDATE or DELETE rolls it back, which can itself take time and generate WAL; that is expected.
Terminating ends the connection; the application must reconnect.
statement_timeout can be set per role (ALTER ROLE reporting SET statement_timeout = '5min') or per transaction (SET LOCAL), so ad-hoc reports cannot run forever while migrations can opt out.
idle_in_transaction_session_timeout handles sessions that hold transactions open without running anything.
Afterwards, EXPLAIN the query to find why it was slow. In SQLite, a long query is interrupted from the application with sqlite3_interrupt (in Python, connection.interrupt()). Described here, not run.
Key points
Cancel first, terminate if needed
The transaction rolls back
Set statement_timeout per role
Handle idle-in-transaction sessions
Fix the root cause afterwards
Common mistakes
Killing the server process from the OS
No timeouts on reporting roles
Follow-ups
Why can a cancelled DELETE take long to stop?
What timeout suits an API role?
Tips
Mention per-role timeouts
473.sql-0473Hardsenior
How would you upgrade a production PostgreSQL database to a new major version with little downtime?
Two common paths: pg_upgrade with --link, which rewrites catalogs and reuses data files, giving downtime of minutes for most sizes; or logical replication into a new-version server, then a quick switchover, giving downtime of seconds at the cost of more setup and limits (sequences and DDL are not replicated). Rehearse on a copy and have a rollback plan either way.
Full answer
pg_upgrade:
Install the new version alongside the old.
Run pg_upgrade --check, then stop the old server and run pg_upgrade --link.
Start the new server, run vacuumdb --analyze-in-stages to rebuild statistics, which are not carried over in older releases.
Rollback after --link is hard once the new server has started, so take a backup or snapshot first.
Logical replication:
Create the new cluster with the schema.
Publish tables on the old server and subscribe from the new; initial copy then streaming changes.
At cut-over: stop writes, wait for the subscriber to catch up, copy sequence values, point the application at the new server.
The old server remains intact as a fallback.
Either way: test the application against the new version, check extensions are available, and rehearse the steps with timing on a production-sized copy. Described from documentation, not run here.
Key points
pg_upgrade --link gives short downtime
Logical replication gives near-zero downtime
Sequences and DDL need manual handling with logical replication
Analyze after upgrading
Rehearse and plan rollback
Common mistakes
Upgrading in place without a backup
Forgetting to copy sequence values at cut-over
Follow-ups
What breaks with extensions during upgrades?
How would you verify data after switchover?
Tips
Compare downtime and rollback for both
474.sql-0474Mediummid
Should business rules live in stored procedures or in application code?
Rules that protect data integrity for every client (uniqueness, references, valid states, balances never negative) belong in the database as constraints, and sometimes triggers or functions. Workflow and presentation logic usually belongs in application code, where it is easier to test, version and deploy. Stored procedures pay off for set-based operations that would otherwise move lots of data over the network.
Full answer
Arguments for the database:
Every client, script and admin tool is subject to the same rules.
Set-based operations (recalculating totals for a million rows) run without network round trips.
Constraints are declarative and cannot be bypassed.
Arguments for the application:
Familiar languages, test frameworks, debugging and code review.
Easier deployment and rollback than coordinated database migrations.
Logic involving external services (email, payments) cannot live in the database anyway.
Fewer database-specific features, which eases migrations between engines.
A balanced rule: declare integrity in the schema (NOT NULL, CHECK, UNIQUE, foreign keys, exclusion constraints), keep business workflows in the application, and use database functions selectively for performance-critical set operations or for security boundaries (functions that expose a narrow operation instead of table access). Keep database code in version control with migrations either way.
Key points
Integrity rules belong in constraints
Workflows fit application code
Procedures help set-based heavy work
Database code needs version control too
Functions can narrow access for security
Common mistakes
Putting all logic in procedures that nobody can test
Enforcing integrity only in one application
Follow-ups
How would you test a stored function?
When do triggers become a maintenance problem?
Tips
Separate integrity from workflow
475.sql-0475Mediummid
In an interview you are asked to estimate the storage for a table of one billion order rows. How do you approach it?
Estimate the average row size from column types (for example bigint 8 bytes, timestamp 8, a few integers, short text), add per-row overhead (about 24 bytes of header plus alignment in PostgreSQL), multiply by the row count, then add indexes, which often total 50 to 100 percent of the table, plus free space and growth. State assumptions and round sensibly.
Full answer
Worked estimate:
Columns: id bigint (8), customer_id bigint (8), placed_at timestamptz (8), status smallint (2), total_minor bigint (8), currency char(3) (about 4), channel short text (about 8). Roughly 46 bytes, say 48 with alignment.
Row overhead in PostgreSQL: tuple header about 24 bytes plus a 4-byte line pointer, so about 76 bytes per row.
Page fill: pages are 8 KB with some free space; assume about 100 rows per page, close to 80 bytes per row.
Table: 1,000,000,000 x 80 bytes is about 80 GB.
Indexes: primary key on id (about 20 to 25 GB), (customer_id, placed_at) (about 30 GB). Total about 55 GB.
Total: about 135 GB, plus bloat headroom (20 percent) and a year of growth.
Then discuss consequences: whether the working set fits in memory, backup and restore times, whether partitioning by time helps, and whether old data could move to cheaper storage. Interviewers value the method and stated assumptions over exact numbers. These figures are estimates, not measured here.
Key points
Estimate row size from types
Add per-row and page overhead
Indexes add a large share
Add headroom for bloat and growth
Discuss consequences, not just the number
Common mistakes
Forgetting indexes
Ignoring per-row overhead
Follow-ups
How would compression change the estimate?
How much memory would the working set need?
Tips
State each assumption
476.sql-0476Mediummid
Write the idea behind a 'trending posts' query that favours recent likes over old ones.
Score each post by its interactions weighted by recency, for example likes in the last 24 hours or a decaying sum where each like counts as exp(-age / half_life). Compute scores periodically into a table indexed by score, because calculating decay over all likes on every request is expensive.
Full answer
Simple window-based score:
text
SELECT post_id, COUNT(*) AS recent_likes
FROM likes WHERE created_at >= now() - interval '24 hours'
GROUP BY post_id ORDER BY recent_likes DESC LIMIT 50;
Alternatively, the common 'gravity' formula divides total points by (age in hours + 2) raised to a power, so newer posts rise faster.
Implementation:
A job every few minutes recomputes scores for posts with recent activity into trending(post_id, score, computed_at) with an index on score.
Only posts with activity in the last few days need recomputing.
Guard against manipulation: count distinct users, weight new accounts lower.
The exact formula is a product decision; the database part is efficient incremental aggregation. The SQL shown is illustrative and was not run here.
Key points
Weight interactions by recency
Window counts or decaying sums
Precompute scores periodically
Recompute only active posts
Count distinct users to resist gaming
Common mistakes
Recomputing decay over all history on each request
Counting raw likes without recency
Follow-ups
How would you personalise trending?
How would you choose the half-life?
Tips
Explain the half-life idea
477.sql-0477Hardsenior
Given an order status history table, return each order's status as it was at the end of 5 March 2026.
Keep only history rows with changed_at up to the cut-off, then pick the latest of those per order with ROW_NUMBER() ordered by changed_at descending. Orders created after the cut-off have no qualifying row and are absent, or appear with NULL through a LEFT JOIN from the orders table.
SELECT order_id, status, changed_at FROM (
SELECT h.*, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC) AS rn
FROM status_history h WHERE changed_at < '2026-03-06'
) WHERE rn = 1 ORDER BY order_id;
order_id
status
changed_at
1
paid
2026-03-01 09:05
2
cancelled
2026-03-05 18:30
Order 1 was 'paid' at the cut-off; its shipment happened on the 6th, after it. Order 2 had been cancelled on the evening of the 5th. Order 3 did not exist yet, so it is missing. The filter uses < '2026-03-06' rather than <= '2026-03-05' so changes at any time on the 5th are included. This 'as of' pattern is the basis of audit questions and of type 2 dimension lookups; an index on (order_id, changed_at) serves it well.
sql
CREATE TABLE status_history (order_id INTEGER, status TEXT, changed_at TEXT);
INSERT INTO status_history VALUES
(1, 'placed', '2026-03-01 09:00'), (1, 'paid', '2026-03-01 09:05'), (1, 'shipped', '2026-03-06 10:00'),
(2, 'placed', '2026-03-04 12:00'), (2, 'cancelled', '2026-03-05 18:30'),
(3, 'placed', '2026-03-07 08:00');
SELECT order_id, status, changed_at FROM (
SELECT h.*, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC) AS rn
FROM status_history h WHERE changed_at < '2026-03-06'
) WHERE rn = 1 ORDER BY order_id;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
Filter history to the cut-off first
Pick the latest row per key
Use a half-open bound for the day
Entities created later are absent
Common mistakes
Picking the latest row overall and then filtering by date
Using <= with a date-only bound on timestamps
Follow-ups
How would you show how long each order stayed in each status?
How would you list orders whose status changed on a given day?
Tips
Filter before ranking
478.sql-0478Easyfresher
A query meant to show each department's head count shows 8 on every row. What is wrong?
COUNT(*) OVER () counts over the whole result, because an empty OVER clause has one partition containing every row. Add PARTITION BY dept_id to count within each department, or use GROUP BY when one row per department is wanted.
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 name, dept_id, COUNT(*) OVER () AS dept_headcount FROM employees ORDER BY dept_id, name;
name
dept_id
dept_headcount
Lena
NULL
8
Asha
1
8
Mei
1
8
Ravi
1
8
Sara
2
8
Tom
2
8
Diego
3
8
Omar
3
8
Every employee shows 8, the total number of employees. The window has no partition, so all rows share one frame.
A corrected version:
sql
SELECT name, dept_id, COUNT(*) OVER (PARTITION BY dept_id) AS dept_headcount FROM employees ORDER BY dept_id, name;
name
dept_id
dept_headcount
Lena
NULL
1
Asha
1
3
Mei
1
3
Ravi
1
3
Sara
2
2
Tom
2
2
Diego
3
2
Omar
3
2
Partitioning by department gives 3 for Engineering, 2 for Sales and Support, and 1 for Lena, whose NULL department forms its own partition. The window keeps one row per employee; if the report needs one row per department, GROUP BY dept_id is simpler and cheaper.
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');
SELECT name, dept_id, COUNT(*) OVER () AS dept_headcount FROM employees ORDER BY dept_id, name;
SELECT name, dept_id, COUNT(*) OVER (PARTITION BY dept_id) AS dept_headcount FROM employees ORDER BY dept_id, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
OVER () is one partition for all rows
PARTITION BY splits the count
NULL keys form their own partition
GROUP BY when one row per group is wanted
Common mistakes
Forgetting PARTITION BY
Using a window when an aggregate would do
Follow-ups
How would you show each employee's share of the department head count?
When would you keep both detail and group totals?
Tips
Read the OVER clause carefully
479.sql-0479Mediummid
A nightly import reports success but the table has fewer rows than the file. Why might ON CONFLICT DO NOTHING be the cause?
ON CONFLICT DO NOTHING silently skips any row that violates a unique key, so duplicates in the file, or rows that already exist, disappear without an error. Count changes() or RETURNING rows to see how many were really inserted, and send conflicting rows to a reject table when they should be reviewed.
Full answer
sql
CREATE TABLE members (email TEXT PRIMARY KEY, name TEXT);
INSERT INTO members VALUES ('a@x.com', 'Ana');
The query as written:
sql
INSERT INTO members VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin') ON CONFLICT DO NOTHING;
SELECT changes() AS inserted, (SELECT COUNT(*) FROM members) AS total;
inserted
total
1
2
Three rows were sent and only one was inserted. 'a@x.com' already existed and the second 'b@x.com' collided with the first; neither raised an error, and Ana's new surname was also silently ignored.
A corrected version:
sql
CREATE TABLE import_rejects (email TEXT, name TEXT);
INSERT INTO import_rejects SELECT column1, column2 FROM (VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin')) v WHERE EXISTS (SELECT 1 FROM members m WHERE m.email = v.column1) OR (SELECT COUNT(*) FROM (VALUES ('a@x.com'), ('b@x.com'), ('b@x.com')) w WHERE w.column1 = v.column1) > 1;
SELECT * FROM import_rejects ORDER BY email, name;
Checked against the same batch, the query lists every row involved in a conflict: Ana's new version, which collides with the existing row, and both Ben rows, which collide with each other (the first was inserted and the second skipped). In practice, load the file into a staging table first, find duplicates and existing keys with SQL, and only then insert, reporting counts for inserted, updated and rejected rows. Choose DO UPDATE when newer values should win.
sql
CREATE TABLE members (email TEXT PRIMARY KEY, name TEXT);
INSERT INTO members VALUES ('a@x.com', 'Ana');
INSERT INTO members VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin') ON CONFLICT DO NOTHING;
SELECT changes() AS inserted, (SELECT COUNT(*) FROM members) AS total;
CREATE TABLE import_rejects (email TEXT, name TEXT);
INSERT INTO import_rejects SELECT column1, column2 FROM (VALUES ('a@x.com', 'Ana Lopez'), ('b@x.com', 'Ben'), ('b@x.com', 'Benjamin')) v WHERE EXISTS (SELECT 1 FROM members m WHERE m.email = v.column1) OR (SELECT COUNT(*) FROM (VALUES ('a@x.com'), ('b@x.com'), ('b@x.com')) w WHERE w.column1 = v.column1) > 1;
SELECT * FROM import_rejects ORDER BY email, name;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
DO NOTHING hides conflicts
Check changes() or RETURNING counts
Duplicates within the file also conflict
Stage and report rejects
Use DO UPDATE when updates should apply
Common mistakes
Reporting success from the absence of errors
Ignoring duplicates inside the batch
Follow-ups
How would you keep the latest of two duplicates in a file?
How would you report inserted versus updated rows?
Tips
Compare rows sent with rows inserted
480.sql-0480Mediummid
After inserting an order, the code reads SELECT MAX(id) to get the new id, and sometimes gets another user's order. Fix it.
MAX(id) returns the highest id in the table, which may belong to an order another session inserted a moment later. Use the id the database returns for your own insert: INSERT ... RETURNING id (SQLite 3.35+ and PostgreSQL), or last_insert_rowid() in SQLite, which is per connection.
INSERT INTO web_orders2 (customer) VALUES ('Ana');
INSERT INTO web_orders2 (customer) VALUES ('Ben');
SELECT MAX(id) AS what_ana_thinks_is_hers FROM web_orders2;
what_ana_thinks_is_hers
2
In this run, two inserts happen back to back, as two users' requests would in production. Ana's code then asks for MAX(id) and receives 2, which is Ben's order. Under concurrency, the gap between insert and select is enough for another insert to land.
A corrected version:
sql
INSERT INTO web_orders2 (customer) VALUES ('Chen') RETURNING id, customer;
id
customer
3
Chen
RETURNING hands back the row that this statement inserted, with no second query and no race. last_insert_rowid() is also safe in SQLite because it is tracked per connection, and PostgreSQL's currval('seq') is per session; only MAX(id) and similar table-wide reads are unsafe. ORMs use these mechanisms internally.
sql
PRAGMA journal_mode = WAL;
CREATE TABLE web_orders2 (id INTEGER PRIMARY KEY, customer TEXT);
INSERT INTO web_orders2 (customer) VALUES ('Ana');
INSERT INTO web_orders2 (customer) VALUES ('Ben');
SELECT MAX(id) AS what_ana_thinks_is_hers FROM web_orders2;
INSERT INTO web_orders2 (customer) VALUES ('Chen') RETURNING id, customer;
Checked on SQLite 3.46.1, run twice with identical output.
Key points
MAX(id) races with other inserts
RETURNING gives the inserted row
last_insert_rowid is per connection
currval is per session in PostgreSQL
Common mistakes
Using MAX(id) or COUNT(*) to find new ids
Reading the id from a different connection
Follow-ups
How would you get ids for a multi-row insert?
What happens to last_insert_rowid after a failed insert?