{"id":"sql-interview-questions/aggregation","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL aggregation & HAVING interview questions","description":"Practice aggregation interview questions with worked answers: WHERE vs HAVING, COUNT differences, conditional aggregation and GROUP BY errors.","body":{"slug":"aggregation","name":"Aggregation & HAVING","h1":"SQL aggregation & HAVING interview questions","lede":"GROUP BY questions look easy until the interviewer asks why your column is not in the GROUP BY. Worked answers for the whole family.","questions":[{"difficulty":"Easy","question":"What is the difference between WHERE and HAVING?","answer_html":"<p>WHERE filters rows before grouping; HAVING filters groups after aggregation. That is why aggregates can appear in HAVING but not in WHERE.</p>\n<pre class=\"iq-code\"><code>SELECT customer_id, SUM(total) AS spent\nFROM orders\nWHERE status = 'completed'          -- row filter, pre-aggregation\nGROUP BY customer_id\nHAVING SUM(total) &gt;= 1000;          -- group filter, post-aggregation</code></pre>\n<p>Anchor the answer in the logical evaluation order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. WHERE cannot see aggregates because they do not exist yet when it runs.</p>"},{"difficulty":"Easy","question":"What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?","answer_html":"<p>COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL. COUNT(DISTINCT column) counts distinct non-NULL values.</p>\n<pre class=\"iq-code\"><code>SELECT COUNT(*)                        AS all_orders,\nCOUNT(discount_code)            AS orders_with_code,\nCOUNT(DISTINCT discount_code)   AS distinct_codes_used\nFROM orders;</code></pre>\n<p>The interview trap is the second one: a report that meant all orders but wrote COUNT(shipped_at) quietly excludes unshipped rows. COUNT(*) is never slower than COUNT(column): the engine does not have to check any value for NULL and can scan the narrowest index. COUNT(1) is the same as COUNT(*) on every major engine.</p>"},{"difficulty":"Easy","question":"Write total revenue per order status.","answer_html":"<p>Group by the status column and sum the total. The GROUP BY columns define the grain: one output row per distinct status.</p>\n<pre class=\"iq-code\"><code>SELECT status, SUM(total) AS revenue, COUNT(*) AS order_count\nFROM orders\nGROUP BY status\nORDER BY revenue DESC;</code></pre>\n<p>Say the word grain out loud. Half of all aggregation questions are really about which grain the result is on, and whether the caller expects one row per status or one per status and date.</p>"},{"difficulty":"Medium","question":"Return customers with more than five completed orders.","answer_html":"<p>Filter completed rows in WHERE, count per customer, keep big groups in HAVING.</p>\n<pre class=\"iq-code\"><code>SELECT customer_id, COUNT(*) AS completed_orders\nFROM orders\nWHERE status = 'completed'\nGROUP BY customer_id\nHAVING COUNT(*) &gt; 5;</code></pre>\n<p>The follow-up: moving status = 'completed' into HAVING is an error, because status is neither grouped nor aggregated, so it has no single value per group. If you need both counts in one query, count conditionally instead: HAVING SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) &gt; 5.</p>"},{"difficulty":"Medium","question":"Filter groups by an aggregate that never appears in the SELECT list.","answer_html":"<p>HAVING can reference any aggregate, whether or not it is projected. Here the average order size drives the filter while only the count is shown.</p>\n<pre class=\"iq-code\"><code>SELECT customer_id, COUNT(*) AS order_count\nFROM orders\nGROUP BY customer_id\nHAVING AVG(total) &gt; 150;</code></pre>\n<p>If you also want the average visible, add AVG(total) to the SELECT list, but nothing requires it. Some candidates believe HAVING only works on SELECTed aggregates; it works on any aggregate over the group.</p>"},{"difficulty":"Medium","question":"What does GROUP BY with multiple columns mean?","answer_html":"<p>One group per distinct combination of the listed columns, so the result grain is the pair. Revenue by status and month is one row per status and month.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL; see the next question for other engines:\nSELECT DATE_TRUNC('month', order_date) AS month,\nstatus,\nSUM(total) AS revenue\nFROM orders\nGROUP BY DATE_TRUNC('month', order_date), status\nORDER BY month, status;</code></pre>\n<p>The pitfall to mention: every extra column multiplies the row count. GROUP BY month, status, customer_id returns one row per customer per status per month, and a dashboard that expected one row per month will show many. Always state the grain of a grouped result before writing it.</p>"},{"difficulty":"Medium","question":"Group by month: why can you not just GROUP BY order_date, and what do you do instead?","answer_html":"<p>order_date has day-level grain, so grouping by it gives one group per day. You must group by an expression that collapses to the month, and then GROUP BY that same expression (or its alias where the engine allows it).</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL / DuckDB:\nSELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY 1\nORDER BY 1;\n\n-- SQLite (dates stored as ISO text):\nSELECT strftime('%Y-%m', order_date) AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY month\nORDER BY month;\n\n-- MySQL:\nSELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY month\nORDER BY month;\n\n-- SQL Server (DATETRUNC needs 2022+; use DATEFROMPARTS on older versions):\nSELECT DATETRUNC(month, order_date) AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY DATETRUNC(month, order_date)\nORDER BY month;</code></pre>\n<p>SQL Server accepts neither a SELECT alias nor an ordinal in GROUP BY, so the expression is repeated. PostgreSQL, MySQL and SQLite accept both. Ordinals break silently when someone reorders the SELECT list, so most style guides prefer the alias or the expression. Truncating to a date value rather than formatting to text also keeps the result sortable and usable in date arithmetic; FORMAT() on SQL Server is also notably slow per row.</p>"},{"difficulty":"Medium","question":"Why does selecting a column that is not in GROUP BY fail?","answer_html":"<p>Because a group of several orders has several order_id values and the query gives no rule for which one to return. The standard (since SQL:1999) allows a non-grouped column only when it is functionally dependent on the grouped columns, meaning the GROUP BY columns determine it uniquely.</p>\n<pre class=\"iq-code\"><code>-- Errors on PostgreSQL, SQL Server, Oracle and MySQL 5.7+ (ONLY_FULL_GROUP_BY):\nSELECT customer_id, order_id, SUM(total)\nFROM orders\nGROUP BY customer_id;\n\n-- Allowed on PostgreSQL and MySQL: c.name depends on the grouped primary key\nSELECT c.customer_id, c.name, SUM(o.total)\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.customer_id;</code></pre>\n<p>The fixes: add the column to GROUP BY, wrap it in an aggregate such as MAX(order_id), or use a window function when you need per-row detail next to group totals. SQL Server and Oracle do not apply the primary-key rule, so they need c.name in the GROUP BY too. SQLite, and MySQL with ONLY_FULL_GROUP_BY switched off, run the first query and return an arbitrary order_id per group, which is why MySQL turned that mode on by default in 5.7.</p>"},{"difficulty":"Hard","question":"Count orders of each status in one pass over the table.","answer_html":"<p>Conditional aggregation: SUM or COUNT a CASE inside one aggregate. One scan, one row, no self-joins.</p>\n<pre class=\"iq-code\"><code>SELECT COUNT(*)                                                  AS all_orders,\nSUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END)     AS completed,\nSUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)     AS cancelled,\nCOUNT(*) FILTER (WHERE status = 'refunded')               AS refunded  -- PostgreSQL, SQLite\nFROM orders;</code></pre>\n<p>The FILTER clause is the SQL-standard spelling of the same idea, supported by PostgreSQL, SQLite 3.30+ and DuckDB; SUM(CASE ...) works everywhere. COUNT(CASE WHEN status = 'completed' THEN 1 END) is a third form: with no ELSE, the CASE yields NULL and COUNT skips it. Add a GROUP BY and the same pattern gives per-customer or per-month status counts in one scan.</p>"},{"difficulty":"Medium","question":"How do WHERE and HAVING interact in a query with a JOIN?","answer_html":"<p>JOINs run first, WHERE filters the joined rows, then grouping and HAVING apply. A filter placed before grouping changes what gets summed; placed in HAVING it filters whole groups.</p>\n<pre class=\"iq-code\"><code>-- Revenue from completed orders, customers who spent &gt;= 1000:\nSELECT c.name, SUM(o.total) AS spent\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nWHERE o.status = 'completed'\nGROUP BY c.customer_id, c.name\nHAVING SUM(o.total) &gt;= 1000;</code></pre>\n<p>The subtle version they may ask next: moving o.status = 'completed' into HAVING fails because status is not grouped, and moving SUM(o.total) &gt;= 1000 into WHERE fails because aggregates do not exist yet when WHERE runs. The evaluation order decides where each filter goes; style has nothing to do with it.</p>"},{"difficulty":"Hard","question":"Group customers into spend buckets and count per bucket.","answer_html":"<p>The tempting one-pass answer groups by a CASE over SUM(total), but that mixes grains: the bucket depends on an aggregate per customer, while the count is per bucket. One query cannot compute both in a single GROUP BY.</p>\n<pre class=\"iq-code\"><code>SELECT CASE\n   WHEN spent &gt;= 1000 THEN '1000+'\n   WHEN spent &gt;= 100  THEN '100-999'\n   ELSE 'under 100'\nEND AS spend_bucket,\nCOUNT(*) AS customers\nFROM (\nSELECT customer_id, SUM(total) AS spent\nFROM orders\nGROUP BY customer_id\n) per_customer\nGROUP BY 1               -- SQL Server: repeat the CASE expression here\nORDER BY 1;</code></pre>\n<p>Recognizing that this needs two aggregation levels is the actual test. The inner query produces one row per customer, the outer one groups those rows into buckets. Customers with no orders are missing from both levels; if they should count as 'under 100', start the inner query from customers with a LEFT JOIN and COALESCE(SUM(o.total), 0).</p>"},{"difficulty":"Medium","question":"How do you concatenate one column values per group, like all product names per order?","answer_html":"<p>String aggregation: STRING_AGG on PostgreSQL, SQL Server 2017+ and DuckDB, GROUP_CONCAT on MySQL and SQLite, LISTAGG on Oracle.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL / SQL Server:\nSELECT o.order_id, STRING_AGG(p.name, ', ') AS products\nFROM orders o\nJOIN order_items oi ON oi.order_id = o.order_id\nJOIN products p ON p.product_id = oi.product_id\nGROUP BY o.order_id;\n\n-- MySQL / SQLite: GROUP_CONCAT(p.name SEPARATOR ', ') / GROUP_CONCAT(p.name, ', ')</code></pre>\n<p>Mention ordering inside the aggregate, because without it the order of names is whatever the plan produced and can change between runs, which breaks comparisons and tests. The spelling differs: STRING_AGG(p.name, ', ' ORDER BY p.name) on PostgreSQL, STRING_AGG(p.name, ', ') WITHIN GROUP (ORDER BY p.name) on SQL Server, GROUP_CONCAT(p.name ORDER BY p.name SEPARATOR ', ') on MySQL. MySQL also truncates the result at group_concat_max_len, 1024 bytes by default, without an error.</p>"}],"faqs":[{"question":"What is the difference between WHERE and HAVING?","answer":"WHERE filters rows before they are grouped; HAVING filters groups after aggregation. The worked questions show both sides of that line, including HAVING on an aggregate you never SELECT."},{"question":"Do the answers cover COUNT(*) vs COUNT(column)?","answer":"Yes, including COUNT(DISTINCT ...), and the report that counts a nullable column and silently drops rows. The LEFT JOIN case, where COUNT(*) turns a customer with no orders into a count of 1, is on the joins page."},{"question":"Are conditional aggregation and pivot questions included?","answer":"Yes. One question counts several statuses in a single pass with SUM(CASE ...), another groups customers into spend buckets defined with CASE inside GROUP BY."},{"question":"Why does my non-aggregated column fail?","answer":"A dedicated question covers the functional-dependency rule behind ONLY_FULL_GROUP_BY in MySQL and the matching error in PostgreSQL and SQL Server, why grouping by a primary key lets you select the other columns of that table, and why SQLite accepts the query silently."}]},"source_url":"https://sqlly.app/sql-interview-questions/aggregation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/basics","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL basics interview questions","description":"12 SQL basics interview questions with worked answers: NULL handling, UNION vs UNION ALL, keys, CASE expressions and the logical order of a query.","body":{"slug":"basics","name":"SQL basics","h1":"SQL basics interview questions","lede":"The questions interviewers use to check that you know the language itself, without an ORM in the way. Every answer ships with runnable SQL.","questions":[{"difficulty":"Medium","question":"What is the logical evaluation order of a SELECT query?","answer_html":"<p>Most engines evaluate a query roughly in this order: FROM and JOIN first, then WHERE, then GROUP BY, then HAVING, then the SELECT list, then ORDER BY and LIMIT.</p>\n<pre class=\"iq-code\"><code>SELECT city, COUNT(*) AS customers      -- 5. SELECT\nFROM customers                           -- 1. FROM / JOIN\nWHERE signup_date >= '2025-01-01'        -- 2. WHERE\nGROUP BY city                            -- 3. GROUP BY\nHAVING COUNT(*) > 10                     -- 4. HAVING\nORDER BY customers DESC                  -- 6. ORDER BY</code></pre>\n<p>The practical consequence: a column alias defined in the SELECT list cannot be used in WHERE, because WHERE runs first. Every engine accepts the alias in ORDER BY, which runs last. HAVING is where engines split: MySQL and SQLite accept a SELECT alias there as an extension, while PostgreSQL and SQL Server make you repeat the expression. Window functions and DISTINCT are evaluated with the SELECT list, which is why a window function cannot appear in WHERE either.</p>"},{"difficulty":"Easy","question":"What does NULL mean, and why does NULL = NULL not return true?","answer_html":"<p>NULL means unknown. A value may be missing, or not apply, or not be entered yet, and the engine cannot say whether two unknowns are equal. So <code>NULL = NULL</code> does not return true; it returns NULL, which the WHERE clause treats as not-true and filters out.</p>\n<pre class=\"iq-code\"><code>-- Returns zero rows even if the column holds NULLs:\nSELECT * FROM customers WHERE city = NULL;\n\n-- The correct forms:\nSELECT * FROM customers WHERE city IS NULL;\nSELECT * FROM customers WHERE city IS NOT NULL;</code></pre>\n<p>This three-valued logic (true, false, unknown) is the root of most NULL surprises, including NOT IN with a NULL in the list.</p>"},{"difficulty":"Easy","question":"How do you count or sum correctly when NULLs are involved?","answer_html":"<p>Aggregates skip NULLs: COUNT(column) counts only non-NULL values while COUNT(*) counts rows. SUM, AVG, MIN and MAX ignore NULL rows entirely, and AVG therefore divides by the number of non-NULL values, not the number of rows.</p>\n<pre class=\"iq-code\"><code>-- Suppose orders has a nullable discount column holding 10, NULL, 20.\n-- Returns 3, 2, 15 and 15: AVG divides 30 by 2, not by 3.\nSELECT COUNT(*) AS rows_all,\nCOUNT(discount) AS rows_with_discount,\nAVG(discount) AS mean_of_non_null,\nCOALESCE(AVG(discount), 0) AS mean_or_zero\nFROM orders;</code></pre>\n<p>If missing discounts should count as zero, the average you want is AVG(COALESCE(discount, 0)), which returns 10. COALESCE(AVG(discount), 0) only replaces the result when every row is NULL. Mixing those two up is the mistake this question is fishing for. ISNULL (SQL Server) and IFNULL (MySQL, SQLite) are the two-argument shorthands.</p>"},{"difficulty":"Easy","question":"What is the difference between UNION and UNION ALL?","answer_html":"<p>UNION ALL concatenates two result sets and keeps everything. UNION additionally removes duplicate rows, which costs a sort or a hash to detect them. If duplicates are impossible or acceptable, UNION ALL is faster.</p>\n<pre class=\"iq-code\"><code>-- One contact list; UNION deduplicates people in both tables:\nSELECT name, email FROM customers\nUNION\nSELECT name, email FROM subscribers;\n\n-- UNION ALL keeps two rows for anyone who is in both tables:\nSELECT name, email FROM customers\nUNION ALL\nSELECT name, email FROM subscribers;</code></pre>\n<p>Both require the same number of columns with compatible types in each branch, and the result takes its column names from the first branch. UNION compares whole rows, so the same email with a different name spelling still comes back twice.</p>"},{"difficulty":"Easy","question":"What does DISTINCT do, and when can it hide a bug?","answer_html":"<p>DISTINCT removes duplicate rows from the result. It applies to the whole selected row, not just the column it is written next to: SELECT DISTINCT city, name returns one row per city and name pair.</p>\n<pre class=\"iq-code\"><code>SELECT DISTINCT city FROM customers;</code></pre>\n<p>The interview follow-up: an unexpected DISTINCT is often a symptom of join fan-out. If joining orders to order_items tripled your row counts and you papered over it with DISTINCT, your SUM and COUNT aggregates are still wrong. Fix the grain of the join first; use DISTINCT to answer a genuine distinct-values question.</p>"},{"difficulty":"Easy","question":"What is the difference between DELETE and TRUNCATE?","answer_html":"<p>DELETE removes the rows that match its WHERE clause one by one, logs each row and fires DELETE triggers. TRUNCATE empties the whole table by deallocating its pages, so its cost does not grow with the row count. It takes no WHERE, fires no DELETE triggers, and is refused while another table's foreign key references the table (PostgreSQL lets you add CASCADE).</p>\n<pre class=\"iq-code\"><code>-- Precise, logged, rollable back, slower on big tables:\nDELETE FROM orders WHERE status = 'cancelled';\n\n-- Every row, at a cost that does not grow with table size:\nTRUNCATE TABLE staging_orders;</code></pre>\n<p>The engine differences are what make the answer strong. TRUNCATE can be rolled back inside a transaction on PostgreSQL and SQL Server, but on MySQL it causes an implicit commit. SQL Server and MySQL reset the identity or AUTO_INCREMENT counter; PostgreSQL keeps the sequence going unless you write TRUNCATE ... RESTART IDENTITY. SQLite has no TRUNCATE at all: DELETE FROM t without a WHERE clause takes a fast path instead.</p>"},{"difficulty":"Easy","question":"What is the difference between CHAR, VARCHAR and TEXT?","answer_html":"<p>CHAR(n) stores fixed-length strings padded with spaces, which suits codes of a known length such as two-letter country codes. VARCHAR(n) stores variable-length strings up to n characters. TEXT stores long strings: up to 1 GB on PostgreSQL (where VARCHAR without a length means the same thing), 64 KB for MySQL's TEXT, with MEDIUMTEXT and LONGTEXT above it. SQL Server's TEXT type is deprecated; use VARCHAR(MAX) or NVARCHAR(MAX).</p>\n<pre class=\"iq-code\"><code>CREATE TABLE products (\nproduct_id   BIGINT PRIMARY KEY,\ncountry_code CHAR(2) NOT NULL,        -- always exactly 2 characters\nname         VARCHAR(200) NOT NULL,   -- bounded, indexed comfortably\ndescription  TEXT                     -- long free-form text\n);</code></pre>\n<p>In PostgreSQL VARCHAR(n) and TEXT are stored the same way, so the choice is about whether you want the length enforced. MySQL and SQL Server differ: MySQL cannot index a full TEXT column without a prefix length, and SQL Server cannot use a MAX column as an index key. The CHAR detail worth knowing is padding: CHAR(5) stores 'ab' as 'ab   ', and comparisons ignore the trailing spaces.</p>"},{"difficulty":"Medium","question":"What is the difference between a PRIMARY KEY and a UNIQUE constraint?","answer_html":"<p>Both enforce uniqueness. A PRIMARY KEY is the table's identity: at most one per table, implicitly NOT NULL, and usually the target of foreign keys. A table can have several UNIQUE constraints, and they allow NULLs. PostgreSQL, MySQL, SQLite and Oracle accept many NULLs in a UNIQUE column because NULL is not equal to NULL; SQL Server allows only one, unless you use a filtered unique index with WHERE col IS NOT NULL. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT for the opposite behavior.</p>\n<pre class=\"iq-code\"><code>CREATE TABLE customers (\ncustomer_id BIGINT PRIMARY KEY,          -- identity, never business meaning\nemail       VARCHAR(320) NOT NULL UNIQUE, -- business key, still enforced\nname        VARCHAR(200) NOT NULL\n);</code></pre>\n<p>On InnoDB the primary key is always the clustered index, and on SQL Server it is by default, so its width is copied into every secondary index. In PostgreSQL the table is a heap and the primary key is a unique B-tree like any other index.</p>"},{"difficulty":"Medium","question":"How does pagination work, and why is OFFSET slow on deep pages?","answer_html":"<p>LIMIT (or TOP / FETCH FIRST) caps the row count and OFFSET skips rows. The engine still produces and discards the skipped rows, so page 1000 of a 10-row page (OFFSET 9990) reads 10,000 rows to return 10. Keyset pagination seeks straight to the last seen key instead.</p>\n<pre class=\"iq-code\"><code>-- Page by page (fine for the first few pages):\nSELECT order_id, order_date\nFROM orders\nORDER BY order_date DESC, order_id DESC\nLIMIT 10 OFFSET 200;\n\n-- Keyset pagination (fast at any depth):\nSELECT order_id, order_date\nFROM orders\nWHERE (order_date, order_id) &lt; ('2025-06-01', 481516)\nORDER BY order_date DESC, order_id DESC\nLIMIT 10;</code></pre>\n<p>The tiebreaker column makes the sort total, which is the other half of the answer: without it, rows that tie on order_date can repeat or vanish between pages. An index on (order_date, order_id) lets the keyset query seek directly. Row-value comparison works on PostgreSQL, MySQL and SQLite; on SQL Server spell it out as order_date &lt; @d OR (order_date = @d AND order_id &lt; @id). The cost of keyset paging is that you can only go to the next or previous page, not jump to page 37.</p>"},{"difficulty":"Easy","question":"What does the BETWEEN operator do, and what is the classic date bug?","answer_html":"<p>BETWEEN is inclusive on both ends. If order_date is a timestamp rather than a date, <code>'2025-12-31'</code> means midnight at the start of December 31, so <code>BETWEEN '2025-01-01' AND '2025-12-31'</code> silently drops almost the whole last day.</p>\n<pre class=\"iq-code\"><code>-- Bug: misses everything after 2025-12-31 00:00:00:\nSELECT * FROM orders\nWHERE order_date BETWEEN '2025-01-01' AND '2025-12-31';\n\n-- Correct: half-open range:\nSELECT * FROM orders\nWHERE order_date &gt;= '2025-01-01'\nAND order_date &lt; '2026-01-01';</code></pre>\n<p>The half-open range (&gt;= start, &lt; next start) is correct for DATE, timestamp and DATETIME2 columns alike, so it keeps working if someone changes the column type later. Writing '2025-12-31 23:59:59.999' instead is fragile: SQL Server's DATETIME rounds it up to the next day.</p>"},{"difficulty":"Medium","question":"What does ORDER BY guarantee, and why add a tiebreaker?","answer_html":"<p>ORDER BY sorts by the listed expressions; rows that tie on all of them may come back in any order, and that order can change between runs, indexes or parallel plans. SQL does not guarantee stable sorts.</p>\n<pre class=\"iq-code\"><code>-- Ties on total are ordered arbitrarily:\nSELECT order_id, total FROM orders ORDER BY total DESC;\n\n-- Total order, deterministic pagination and deduplication:\nSELECT order_id, total FROM orders ORDER BY total DESC, order_id;</code></pre>\n<p>If a query relies on row order for paging, ranking or deduplication, always add a unique tiebreaker column. The only ordering that exists is the one a final ORDER BY specifies; a SELECT without ORDER BY has no order at all, even if it always looks sorted.</p>"},{"difficulty":"Easy","question":"How does a CASE expression work, and where can it be used?","answer_html":"<p>CASE returns a value from the first matching condition, with an optional ELSE default (NULL if omitted). It is an expression, so it goes anywhere an expression is allowed: the SELECT list, WHERE, ORDER BY, GROUP BY and aggregates.</p>\n<pre class=\"iq-code\"><code>SELECT order_id,\nCASE\nWHEN total &gt;= 500 THEN 'large'\nWHEN total &gt;= 100 THEN 'medium'\nELSE 'small'\nEND AS size_bucket\nFROM orders;</code></pre>\n<p>Conditions are tested in order and the first match wins, which is why the 500 check comes before the 100 check. All branches must return compatible types: mixing a number and a string makes SQL Server try to convert the string and fail at runtime. CASE inside SUM or COUNT is conditional aggregation, which has its own question.</p>"}],"faqs":[{"question":"What SQL dialect are these answers written in?","answer":"Standard SQL where it exists. When a question needs one dialect, such as date truncation or generate_series, the example is PostgreSQL and the answer says so, along with the SQL Server, MySQL and SQLite spelling where it differs."},{"question":"What schema do the worked answers use?","answer":"One small shop schema: customers, orders, order_items and products, plus an employees table with a manager_id for self joins. It is printed at the top of the page so every answer makes sense in context."},{"question":"What difficulty are the basics questions?","answer":"They run from easy warm-ups such as NULL handling to medium questions about the logical order of query evaluation and reliable pagination."},{"question":"Can I practice these instead of reading them?","answer":"Yes. Press Hide answers, next to the question list, and this page becomes a quiz: each answer stays hidden until you reveal it, and a counter tracks how many you have opened. The difficulty buttons narrow the list to easy, medium or hard questions. For a shuffled deck across every topic, use the Practice mode link at the top of the page."}]},"source_url":"https://sqlly.app/sql-interview-questions/basics","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/indexes","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL indexes & performance interview questions","description":"Practice SQL index and query performance interview questions with worked answers: composite index order, covering indexes, sargability and EXPLAIN.","body":{"slug":"indexes","name":"Indexes & performance","h1":"SQL indexes & performance interview questions","lede":"Performance questions test reasoning more than recall: why an index was ignored, what the leftmost-prefix rule buys you, and how to read a plan.","questions":[{"difficulty":"Easy","question":"What is an index, and what does it cost?","answer_html":"<p>An index is a separate structure, usually a B-tree, that maps column values to row locations so lookups avoid scanning the whole table. It speeds reads and slows writes: every INSERT, UPDATE or DELETE on indexed columns must update each index too, and every index consumes storage.</p>\n<pre class=\"iq-code\"><code>CREATE INDEX idx_orders_customer ON orders (customer_id);\n\n-- Now a point lookup probes a few tree levels instead of scanning orders:\nSELECT * FROM orders WHERE customer_id = 42;</code></pre>\n<p>The complete answer names both sides: an index pays for itself only if queries use it often enough to cover the extra cost on every write. Indexes also help ORDER BY (rows come out of the index already sorted), joins (the inner side of a nested loop can seek) and uniqueness checks, not just WHERE filters.</p>"},{"difficulty":"Medium","question":"You have an index on (city, signup_date). Which queries can use it?","answer_html":"<p>A composite B-tree index works on filters and sorts that use a leftmost prefix of its columns. The (city, signup_date) index serves city, city plus a signup_date range, and equality on city plus a sort on signup_date, but not signup_date alone.</p>\n<pre class=\"iq-code\"><code>CREATE INDEX idx_customers_city_date ON customers (city, signup_date);\n\n-- Uses the index:\nSELECT * FROM customers WHERE city = 'Berlin';\nSELECT * FROM customers WHERE city = 'Berlin' AND signup_date &gt;= '2025-01-01';\nSELECT * FROM customers WHERE city = 'Berlin' ORDER BY signup_date;\n\n-- Cannot seek (only a full scan or index scan):\nSELECT * FROM customers WHERE signup_date &gt;= '2025-01-01';</code></pre>\n<p>The design rule that follows: equality columns first, then the range or sort column. A gap in the middle stops the seek; WHERE city = ? AND name = ? with index (city, signup_date, name) can seek on city but must check name on every entry for that city. The modern caveat: Oracle, MySQL 8.0.13+, PostgreSQL 18 and SQLite (once ANALYZE has gathered statistics) have skip scans, which can use the index for signup_date alone by probing once per distinct city. That only pays off when the leading column has few distinct values.</p>"},{"difficulty":"Medium","question":"What does sargable mean? Why does WHERE LOWER(email) = ? ignore the index?","answer_html":"<p>Sargable (from Search ARGument ABLE) describes predicates the engine can answer with an index seek. The index on email is sorted by email, not by LOWER(email), so once the column is wrapped in a function the engine has to compute LOWER for every row and compare.</p>\n<pre class=\"iq-code\"><code>-- users(user_id, email) is a login table, not in the shop schema;\n-- email lookup is where this bites in real code.\n-- Not sargable: function applied to the column\nSELECT * FROM users WHERE LOWER(email) = 'anna@example.com';\n\n-- Sargable, if emails are stored lowercased: normalize the parameter\nSELECT * FROM users WHERE email = 'anna@example.com';\n\n-- If stored case varies, index the expression (PostgreSQL, SQLite, Oracle;\n-- MySQL 8.0.13+ needs ((LOWER(email))), SQL Server an indexed computed column):\nCREATE INDEX idx_users_email_lower ON users (LOWER(email));</code></pre>\n<p>The same rule kills leading-wildcard LIKE: WHERE name LIKE '%son' cannot seek because any value could end in son, while LIKE 'son%' seeks fine. Other common violations: arithmetic on the column (WHERE total * 1.2 &gt; 100 instead of total &gt; 100 / 1.2) and date functions (WHERE YEAR(order_date) = 2025 instead of a half-open date range). On SQL Server and MySQL a case-insensitive collation often makes LOWER unnecessary in the first place. The trap is rewriting the query when the expression index is the better fix; the follow-up is usually \"why not just store emails lowercased?\", which is a legitimate design answer, so say which you would choose and why.</p>"},{"difficulty":"Medium","question":"What is a covering index, and what is an index-only scan?","answer_html":"<p>A covering index contains every column a query needs, so the engine answers it from the index alone and never visits the table. PostgreSQL shows it in EXPLAIN as Index Only Scan; SQL Server shows an index seek with no Key Lookup. The INCLUDE clause adds columns to the leaf level without making them part of the key.</p>\n<pre class=\"iq-code\"><code>-- Query: SELECT order_id, order_date FROM orders WHERE customer_id = 42\n-- SQL Server and PostgreSQL 11+:\nCREATE INDEX idx_orders_covering ON orders (customer_id) INCLUDE (order_id, order_date);\n\n-- MySQL and SQLite have no INCLUDE: put the columns in the key instead\nCREATE INDEX idx_orders_covering ON orders (customer_id, order_date, order_id);</code></pre>\n<p>The tradeoff to state: wide indexes cost more on writes and in storage, so cover the hot queries, not every query. On InnoDB, and on SQL Server when the primary key is clustered, every secondary index already carries the primary key, so order_id is covered for free there. PostgreSQL has its own caveat: an index-only scan still checks the visibility map and visits the table for recently changed pages, so it works best on tables VACUUM keeps up with.</p>"},{"difficulty":"Easy","question":"What is the difference between a clustered and a non-clustered index?","answer_html":"<p>A clustered index dictates the physical order of the table's rows; the table is the index. SQL Server gives each table one clustered index (the primary key by default) and non-clustered indexes point to the clustered key. MySQL InnoDB similarly stores rows in primary-key order. PostgreSQL has no clustered indexes: the table is a heap and every index points into it. Its CLUSTER command reorders the table once but does not maintain that order afterwards.</p>\n<pre class=\"iq-code\"><code>-- SQL Server: non-clustered index pointing into the clustered table\nCREATE NONCLUSTERED INDEX idx_orders_date ON orders (order_date)\nINCLUDE (customer_id, total);</code></pre>\n<p>The practical consequences: in SQL Server and InnoDB, insert patterns that append to the clustered key (an identity PK) are cheap, while random keys (a UUIDv4 PK) cause page splits; and a secondary-index lookup that needs other columns pays a second seek through the clustered key. In PostgreSQL, any index access that is not an index-only scan fetches the row from the heap, so covering indexes matter there too.</p>"},{"difficulty":"Medium","question":"Why can LIKE '%term' not use a B-tree index, and what are the alternatives?","answer_html":"<p>A B-tree orders values lexicographically from the left. A predicate on the prefix (LIKE 'term%') narrows a contiguous range; a leading wildcard (%term) could match anywhere, so no range seek is possible.</p>\n<pre class=\"iq-code\"><code>-- Uses the index:\nSELECT * FROM products WHERE name LIKE 'steel%';\n\n-- Cannot seek: full scan\nSELECT * FROM products WHERE name LIKE '%steel%';\n\n-- PostgreSQL alternative: trigram index for contains-search\nCREATE EXTENSION IF NOT EXISTS pg_trgm;\nCREATE INDEX idx_products_name_trgm ON products USING gin (name gin_trgm_ops);</code></pre>\n<p>A PostgreSQL detail that catches people: under a non-C collation, a plain B-tree index does not serve LIKE 'steel%' at all; you need the index created with text_pattern_ops (or a C collation). The general answer: suffix searches can use an index on the reversed string, contains-searches want full-text or trigram indexes, and on a small table the scan may simply be faster than any index.</p>"},{"difficulty":"Medium","question":"When does an index hurt, and how do you decide whether to keep one?","answer_html":"<p>Indexes cost write throughput: every write touches each index, plus storage and planner overhead from statistics. An index that no query seeks on is pure cost.</p>\n<pre class=\"iq-code\"><code>-- A low-selectivity column rarely helps on its own:\nCREATE INDEX idx_orders_status ON orders (status);   -- 3 distinct values over 10M rows\n\n-- PostgreSQL: indexes that have never been scanned since stats were reset\nSELECT relname, indexrelname, idx_scan\nFROM pg_stat_user_indexes\nWHERE idx_scan = 0;</code></pre>\n<p>An index on status is worth it only for the rare value: if 1% of orders are 'open' and queries look for those, a partial index on just the open rows beats a full one. The decision framework: check actual usage (pg_stat_user_indexes on PostgreSQL, sys.dm_db_index_usage_stats on SQL Server, sys.schema_unused_indexes on MySQL), weigh read patterns against write volume, and prefer a few composite indexes that serve several queries over many single-column ones. Check usage on every replica before dropping: an index unused on the primary may serve the reports on a read replica. The follow-up is usually the recovery story: keep the index DDL in the migration history, capture the usage stats before dropping, and be ready to re-create the index the day a plan regresses.</p>"},{"difficulty":"Hard","question":"What is a partial index, and when is it the right choice?","answer_html":"<p>A partial (filtered) index covers only the rows matching a predicate. It is smaller and cheaper to maintain, and it can serve the hot slice of data precisely.</p>\n<pre class=\"iq-code\"><code>-- Almost every query only looks at open orders, which are 2% of rows:\nCREATE INDEX idx_orders_open ON orders (customer_id)\nWHERE status = 'open';\n\n-- A partial unique index enforces a rule a plain UNIQUE cannot:\n-- carts(customer_id, status) tracks each customer's checkout carts\n-- (not in the shop schema); at most one open cart, any number closed.\nCREATE UNIQUE INDEX ux_carts_one_open ON carts (customer_id)\nWHERE status = 'open';</code></pre>\n<p>The same syntax works on PostgreSQL, SQLite and SQL Server (where it is called a filtered index); MySQL and Oracle have no partial indexes. The planner uses one only when the query's WHERE clause implies the index predicate, so WHERE customer_id = ? AND status = 'open' matches. On SQL Server that has to be provable at compile time: a parameterized status = @s will not use the filtered index unless the plan is compiled for the literal value. The follow-up is usually how you would enforce the one-open-cart rule on MySQL anyway, since it has no partial index: a unique index over a null-when-closed expression, CASE WHEN status = 'open' THEN customer_id END, works because a UNIQUE index permits any number of NULLs.</p>"},{"difficulty":"Medium","question":"How do you read an EXPLAIN plan? What are the red flags?","answer_html":"<p>Read it from the deepest nodes up: each node is an operation, the numbers are estimated rows and cost, and the top node is the final step. The first question is always access method: index seek or scan versus a sequential scan of the whole table.</p>\n<pre class=\"iq-code\"><code>EXPLAIN ANALYZE\nSELECT c.name, SUM(o.total)\nFROM customers c JOIN orders o ON o.customer_id = c.customer_id\nWHERE o.order_date &gt;= '2025-01-01'\nGROUP BY c.customer_id, c.name;\n\n-- Red flags: Seq Scan on orders with a highly selective filter,\n-- estimated rows far off from actual rows (stale statistics),\n-- Nested Loop over millions of rows, and Sort spilling to disk.</code></pre>\n<p>EXPLAIN ANALYZE (PostgreSQL, MySQL 8.0.18+) actually runs the query, so wrap data-changing statements in a transaction you roll back. It shows real rows next to the estimates, and a gap of 10x or more points at stale statistics or correlated columns the planner treats as independent. SQL Server's equivalent is the actual execution plan. Then say what you would do: ANALYZE (or UPDATE STATISTICS) the table, add or widen an index for the filter, or rewrite the query. The wrong answer is reciting red flags without naming the fix; a plan you cannot act on is just criticism. The follow-up is almost always estimates versus actual rows: how far off was the guess, and which choice did the bad guess make for the optimizer.</p>"},{"difficulty":"Hard","question":"The optimizer is ignoring your index. What are the likely causes?","answer_html":"<p>Usual suspects, roughly in order: the predicate is not sargable (function or leading wildcard on the column); the query matches too many rows for a seek to beat a scan (low selectivity); statistics are stale so the estimates lie; type mismatch or implicit conversion (comparing varchar column to an int parameter); OR branches on different columns with no composite index; and optimizer hints or settings forcing another plan.</p>\n<pre class=\"iq-code\"><code>-- Type mismatch: customers.phone is VARCHAR, the value is a number.\n-- MySQL converts every phone to a number to compare, so no index seek:\nSELECT * FROM customers WHERE phone = 5551234;\n\n-- Compare like with like:\nSELECT * FROM customers WHERE phone = '5551234';</code></pre>\n<p>The direction of the mismatch matters: the column is what gets converted, so a string column compared to a number loses its index, while a number column compared to a quoted literal is usually fine because the literal is converted once. SQL Server's version is a VARCHAR column compared to an NVARCHAR parameter, which most .NET drivers send by default; under a SQL_ collation the column is converted row by row and the seek becomes a scan. Structure the answer as checklist then measurement: check sargability and types, check selectivity, refresh statistics, and compare the plan before and after.</p>"},{"difficulty":"Medium","question":"Why do foreign keys need their own indexes, and what breaks without them?","answer_html":"<p>A foreign key constraint checks the parent on writes, but deleting or updating a parent row must find referencing children, and without an index on the child column that is a full scan per parent write.</p>\n<pre class=\"iq-code\"><code>-- The FK enforces integrity but creates no index on most engines\n-- (SQL Server, PostgreSQL, Oracle and SQLite do not auto-index the child side):\nCREATE TABLE orders (\norder_id    BIGINT PRIMARY KEY,\ncustomer_id BIGINT REFERENCES customers(customer_id)\n);\n\n-- Add it yourself:\nCREATE INDEX idx_orders_customer ON orders (customer_id);</code></pre>\n<p>The cascading failure story: DELETE on customers slows to a scan of orders per row, the delete transaction holds locks longer, and everything behind it queues. MySQL InnoDB is the exception: it requires an index on the foreign key column and creates one if none exists. On Oracle an unindexed foreign key is worse still, because a parent delete or key update locks the whole child table. Join performance on the FK column is the second benefit, but the delete-path check is the reason that surprises people. The trap is answering \"the database creates that index for me\": InnoDB does, and PostgreSQL, SQL Server, Oracle and SQLite do not. The follow-up is usually to describe the production symptom you would see without it, which is the cascading delete story above.</p>"},{"difficulty":"Medium","question":"Why is SELECT * discouraged, beyond style?","answer_html":"<p>Three concrete costs: it defeats covering indexes, because the engine must fetch every column from the table; it ships bytes you discard, such as wide TEXT or JSON columns sent over the network; and it couples code to the schema, so adding, dropping or reordering a column changes every result set that consumed it.</p>\n<pre class=\"iq-code\"><code>-- Needs customer_id, order_id and order_date, which a covering index can hold:\nSELECT order_id, order_date FROM orders WHERE customer_id = 42;\n\n-- SELECT * forces a heap fetch for every column, every time:\nSELECT * FROM orders WHERE customer_id = 42;</code></pre>\n<p>The caveat: SELECT * is fine for ad-hoc exploration and inside EXISTS. The discipline belongs in application code, views and reports. In a view it has a specific trap: on SQL Server and PostgreSQL the * is expanded when the view is created, so columns added to the table later do not appear in the view until it is recreated.</p>"},{"difficulty":"Medium","question":"What do cost and rows in a plan actually measure, and how do they mislead?","answer_html":"<p>Cost is the optimizer's model of work: page reads, comparisons and a penalty for spilling, expressed in each engine's own units. Rows is the planner's guess at how many rows the step returns. Neither is a measurement, and the two most common misreadings are treating cost as milliseconds and treating rows as fact.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL: cost is in abstract units, roughly page fetches,\n-- and the pair is startup cost..total cost:\nEXPLAIN SELECT * FROM orders WHERE customer_id = 42;\n-- Index Scan using idx_orders_customer on orders (cost=0.43..8.45 rows=1)\n\n-- MySQL's tabular EXPLAIN has no cost column at all, only estimated rows;\n-- the number hides in EXPLAIN FORMAT=JSON. SQL Server shows an estimated\n-- subtree cost in its own units, next to estimated rows.</code></pre>\n<p>The mis-signals to name: the plan with the higher cost can be the faster one, because the model cannot see your cache, your parallelism or how stale the statistics are, so \"the other plan had a lower number\" is not an argument. The trap is tuning to the estimate instead of the measurement; the follow-up is always EXPLAIN ANALYZE (PostgreSQL, MySQL 8.0.18+) or the actual plan in SQL Server, where cost stays a guess but rows become facts.</p>"},{"difficulty":"Medium","question":"How do you spot a bad row estimate in a plan, and what fixes it?","answer_html":"<p>Compare estimated rows against actual rows at each node, which means running the plan with actuals: EXPLAIN ANALYZE on PostgreSQL and MySQL, the actual execution plan on SQL Server. The signature is a node estimating a handful of rows and producing thousands, and the reason it matters is that the estimate, not the reality, chose the join algorithm and sized the memory grant.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL prints both, and the gap is the diagnosis:\nEXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;\n-- Index Scan using idx_orders_customer on orders\n--   (cost=0.43..8.45 rows=1 width=40)\n--   (actual time=0.030..0.290 rows=120 loops=1)   -- 120x off\n\n-- The first fix is usually fresh statistics:\nANALYZE orders;   -- SQL Server: UPDATE STATISTICS orders</code></pre>\n<p>Usual causes in the order to check them: statistics never refreshed after a bulk load, correlated columns the planner multiplies as if independent (PostgreSQL 10+ can declare extended statistics with CREATE STATISTICS), values the planner could not see at plan time (SQL Server parameter sniffing, PL/pgSQL variables), and columns wrapped in functions. The trap is treating the mismatch as cosmetic; the follow-up is naming which decision the bad estimate corrupted, usually a nested loop standing in for a hash join, and fixing the estimate before touching the query.</p>"},{"difficulty":"Hard","question":"What do the join algorithms in a plan tell you, and what should each choice make you check?","answer_html":"<p>Three algorithms cover almost every plan. A nested loop probes the inner side once per outer row: right for a small outer input over an indexed inner side, terrible when both sides are large. A hash join builds a hash table on the smaller input and probes it with the larger: the choice for big unsorted inputs, and it needs the memory grant to keep the table in memory. A merge join walks two sorted inputs in lockstep: efficient at scale, but only when the inputs are sorted already or cheap to sort.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL and SQL Server plan vocabulary:\n-- Nested Loop  -- small outer row count, index seek on the inner side\n-- Hash Join    -- both sides large; check the memory grant and spills\n-- Merge Join   -- sorted inputs; a Sort node on top means the sort is the plan\n\n-- MySQL's tabular EXPLAIN names no algorithm; since MySQL 8.0.18 an\n-- equi-join over large inputs runs as a hash join where older versions looped.</code></pre>\n<p>What each choice should make you check: a nested loop wants you to look at the outer row estimate, because a 10-row estimate that returns 100,000 is why the loop is slow; a hash join wants the spill check (SQL Server's hash warning event, PostgreSQL printing Batches above 1); a merge join wants to know whether a sort was added just to feed it. The trap is naming algorithms without the checks; the follow-up is usually how you would fix a nested loop over millions of rows, and the answer is the estimate or the missing index, not a hint first.</p>"}],"faqs":[{"question":"Do I need to know a specific database for these?","answer":"No. The reasoning is engine-agnostic: B-trees, selectivity and the leftmost-prefix rule work the same on SQL Server, PostgreSQL, MySQL and SQLite, and the answers note engine-specific names where they differ."},{"question":"What does sargable mean, and is it covered?","answer":"Yes, with the two classic violations: wrapping an indexed column in a function, and leading-wildcard LIKE searches. Both show the rewrite that lets the index work again."},{"question":"Are EXPLAIN plans covered?","answer":"Four questions walk the whole path: reading a plan and its red flags, what cost and row estimates actually measure, diagnosing bad row estimates against actuals, and what the choice of join algorithm signals. Estimates versus actual rows is the thread through all of them."},{"question":"Is there a question about when indexes hurt?","answer":"Yes: write amplification on insert-heavy tables, indexes that never get used, and why every index is a bet that some query is worth slowing writes down for."}]},"source_url":"https://sqlly.app/sql-interview-questions/indexes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/joins","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL joins interview questions","description":"Practice SQL join interview questions with worked answers: INNER and LEFT JOIN, anti-joins, self joins, join fan-out mistakes and LATERAL top-n queries.","body":{"slug":"joins","name":"SQL joins","h1":"SQL joins interview questions","lede":"Joins are where interviewers separate people who have read about SQL from people who have written it. Every answer uses the shop schema below.","questions":[{"difficulty":"Easy","question":"What is the difference between an INNER JOIN and a LEFT JOIN?","answer_html":"<p>INNER JOIN keeps only rows with a match on both sides. LEFT JOIN keeps every row of the left table; unmatched right-side columns come back NULL.</p>\n<pre class=\"iq-code\"><code>-- Only customers who have ordered:\nSELECT c.name, o.order_id, o.total\nFROM customers c\nINNER JOIN orders o ON o.customer_id = c.customer_id;\n\n-- Every customer; orders columns are NULL when they never ordered:\nSELECT c.name, o.order_id, o.total\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.customer_id;</code></pre>\n<p>The classic check: with a LEFT JOIN, columns from the right table can be NULL either because there was no match or because the stored value is NULL. COALESCE only fixes the display; it does not tell you which happened.</p>"},{"difficulty":"Easy","question":"Write a query that returns each customer and their order count, including customers with zero orders.","answer_html":"<p>LEFT JOIN plus COUNT of the right table's key. Counting the right table's column is the whole trick, because COUNT(*) counts the NULL-extended rows too.</p>\n<pre class=\"iq-code\"><code>SELECT c.name, COUNT(o.order_id) AS order_count\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.customer_id, c.name\nORDER BY order_count DESC;</code></pre>\n<p>With COUNT(*), a customer with no orders shows 1 instead of 0, because the LEFT JOIN produced one row for them with NULLs. The interview is really checking whether you know which column to count.</p>"},{"difficulty":"Medium","question":"What is join fan-out, and how does it corrupt aggregates?","answer_html":"<p>Fan-out happens when one row of a table matches several rows on the other side, so joined output has more rows than either input. Aggregates then double- or triple-count.</p>\n<pre class=\"iq-code\"><code>-- Each order has several order_items; joining then summing\n-- counts each order total once per item line:\nSELECT SUM(o.total) AS wrong_revenue      -- inflated\nFROM orders o\nJOIN order_items oi ON oi.order_id = o.order_id;\n\n-- Correct: collapse order_items to one row per order, then join:\nSELECT SUM(o.total) AS revenue, SUM(i.lines) AS item_lines\nFROM orders o\nJOIN (\nSELECT order_id, COUNT(*) AS lines\nFROM order_items\nGROUP BY order_id\n) i ON i.order_id = o.order_id;</code></pre>\n<p>An order worth 100 with three item lines contributes 300 to the first query. Name the two fixes: aggregate the many side down to the grain of the one side before joining, or aggregate each table separately and join the results. SUM(DISTINCT o.total) is the tempting patch and it is wrong too: two different orders that both total 100 collapse into one.</p>"},{"difficulty":"Medium","question":"How do you find rows in one table with no match in another (an anti-join)?","answer_html":"<p>Two idiomatic ways. LEFT JOIN with IS NULL is the classic; NOT EXISTS states the intent directly. Both handle NULLs correctly, and PostgreSQL, SQL Server and MySQL 8.0.17+ usually plan them as the same anti-join.</p>\n<pre class=\"iq-code\"><code>-- Customers who never ordered (LEFT JOIN anti-join):\nSELECT c.customer_id, c.name\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.customer_id\nWHERE o.order_id IS NULL;            -- test a column that is never NULL in a real match\n\n-- Same result, usually the better answer:\nSELECT c.customer_id, c.name\nFROM customers c\nWHERE NOT EXISTS (\nSELECT 1 FROM orders o WHERE o.customer_id = c.customer_id\n);</code></pre>\n<p>NOT IN is the trap: if the subquery returns even one NULL, NOT IN returns no rows at all, because x NOT IN (1, NULL) can never be proven true. Mentioning that unprompted is the senior signal in this question.</p>"},{"difficulty":"Medium","question":"What does a FULL OUTER JOIN do, and when would you use it?","answer_html":"<p>It keeps every row from both sides, matching where it can and filling NULLs where it cannot. Use it when comparing two datasets that should mirror each other, such as reconciling a source and a target table.</p>\n<pre class=\"iq-code\"><code>SELECT COALESCE(s.id, t.id) AS id, s.balance AS source_balance, t.balance AS target_balance\nFROM source_balances s\nFULL OUTER JOIN target_balances t ON t.id = s.id\nWHERE s.id IS NULL OR t.id IS NULL       -- mismatches only\nOR s.balance &lt;&gt; t.balance;</code></pre>\n<p>A matched row where only one side's balance is NULL slips past the &lt;&gt; test, because comparing with NULL is unknown rather than true; s.balance IS DISTINCT FROM t.balance (PostgreSQL, SQLite, SQL Server 2022+; NOT (a &lt;=&gt; b) on MySQL) closes that gap. MySQL has no FULL OUTER JOIN, and SQLite only gained it in 3.39, which is the usual follow-up: emulate it with a LEFT JOIN unioned with a RIGHT JOIN, as the last question on this page shows.</p>"},{"difficulty":"Easy","question":"What is a CROSS JOIN, and what is a legitimate use?","answer_html":"<p>A CROSS JOIN is every row paired with every row (a Cartesian product). n rows times m rows produces n times m rows, usually by accident through a forgotten join condition.</p>\n<pre class=\"iq-code\"><code>-- Legitimate: build every day and product combination,\n-- then left join actual sales onto that grid (PostgreSQL):\nSELECT d.day, p.product_id, COALESCE(s.units, 0) AS units\nFROM (\nSELECT g::date AS day\nFROM generate_series(DATE '2025-01-01', DATE '2025-01-31', INTERVAL '1 day') AS g\n) d\nCROSS JOIN products p\nLEFT JOIN sales s ON s.day = d.day AND s.product_id = p.product_id;</code></pre>\n<p>CROSS JOIN is right when you need the complete grid of combinations, so that a product with no sales on a day shows 0 instead of having no row. Other engines build the calendar with a recursive CTE or a calendar table instead of generate_series. An accidental Cartesian product usually comes from an old-style comma join with a missing WHERE condition, and the symptom is a row count equal to the product of the two table sizes.</p>"},{"difficulty":"Medium","question":"What is a self join, and how do you list each employee with their manager?","answer_html":"<p>A self join joins a table to itself under two aliases. With employees.manager_id referencing employees.employee_id:</p>\n<pre class=\"iq-code\"><code>SELECT e.name AS employee,\nm.name AS manager\nFROM employees e\nLEFT JOIN employees m ON m.employee_id = e.manager_id\nORDER BY e.name;</code></pre>\n<p>It is a LEFT JOIN so the CEO, whose manager_id is NULL, still appears. The follow-up is usually how to get the whole reporting chain, which needs a recursive CTE rather than a fixed number of self joins.</p>"},{"difficulty":"Medium","question":"What changes when you move a filter from the ON clause to WHERE in a LEFT JOIN?","answer_html":"<p>For INNER JOINs nothing changes: ON and WHERE are logically equivalent. For LEFT JOINs it matters enormously, because WHERE runs after the join and its NULL-extended rows.</p>\n<pre class=\"iq-code\"><code>-- Keeps all customers, counts only delivered orders:\nSELECT c.name, COUNT(o.order_id) AS delivered\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.customer_id\n      AND o.status = 'delivered'\nGROUP BY c.customer_id, c.name;\n\n-- Turns the LEFT JOIN into an INNER JOIN effectively:\nSELECT c.name, COUNT(o.order_id) AS delivered\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.customer_id\nWHERE o.status = 'delivered'          -- kills the NULL rows\nGROUP BY c.customer_id, c.name;</code></pre>\n<p>The rule to state: filters on the right (nullable) side go in ON if you want to keep unmatched left rows; WHERE is for filters on the left side or when you genuinely want the inner-join behavior.</p>"},{"difficulty":"Easy","question":"What happens when you join on a key that has duplicates on either side?","answer_html":"<p>Every matching pair produces a row. If the left key has n duplicates and the right has m, that key contributes n times m rows. Duplicates on one side multiply the other side's rows.</p>\n<pre class=\"iq-code\"><code>-- If customers had two rows for customer_id = 7 and orders has\n-- three orders for that customer, the join returns 6 rows for them:\nSELECT *\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id;</code></pre>\n<p>The defense is uniqueness, not hope: primary keys on the one side, and checking for duplicates with GROUP BY ... HAVING COUNT(*) &gt; 1 when you inherit a schema. Fan-out plus aggregation is how double-counting bugs reach dashboards.</p>"},{"difficulty":"Medium","question":"How do you join a table to an aggregate of another table without fan-out?","answer_html":"<p>Aggregate first, then join the aggregate. Joining raw rows first and grouping afterwards works too, but only if you aggregate the right grain; the pre-aggregated join makes the intent explicit and the plan cheaper.</p>\n<pre class=\"iq-code\"><code>SELECT c.name, agg.total_spent\nFROM customers c\nJOIN (\nSELECT customer_id, SUM(total) AS total_spent\nFROM orders\nGROUP BY customer_id\n) agg ON agg.customer_id = c.customer_id;</code></pre>\n<p>The window-function alternative keeps every order row and attaches each customer's total alongside, without collapsing rows: SUM(total) OVER (PARTITION BY customer_id). Say when each is right: pre-aggregated join when you want one row per customer, the window when you still need order-level rows.</p>"},{"difficulty":"Hard","question":"How do you get the top three orders per customer?","answer_html":"<p>Window functions or a correlated LATERAL join. The window version numbers every order and then throws most of them away; the LATERAL version runs a small query per customer that can stop after three rows when an index on (customer_id, total) supports it. Many customers with few orders each favors the window; few customers with long histories favors LATERAL.</p>\n<pre class=\"iq-code\"><code>-- ROW_NUMBER: rank within each customer, then filter outside:\nSELECT customer_id, order_id, total\nFROM (\nSELECT o.*,\nROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY total DESC) AS rn\nFROM orders o\n) ranked\nWHERE rn &lt;= 3;\n\n-- LATERAL (PostgreSQL, MySQL 8.0.14+). Oracle 12c+ has LATERAL too but writes\n-- FETCH FIRST 3 ROWS ONLY; SQL Server spells it CROSS APPLY with TOP (3):\nSELECT c.name, top_orders.order_id, top_orders.total\nFROM customers c\nCROSS JOIN LATERAL (\nSELECT o.order_id, o.total\nFROM orders o\nWHERE o.customer_id = c.customer_id\nORDER BY o.total DESC\nLIMIT 3\n) top_orders;</code></pre>\n<p>The nuance worth adding: ROW_NUMBER breaks ties arbitrarily, RANK gives ties the same rank and skips the next, DENSE_RANK skips nothing. Choose deliberately. The WHERE rn &lt;= 3 must sit outside the subquery because window functions cannot appear in WHERE.</p>"},{"difficulty":"Hard","question":"How do you emulate a FULL OUTER JOIN in MySQL?","answer_html":"<p>Union a LEFT JOIN with a RIGHT JOIN, and keep rows from the second query only where the left side had no match. That WHERE clause is what prevents duplicates, which is why UNION ALL is safe here.</p>\n<pre class=\"iq-code\"><code>SELECT s.id, s.balance AS source_balance, t.balance AS target_balance\nFROM source_balances s\nLEFT JOIN target_balances t ON t.id = s.id\nUNION ALL\nSELECT t.id, s.balance, t.balance\nFROM source_balances s\nRIGHT JOIN target_balances t ON t.id = s.id\nWHERE s.id IS NULL;</code></pre>\n<p>The first half returns every source row, matched or not. The second half returns only target rows with no source match. Note the second branch selects t.id: s.id is NULL on exactly those rows, so selecting it would print an id of NULL. Plain UNION instead of UNION ALL plus the filter also looks right, but it silently merges genuinely duplicate rows.</p>"}],"faqs":[{"question":"Which join types do these questions cover?","answer":"INNER, LEFT and FULL OUTER joins, CROSS JOIN, self joins, anti-joins, and correlated LATERAL joins for top-n-per-group problems."},{"question":"What is the hardest question here?","answer":"The top three orders per customer with LATERAL, and simulating a FULL OUTER JOIN in engines that do not have one. Both come up regularly in senior interviews."},{"question":"Do the answers explain the classic LEFT JOIN mistakes?","answer":"Yes: rows duplicated by join fan-out, filters drifting from ON to WHERE and changing the result, and counting the wrong column so zero-order customers disappear."},{"question":"Is there a way to test myself on these?","answer":"Press Hide answers next to the question list: every answer collapses behind a Show answer button and a counter tracks how many you have opened. Practice mode, linked at the top, deals a shuffled deck from all eight topics instead."}]},"source_url":"https://sqlly.app/sql-interview-questions/joins","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/schema-design","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL schema design & normalization interview questions","description":"Practice database design interview questions with worked answers: 1NF 2NF and 3NF, surrogate vs natural keys, many-to-many tables and denormalization.","body":{"slug":"schema-design","name":"Schema design & normalization","h1":"SQL schema design & normalization interview questions","lede":"Design questions have no single right answer, which is exactly why interviewers ask them. Each answer gives the standard solution and its tradeoffs.","questions":[{"difficulty":"Easy","question":"What is first normal form (1NF)?","answer_html":"<p>Every column holds a single atomic value, and rows are unique. No comma-separated lists in a cell, no repeating column groups like phone1, phone2, phone3.</p>\n<pre class=\"iq-code\"><code>-- Violates 1NF:\norders(order_id, product_names TEXT)  -- \"widget, gadget, sprocket\"\n\n-- In 1NF:\norders(order_id, ...)\norder_items(order_id, product_id, quantity)</code></pre>\n<p>The reason it matters beyond theory: a comma-separated list cannot be joined, indexed or constrained, and every query that needs one product must parse text. The repeating-columns version cannot be extended without ALTER TABLE. The fix is a child table, which is also the answer to the many-to-many question.</p>"},{"difficulty":"Medium","question":"Explain second and third normal form with a concrete example.","answer_html":"<p>2NF: every non-key column depends on the whole key, not part of it. 3NF: every non-key column depends on the key and nothing else, so no non-key column determines another one. One example of each:</p>\n<pre class=\"iq-code\"><code>-- Violates 2NF: key is (order_id, product_id)\norder_items(order_id, product_id, quantity,\nproduct_name)          -- depends on product_id alone, part of the key\n\n-- Violates 3NF: key is order_id\norders(order_id, customer_id,\ncustomer_city)         -- depends on customer_id, a non-key column</code></pre>\n<pre class=\"iq-code\"><code>-- Decomposed:\nproducts(product_id, product_name)\norders(order_id, customer_id)\ncustomers(customer_id, city)\norder_items(order_id, product_id, quantity)</code></pre>\n<p>2NF can only be violated when the key is composite; 3NF removes transitive dependencies (order_id determines customer_id, which determines city). The damage is the same in both cases: one fact is stored in many rows, so renaming a product or moving a customer means updating all of them, and missing one leaves the rows disagreeing. The trap is the transitive dependency dressed up as convenience: customer_city arrives on orders as \"we just want the city on the invoice\", and accepting that wording is how the update anomaly gets designed in. The wrong answer is patching the inconsistency in code with triggers; the fix is the decomposition, and the join back is cheap.</p>"},{"difficulty":"Easy","question":"Surrogate keys or natural keys: how do you choose?","answer_html":"<p>A surrogate key has no business meaning (an identity or sequence bigint, or a UUID); a natural key comes from the data itself (email, ISBN, country code). The practical rule: surrogate primary key for stability, UNIQUE constraint on the natural key for correctness.</p>\n<pre class=\"iq-code\"><code>CREATE TABLE users (\nuser_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\nemail   VARCHAR(320) NOT NULL UNIQUE      -- natural key, still enforced\n);</code></pre>\n<p>The reasons for surrogates: business keys change (an email update would cascade through every FK), they are narrow (a 4-byte or 8-byte FK beats a 320-character one in every child index), and nothing real is guaranteed immutable. The reason to keep the natural key as UNIQUE: without it, the surrogate hides duplicate real rows.</p>"},{"difficulty":"Medium","question":"How do you model a many-to-many relationship?","answer_html":"<p>A junction (bridge) table holding both primary keys, usually with a composite key of the pair, and foreign keys to both sides.</p>\n<pre class=\"iq-code\"><code>CREATE TABLE order_items (\norder_id    BIGINT REFERENCES orders(order_id),\nproduct_id  BIGINT REFERENCES products(product_id),\nquantity    INT NOT NULL,\nunit_price  NUMERIC(10,2) NOT NULL,\nPRIMARY KEY (order_id, product_id)\n);</code></pre>\n<p>The follow-up: relationship attributes such as quantity belong on the junction row, not on either endpoint. If the same product can appear on two lines of one order (say, at different prices), the composite key is too strict and you need a line number in the key or a surrogate key. A rule like every order must have at least one item cannot be expressed with foreign keys alone; it needs application logic, a trigger or a deferred check.</p>"},{"difficulty":"Medium","question":"How do you model an employee manager relationship in the same table?","answer_html":"<p>A self-referencing foreign key: manager_id points at the same table's primary key, nullable for the top of the hierarchy.</p>\n<pre class=\"iq-code\"><code>CREATE TABLE employees (\nemployee_id BIGINT PRIMARY KEY,\nname        VARCHAR(200) NOT NULL,\nmanager_id  BIGINT REFERENCES employees(employee_id)   -- NULL = CEO\n);</code></pre>\n<p>The follow-ups to expect: reading the whole chain needs a recursive CTE; deleting a manager who has reports is either blocked (the default) or, with ON DELETE SET NULL, leaves the reports without a manager, so reassigning them belongs in the delete path; and cycles. A CHECK (manager_id &lt;&gt; employee_id) blocks the one-step loop of an employee managing themselves, but A manages B, B manages A passes every constraint; catching that needs a trigger or application check that walks the chain before the update.</p>"},{"difficulty":"Medium","question":"When is denormalization justified?","answer_html":"<p>When reads dominate writes and the join or aggregation cost is measurable: reporting tables, dashboards, counters, and data spread across services. Denormalization trades update-anomaly risk for read speed, so it must come with a maintenance path.</p>\n<pre class=\"iq-code\"><code>-- Normalized source of truth:\norders(order_id, customer_id, total, ...)\n\n-- Denormalized read model:\ncustomer_stats(customer_id, order_count, lifetime_value)  -- refreshed on write or on schedule</code></pre>\n<p>The disciplined answer: normalize first, denormalize specific paths after measuring, and state the sync strategy (trigger, transactional outbox, or scheduled rebuild) plus the staleness tolerance. Denormalizing up front adds sync code before anyone knows which reads are slow; refusing to denormalize while a dashboard aggregates 500M rows on every page load is the opposite mistake.</p>"},{"difficulty":"Hard","question":"How would you store hierarchical data? Compare adjacency list, nested sets and closure table.","answer_html":"<p>Adjacency list (each row points at its parent) is simple and cheap to write; reading a whole subtree needs a recursive CTE, which every modern engine has. Nested sets (each node stores left and right bounds) reads whole subtrees in one query but makes every insert or move rewrite half the table. A closure table (one row per ancestor-descendant pair) answers subtree and ancestor queries with a plain join, and inserting a leaf is cheap, at the cost of one row per ancestor for every node; moving a subtree means deleting and reinserting many path rows.</p>\n<pre class=\"iq-code\"><code>-- Adjacency list: the default choice today\ncategories(category_id, name, parent_id REFERENCES categories)\n\n-- Closure table: fast subtree queries at any depth\ncategory_paths(ancestor_id, descendant_id, depth)</code></pre>\n<p>The senior answer starts with an adjacency list plus recursive CTEs and reaches for the others only when measurements say so: nested sets for trees that almost never change, a closure table when subtree queries are the hot path and moves are rare. The fourth option is a materialized path, storing the lineage as text such as '/1/7/42/', which makes subtree queries a prefix LIKE; PostgreSQL's ltree type and SQL Server's hierarchyid are built-in versions of it.</p>"},{"difficulty":"Medium","question":"When should a column be NULLable, and what are the tradeoffs?","answer_html":"<p>NULL means unknown or not applicable, and every NULLable column spreads three-valued logic through every query that touches it. Make a column NOT NULL by default and nullable only when absence is a real state of the world.</p>\n<pre class=\"iq-code\"><code>CREATE TABLE customers (\nemail           VARCHAR(320) NOT NULL,        -- every customer has one\nmiddle_name     VARCHAR(200),                 -- genuinely optional\ndeleted_at      TIMESTAMPTZ                   -- NULL = not deleted (soft delete)\n);</code></pre>\n<p>The costs to name: NULL defeats = comparisons, breaks NOT IN, needs COALESCE or IS NOT NULL everywhere, and makes aggregates silently skip rows. When NULL could mean two different things (not yet known versus not applicable), use a separate column or a status value so the meaning is explicit. Defaulting every optional field to empty string is the opposite mistake, since empty string and unknown become indistinguishable.</p>"},{"difficulty":"Medium","question":"How do you model a one-to-one relationship?","answer_html":"<p>Put the foreign key on the optional side with a UNIQUE constraint, or split a wide table when a subset of columns is rarely read or has different access permissions.</p>\n<pre class=\"iq-code\"><code>-- users(user_id, email) and its profile table; neither is in the shop schema.\nCREATE TABLE users (\nuser_id     BIGINT PRIMARY KEY,\nemail       VARCHAR(320) NOT NULL\n);\n\n-- At most one profile per user: user_id is both the PK and the FK\nCREATE TABLE user_profiles (\nuser_id     BIGINT PRIMARY KEY REFERENCES users(user_id),\nbio         TEXT,\navatar_url  VARCHAR(500)\n);</code></pre>\n<p>The reasons to split: the profile columns are large, read rarely, or need different permissions. Making the child's primary key also its foreign key allows at most one profile per user; a separate profile_id key plus a UNIQUE constraint on user_id says the same thing. The wrong answer is a separate profile_id key with no UNIQUE on user_id, which silently allows many profiles per user; naming the PK-as-FK trick is what this question is fishing for. Strictly this is one-to-zero-or-one: forcing every user to have a profile needs a deferred constraint or application logic, since one of the two rows has to be inserted first. The follow-up is usually why not just put the profile columns on users, and the answer is the split reasons: row width, access patterns and permissions.</p>"},{"difficulty":"Hard","question":"How do you store data that changes over time (temporal / versioned data)?","answer_html":"<p>Validity ranges: add valid_from and valid_to to the rows that represent history, with an open end for the current row, and on PostgreSQL enforce non-overlap with an exclusion constraint.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL; btree_gist lets the GiST index handle product_id WITH =\nCREATE EXTENSION IF NOT EXISTS btree_gist;\n\nCREATE TABLE product_prices (\nproduct_id BIGINT REFERENCES products(product_id),\nprice      NUMERIC(10,2) NOT NULL,\nvalid_from TIMESTAMPTZ NOT NULL,\nvalid_to   TIMESTAMPTZ NOT NULL DEFAULT 'infinity',\nCONSTRAINT no_overlap EXCLUDE USING gist (\nproduct_id WITH =, tstzrange(valid_from, valid_to) WITH &amp;&amp;\n)\n);\n\n-- Price of a product as it was on a given date:\nSELECT price FROM product_prices\nWHERE product_id = 42\nAND '2025-03-15' &gt;= valid_from AND '2025-03-15' &lt; valid_to;</code></pre>\n<p>The discipline: half-open ranges [from, to) so one row's end can equal the next row's start without overlapping; a current-price view filters valid_to = 'infinity'; and a price change never overwrites, it closes the old row and inserts a new one in one transaction. PostgreSQL 18 can declare the same rule as a temporal key, PRIMARY KEY (product_id, valid_period WITHOUT OVERLAPS) on a range column. On engines without either, overlap prevention moves to triggers or serialized transactions. Also worth naming: SQL:2011 system-versioned tables (SQL Server 2016+, MariaDB 10.3+), where the engine records every row's history automatically. They track when the database knew a fact, which is a different question from when a price was valid.</p>"},{"difficulty":"Medium","question":"What is the EAV pattern, and why is it dangerous?","answer_html":"<p>Entity-attribute-value stores the schema as data: instead of one column per attribute, every attribute becomes a row of (entity_id, attribute, value). Users can add fields without a schema change, and almost everything else gets harder.</p>\n<pre class=\"iq-code\"><code>-- EAV:\nentity_values(entity_id, attribute, value)\n-- (42, 'price', '19.99'): a number stored as text, cast back on every read\n\n-- Versus typed columns:\nproducts(product_id, price NUMERIC, weight_kg NUMERIC, color VARCHAR)</code></pre>\n<p>The costs to enumerate: no column types or constraints (everything is TEXT), every query is a pivot or a chain of self-joins, the planner has no statistics per attribute, and NOT NULL or FK rules are unenforceable. When user-defined attributes are a genuine requirement, JSONB (PostgreSQL) or JSON columns with generated columns and indexes over the hot attributes give the flexibility with types attached. EAV survives in clinical and CMS systems where the attribute set is open-ended and defined by users; even there, the cost shows up in every report.</p>"},{"difficulty":"Medium","question":"How much integrity should live in the schema versus the application?","answer_html":"<p>Push what the engine can enforce into the schema: primary keys, foreign keys, UNIQUE, NOT NULL, CHECK and (where supported) exclusion constraints. The engine enforces them for every writer and every transaction; application code enforces them only on the paths where someone remembered to.</p>\n<pre class=\"iq-code\"><code>CREATE TABLE order_items (\norder_id   BIGINT NOT NULL REFERENCES orders(order_id),\nproduct_id BIGINT NOT NULL REFERENCES products(product_id),\nquantity   INT    NOT NULL CHECK (quantity &gt; 0),\nunit_price NUMERIC(10,2) NOT NULL CHECK (unit_price &gt;= 0),\nPRIMARY KEY (order_id, product_id)\n);</code></pre>\n<p>What belongs in the application: cross-table business rules the schema cannot express (an order limit per customer tier), user-facing validation with good error messages, and anything needing external systems. The point that lands well: batch jobs, migrations, a second service and someone's manual UPDATE all bypass your application code, but none of them bypass the constraint. Application checks also race: two requests can both check that an email is free and both insert it, and only a UNIQUE constraint stops the second one. Checking in both layers is normal, the application for friendly error messages and the schema for the guarantee.</p>"}],"faqs":[{"question":"Which normal forms do these questions cover?","answer":"First, second and third normal form, each with a concrete table that violates the form and the decomposition that fixes it, plus when breaking 3NF is the right call."},{"question":"Is there a question about modeling many-to-many relationships?","answer":"Yes: the junction-table pattern with a composite key, and the follow-up about putting extra columns such as quantity on the junction row."},{"question":"Do the answers take sides on surrogate versus natural keys?","answer":"They explain both, then give the rule most teams settle on: a surrogate primary key for stability, plus a UNIQUE constraint so the natural key still cannot repeat."},{"question":"Are there system-design style questions?","answer":"Yes: storing hierarchies three ways, temporal data with valid_from and valid_to, audit history, and the EAV pattern with the reasons it goes wrong."}]},"source_url":"https://sqlly.app/sql-interview-questions/schema-design","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/subqueries","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL subquery & CTE interview questions","description":"Practice SQL subquery and CTE interview questions with worked answers: IN vs EXISTS, correlated subqueries, recursive CTEs and the NOT IN NULL trap.","body":{"slug":"subqueries","name":"Subqueries & CTEs","h1":"SQL subquery & CTE interview questions","lede":"From scalar subqueries to recursive CTEs, including the NOT IN versus NULL trap: one NULL in the subquery and the query returns nothing.","questions":[{"difficulty":"Easy","question":"What is a scalar subquery, and where can it appear?","answer_html":"<p>A subquery that returns exactly one row and one column, usable anywhere a single value is allowed: the SELECT list, WHERE comparisons, even ORDER BY.</p>\n<pre class=\"iq-code\"><code>SELECT name,\n(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.customer_id) AS order_count\nFROM customers c;</code></pre>\n<p>Two follow-ups. If the subquery returns more than one row, PostgreSQL, SQL Server, MySQL and Oracle raise a runtime error, while SQLite silently uses the first row; if it returns no rows, the value is NULL, so a COUNT subquery is safe but a SUM one may need COALESCE. And a correlated scalar subquery is logically evaluated once per outer row: some optimizers turn it into a join, PostgreSQL generally does not, so on large tables a LEFT JOIN to a grouped subquery is often faster.</p>"},{"difficulty":"Easy","question":"What is the difference between IN and EXISTS?","answer_html":"<p>IN tests membership against a list the subquery returns. EXISTS tests whether the correlated subquery returns any row, and short-circuits at the first match. Modern optimizers rewrite both into the same semi-join in most cases, but they differ in two ways: NULL semantics and what you can express.</p>\n<pre class=\"iq-code\"><code>-- IN: explicit list membership\nSELECT * FROM customers\nWHERE customer_id IN (SELECT customer_id FROM orders WHERE total &gt; 500);\n\n-- EXISTS: first match wins, no list materialized\nSELECT * FROM customers c\nWHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND o.total &gt; 500);</code></pre>\n<p>EXISTS can correlate on any condition, such as o.total &gt; c.credit_limit, while IN only tests equality against a list. The NULL trap of NOT IN does not apply to NOT EXISTS. Inside EXISTS the select list is ignored, so SELECT 1 and SELECT * perform the same; SELECT 1 just tells the reader that only existence matters.</p>"},{"difficulty":"Medium","question":"Write a correlated subquery: return orders above the average for their own customer.","answer_html":"<p>The inner query references the outer row, so it computes a different average per customer.</p>\n<pre class=\"iq-code\"><code>SELECT o.order_id, o.customer_id, o.total\nFROM orders o\nWHERE o.total &gt; (\nSELECT AVG(o2.total)\nFROM orders o2\nWHERE o2.customer_id = o.customer_id\n);</code></pre>\n<p>Say what correlated means: the subquery cannot run once on its own; it re-runs (or is rewritten to a join) per outer row. The window-function version computes AVG(total) OVER (PARTITION BY customer_id) AS customer_avg in a subquery and filters total &gt; customer_avg outside it; it reads orders once instead of once per customer, which usually wins at scale.</p>"},{"difficulty":"Medium","question":"Why can NOT IN return no rows when the subquery contains a NULL?","answer_html":"<p>x NOT IN (a, b, NULL) can never be true: if x equals a or b the result is false, and if it equals neither, the comparison with NULL is unknown. A WHERE clause keeps only true rows, so everything is filtered out.</p>\n<pre class=\"iq-code\"><code>-- Returns zero rows if any orders.customer_id is NULL:\nSELECT * FROM customers c\nWHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o);\n\n-- Safe: NULLs do not match, so they are simply skipped:\nSELECT * FROM customers c\nWHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);</code></pre>\n<p>The defense: filter NULLs explicitly (WHERE o.customer_id IS NOT NULL inside the subquery), make the column NOT NULL in the schema, or use NOT EXISTS. The bug is nasty because the query works for months and then returns nothing the day one guest order with a NULL customer_id is inserted.</p>"},{"difficulty":"Easy","question":"What is a derived table, and when is one needed?","answer_html":"<p>A subquery in the FROM clause: an inline view that materializes (or is rewritten as) an intermediate result you can query like a table. You need one whenever a later step must filter or join on a value computed in an earlier step, such as a window function result.</p>\n<pre class=\"iq-code\"><code>SELECT city, avg_spend\nFROM (\nSELECT c.city, AVG(o.total) AS avg_spend\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.city\n) city_stats\nWHERE avg_spend &gt; 100;</code></pre>\n<p>WHERE cannot filter on AVG directly because aggregates do not exist until after grouping. Here HAVING AVG(o.total) &gt; 100 would do the same job without a derived table; the derived table earns its place when you filter on a window function or join one aggregate to another. The alias (city_stats) is required by PostgreSQL before 16, MySQL and SQL Server. Optimizers usually merge simple derived tables into the outer query, so there is no automatic performance penalty.</p>"},{"difficulty":"Medium","question":"What is a CTE, and why use one instead of a subquery?","answer_html":"<p>A WITH clause defines a named, temporary result visible for the duration of one statement. It improves readability, lets one definition be referenced several times, and is the only syntax for recursion.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL date truncation; the CTE syntax itself is portable:\nWITH monthly AS (\nSELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY 1\n),\nbest AS (\nSELECT month, revenue,\nROW_NUMBER() OVER (ORDER BY revenue DESC) AS rn\nFROM monthly\n)\nSELECT month, revenue FROM best WHERE rn &lt;= 3;</code></pre>\n<p>The performance note: a CTE is for readability, not speed. PostgreSQL before 12 always materialized CTEs, which blocked filters from being pushed inside; since 12 it inlines a CTE referenced once, and you can force either behavior with MATERIALIZED or NOT MATERIALIZED. SQL Server never materializes a CTE, so one referenced twice is computed twice; when that is expensive, a temporary table is the fix.</p>"},{"difficulty":"Hard","question":"Write a recursive CTE that walks the employee manager hierarchy.","answer_html":"<p>A recursive CTE has an anchor member (the top of the hierarchy) and a recursive member that joins the CTE to itself until it returns no rows.</p>\n<pre class=\"iq-code\"><code>WITH RECURSIVE chain AS (\n-- anchor: the CEO\nSELECT employee_id, name, manager_id, 0 AS level\nFROM employees\nWHERE manager_id IS NULL\n\nUNION ALL\n\n-- recursive: one level down each iteration\nSELECT e.employee_id, e.name, e.manager_id, c.level + 1\nFROM employees e\nJOIN chain c ON e.manager_id = c.employee_id\n)\nSELECT * FROM chain ORDER BY level;</code></pre>\n<p>SQL Server and Oracle write plain WITH; PostgreSQL, MySQL 8+ and SQLite require WITH RECURSIVE. If the data contains a cycle (A manages B, B manages A), UNION ALL keeps producing rows: PostgreSQL and SQLite loop until you cancel, SQL Server stops with an error after 100 levels (OPTION (MAXRECURSION n) changes that), and MySQL stops at cte_max_recursion_depth, 1000 by default. The fix is to carry the path of visited ids and stop when the next id is already in it, or use PostgreSQL 14's CYCLE clause.</p>"},{"difficulty":"Medium","question":"Return the second-highest salary per department. Show two ways.","answer_html":"<p>The window way and the offset way. Both handle ties differently, which is the discussion the interviewer wants.</p>\n<pre class=\"iq-code\"><code>-- Way 1: DENSE_RANK keeps ties together, so two people sharing\n-- the top salary both count as rank 1 and rank 2 is the next value:\nSELECT department, name, salary\nFROM (\nSELECT name, department, salary,\nDENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk\nFROM employees\n) ranked\nWHERE rnk = 2;\n\n-- Way 2: DISTINCT salaries, skip one with OFFSET:\nSELECT DISTINCT department, salary\nFROM employees e\nWHERE salary = (\nSELECT DISTINCT salary\nFROM employees e2\nWHERE e2.department = e.department\nORDER BY salary DESC\nLIMIT 1 OFFSET 1\n);</code></pre>\n<p>State the tie question out loud: does the interviewer want the second-highest distinct salary, or the person in second place? Both queries above answer the first; ROW_NUMBER answers the second. A department with only one distinct salary returns no row from either query, which is correct rather than broken. Way 2 uses LIMIT ... OFFSET; SQL Server writes ORDER BY salary DESC OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY.</p>"},{"difficulty":"Medium","question":"What is a semi-join, and how do you write one?","answer_html":"<p>A semi-join returns rows from the left side that have at least one match on the right, without duplicating left rows or needing right-side columns. SQL spells it as IN or EXISTS.</p>\n<pre class=\"iq-code\"><code>-- Customers who ordered in March, once each, no order columns needed:\nSELECT c.name\nFROM customers c\nWHERE EXISTS (\nSELECT 1 FROM orders o\nWHERE o.customer_id = c.customer_id\nAND o.order_date &gt;= '2025-03-01' AND o.order_date &lt; '2025-04-01'\n);</code></pre>\n<p>The contrast with a plain join: joining customers to March orders duplicates a customer once per March order, forcing DISTINCT to undo the fan-out. EXISTS states the intent (has at least one match) and lets the optimizer choose a fast semi-join plan, often a hash or index probe with early termination.</p>"},{"difficulty":"Medium","question":"When can the optimizer flatten a subquery into a JOIN, and when not?","answer_html":"<p>Simple cases flatten: uncorrelated derived tables, IN and EXISTS subqueries the planner can rewrite to semi-joins. Subqueries containing LIMIT, aggregates whose result depends on the outer row, and recursive CTEs often cannot be flattened, so they run once per outer row or are materialized first. How far each optimizer goes differs: SQL Server decorrelates many scalar subqueries into joins, while PostgreSQL runs a correlated scalar subquery as a SubPlan per row.</p>\n<pre class=\"iq-code\"><code>-- Becomes a semi-join (hash or merge) in most engines:\nSELECT c.name FROM customers c\nWHERE c.customer_id IN (SELECT customer_id FROM orders WHERE total &gt; 500);\n\n-- Per-row execution risk: scalar correlated subquery in SELECT:\nSELECT name,\n(SELECT MAX(total) FROM orders o WHERE o.customer_id = c.customer_id) AS max_total\nFROM customers c;</code></pre>\n<p>The practical point: read the plan rather than assume. In PostgreSQL a SubPlan node executed once per outer row is the signal to rewrite as a LEFT JOIN to a grouped subquery, or as a window function. The rewrite of the example: LEFT JOIN (SELECT customer_id, MAX(total) AS max_total FROM orders GROUP BY customer_id) m ON m.customer_id = c.customer_id.</p>"},{"difficulty":"Medium","question":"How does a subquery in FROM differ from a view?","answer_html":"<p>A derived table lives inside one statement; a view is a named query stored in the database, so many queries can reuse it and you can grant access to the view without granting access to the tables behind it.</p>\n<pre class=\"iq-code\"><code>CREATE VIEW monthly_revenue AS\nSELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY 1;\n\nSELECT * FROM monthly_revenue WHERE revenue &gt; 10000;</code></pre>\n<p>Worth adding: a plain view stores no data. The optimizer expands it into the query like a derived table, so it is no faster than the SQL it contains. Materialized views (PostgreSQL, Oracle) store the result and must be refreshed; SQL Server's indexed views store it too and are kept up to date on every write. Views also give a stable interface: you can restructure the tables behind one without breaking the reports that query it. The trap answer is \"a view is faster because the query is saved\"; saving text is not saving work, and the optimizer still runs the whole thing every time. The follow-up is usually when a materialized view is worth its refresh problem, and the honest answer is when the aggregation is expensive and staleness of minutes is acceptable.</p>"},{"difficulty":"Easy","question":"What does the IN operator with a literal list do, and what are its edge behaviors with NULL?","answer_html":"<p>x IN (1, 2, 3) is shorthand for x = 1 OR x = 2 OR x = 3. With NULL in the list, matching rows still match, but non-matching rows become unknown instead of false, so NOT IN flips to empty results.</p>\n<pre class=\"iq-code\"><code>-- Rows whose status is completed or shipped:\nSELECT * FROM orders WHERE status IN ('completed', 'shipped');\n\n-- Returns no rows at all: for every row, status &lt;&gt; NULL is\n-- unknown, so the whole NOT IN can never be true:\nSELECT * FROM orders WHERE status NOT IN ('completed', 'shipped', NULL);</code></pre>\n<p>Nobody types NULL into a literal list on purpose; it arrives through a parameter or an application-built list. Rows whose own status is NULL drop out of both IN and NOT IN, because NULL = 'completed' is unknown too. The rule: IN is safe for positive filters, NOT IN needs a guarantee that neither the column nor the list contains NULL.</p>"}],"faqs":[{"question":"What is the difference between IN and EXISTS?","answer":"IN checks a value against the list a subquery returns; EXISTS checks whether a correlated subquery returns any row at all. The answers cover both, including the semi-join reading of EXISTS and why NOT IN with a NULL in the subquery returns zero rows while NOT EXISTS does not."},{"question":"Is there a recursive CTE question?","answer":"Yes: walk an employee manager hierarchy with a recursive CTE, the anchor-plus-recursive-member structure spelled out line by line."},{"question":"Do the answers cover correlated subqueries?","answer":"Several. The headline one returns every order that is above the average for its own customer, and a later one finds the second-highest salary per department two different ways."},{"question":"When should a subquery become a JOIN?","answer":"There is a dedicated answer on when the optimizer can flatten a subquery into a join, when it cannot, and what that means for the plan you get."}]},"source_url":"https://sqlly.app/sql-interview-questions/subqueries","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/transactions","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL transactions & concurrency interview questions","description":"12 SQL transaction and concurrency interview questions with worked answers: ACID, isolation levels and read anomalies, MVCC, deadlocks, SELECT FOR UPDATE and savepoints.","body":{"slug":"transactions","name":"Transactions & concurrency","h1":"SQL transactions & concurrency interview questions","lede":"Transactions questions move fast from definitions to debugging: which anomaly your default level lets through, why the deadlock victim died, and what an idle-in-transaction session is costing. Every answer names where the engines differ.","questions":[{"difficulty":"Easy","question":"What does ACID mean, in plain terms?","answer_html":"<p>Atomicity: every write in the transaction happens or none of it does. Consistency: the database moves from one valid state to another, with every constraint still holding at commit. Isolation: concurrent transactions cannot see each other's half-finished work. Durability: once COMMIT returns, the changes survive a crash, because they were written to the log before the commit was acknowledged.</p>\n<pre class=\"iq-code\"><code>-- accounts(account_id, balance) is not in the shop schema; a transfer needs it.\nBEGIN;\nUPDATE accounts SET balance = balance - 100 WHERE account_id = 1;\nUPDATE accounts SET balance = balance + 100 WHERE account_id = 2;\nCOMMIT;    -- or ROLLBACK, which erases both updates</code></pre>\n<p>The follow-up is usually \"which of the four does the engine own?\" Atomicity, isolation and durability are the engine's job, delivered by undo and redo logging plus locking or multi-version storage. Consistency is shared: the engine enforces the constraints you declare, and your code owns the rules the schema cannot express, such as the ledger balancing at the end of the day. Reciting the acronym without splitting it that way is the trap this question sets.</p>"},{"difficulty":"Easy","question":"What happens if the connection dies in the middle of a transaction?","answer_html":"<p>The engine rolls the transaction back. Uncommitted changes were never durable: they lived in memory and in the log only as intent, and crash recovery replays committed work and undoes incomplete work. No other session can commit your transaction for you.</p>\n<pre class=\"iq-code\"><code>BEGIN;\nUPDATE orders SET status = 'processing' WHERE order_id = 42;\nUPDATE orders SET status = 'processing' WHERE order_id = 43;\n-- connection drops here: both updates are undone, no partial state survives\nCOMMIT;</code></pre>\n<p>Two consequences worth naming: the locks the transaction held are released, so a dead connection cannot block others beyond the cleanup; and anything the application already sent on the side, a confirmation email or a queue message, is not rolled back with the data, which is the gap the transactional outbox pattern exists to close. The trap is designing around \"it will probably commit\"; the whole point of the transaction is assuming the opposite.</p>"},{"difficulty":"Easy","question":"What is autocommit, and when does a transaction start implicitly?","answer_html":"<p>Autocommit wraps every standalone statement in its own transaction and commits it the moment the statement finishes. It is the default on PostgreSQL, MySQL, SQL Server, Oracle and SQLite. Writing BEGIN (START TRANSACTION or BEGIN TRANSACTION on MySQL and SQL Server) suspends autocommit until the matching COMMIT or ROLLBACK.</p>\n<pre class=\"iq-code\"><code>-- Each statement commits itself:\nUPDATE orders SET status = 'shipped' WHERE order_id = 42;\n\n-- Two statements, one fate:\nBEGIN;\nUPDATE orders SET status = 'shipped' WHERE order_id = 42;\nUPDATE orders SET status = 'shipped' WHERE order_id = 43;\nCOMMIT;</code></pre>\n<p>The detail that catches people: drivers and ORMs often run with autocommit off and issue BEGIN themselves, so a connection that looks idle can be sitting inside an open transaction holding its locks. The trap answer is \"a single UPDATE outside a transaction is not atomic\"; one statement is always atomic, autocommit or not. Transactions exist to give many statements the guarantee that one statement already has.</p>"},{"difficulty":"Medium","question":"What are the three read anomalies: dirty read, non-repeatable read and phantom?","answer_html":"<p>A dirty read sees a row another transaction wrote but has not committed; if that transaction rolls back, you built logic on a value that never existed. A non-repeatable read gets different values for the same row read twice in one transaction, because another transaction updated and committed in between. A phantom runs the same range query twice and the second run returns rows the first did not see, because another transaction inserted and committed in between.</p>\n<pre class=\"iq-code\"><code>-- Session A reads:\nSELECT total FROM orders WHERE order_id = 42;        -- 100\n-- Session B updates and commits:\nUPDATE orders SET total = 200 WHERE order_id = 42; COMMIT;\n-- Session A reads the same row again:\nSELECT total FROM orders WHERE order_id = 42;        -- 200: non-repeatable read\n\n-- Session A counts:\nSELECT COUNT(*) FROM orders WHERE customer_id = 7;   -- 4\n-- Session B inserts one more order for customer 7 and commits.\n-- Session A counts again:\nSELECT COUNT(*) FROM orders WHERE customer_id = 7;   -- 5: a phantom</code></pre>\n<p>The distinction the follow-up probes: a non-repeatable read is one row changing, a phantom is rows joining or leaving a predicate. Saying \"no modern engine allows dirty reads\" is correct but incomplete until you name the mechanism, readers seeing only committed versions. The one common exception is worth knowing: SQL Server's NOLOCK hint (READ UNCOMMITTED) does allow dirty reads, which is why every NOLOCK in a codebase deserves a conversation.</p>"},{"difficulty":"Medium","question":"What are the four isolation levels, and which anomaly does each prevent?","answer_html":"<p>READ UNCOMMITTED permits dirty reads. READ COMMITTED prevents dirty reads but allows non-repeatable reads and phantoms. REPEATABLE READ also prevents non-repeatable reads, and the SQL standard still permits phantoms at this level. SERIALIZABLE prevents all three: the outcome must be one that running the transactions one after another could also have produced.</p>\n<pre class=\"iq-code\"><code>--                     dirty reads   non-repeatable   phantoms\n-- READ UNCOMMITTED      allowed        allowed       allowed\n-- READ COMMITTED          no           allowed       allowed\n-- REPEATABLE READ         no              no         allowed by the standard\n-- SERIALIZABLE            no              no            no</code></pre>\n<p>The senior caveat is that popular engines exceed their own level: PostgreSQL's REPEATABLE READ is snapshot isolation and blocks phantoms too, failing a conflicting write with a serialization error instead of waiting, and MySQL InnoDB's REPEATABLE READ blocks most phantoms with next-key locks on the index range it scanned. Oracle's SERIALIZABLE is snapshot isolation as well. The trap is reciting the standard's matrix as if it described real engines; the interviewer asking this wants the engine reality.</p>"},{"difficulty":"Medium","question":"What isolation level does each engine default to, and how do you change it?","answer_html":"<p>PostgreSQL, SQL Server and Oracle default to READ COMMITTED; MySQL InnoDB defaults to REPEATABLE READ. SQLite has no level to set: every transaction is serializable because the whole database is one file with database-level locking, and WAL mode gives readers a consistent snapshot without changing that. READ UNCOMMITTED does nothing on PostgreSQL (it is accepted as an alias for READ COMMITTED) and does not exist on Oracle; multi-version storage means neither engine can produce a dirty read in the first place.</p>\n<pre class=\"iq-code\"><code>-- SQL Server, MySQL and Oracle share the standard spelling:\nSET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n\n-- PostgreSQL makes the level a property of the transaction:\nBEGIN ISOLATION LEVEL SERIALIZABLE;\n-- or the server default: SET default_transaction_isolation = 'repeatable read';\n\n-- SQLite: nothing to set. Writers take turns on the whole\n-- database file; there are no row or table locks to tune.</code></pre>\n<p>The nuance that earns credit on SQL Server: its READ COMMITTED can run on row versioning instead of locking, switched on per database with READ_COMMITTED_SNAPSHOT or the SNAPSHOT isolation level, both opt-in. The trap is presenting SQLite's serializability as a feature to celebrate; the honest framing is that with database-level locking there is nothing to isolate from, and write concurrency is bounded by taking turns.</p>"},{"difficulty":"Medium","question":"How does MVCC differ from locking?","answer_html":"<p>Locking makes readers and writers queue: a writer holds a lock on the rows it changed, and a reader either waits or takes a shared lock that blocks writers. MVCC (multi-version concurrency control) keeps the previous version of a row while a writer builds a new one, so readers read the last committed version without blocking and writers never wait on readers. Writers still conflict with writers; MVCC removes only the reader-writer queue.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL: the UPDATE writes a new row version; the old version\n-- stays readable and VACUUM reclaims it once nothing needs it.\nUPDATE products SET price = 20 WHERE product_id = 7;\n\n-- SQL Server: same idea, opt-in per database, version store in tempdb:\nALTER DATABASE shop SET READ_COMMITTED_SNAPSHOT ON;</code></pre>\n<p>Per engine: PostgreSQL and Oracle are multi-version from the ground up (Oracle's cost is undo space, and an exhausted undo tablespace produces the \"snapshot too old\" error); MySQL InnoDB is multi-version with row locks on top; SQL Server is lock-first with versioning as an opt-in; SQLite is locking only, one writer at a time on the whole file. The trap is saying \"MVCC means no locks\"; every MVCC engine still locks writes, and two transactions updating the same row still take turns.</p>"},{"difficulty":"Medium","question":"What does SELECT FOR UPDATE do, and when is optimistic concurrency the better choice?","answer_html":"<p>SELECT FOR UPDATE reads rows and holds a write lock on them until the transaction ends, so another transaction's FOR UPDATE or UPDATE on those rows waits. It is pessimistic: lock first, then decide. Optimistic concurrency takes no lock; the transaction re-checks what it read at write time and fails cleanly when someone got there first.</p>\n<pre class=\"iq-code\"><code>-- Pessimistic: the row cannot change under you\nBEGIN;\nSELECT stock FROM products WHERE product_id = 7 FOR UPDATE;\nUPDATE products SET stock = stock - 1 WHERE product_id = 7;\nCOMMIT;\n\n-- Optimistic: no lock held, verify at write time\nUPDATE products SET stock = stock - 1\nWHERE product_id = 7 AND stock = 5;   -- zero rows updated: someone moved it</code></pre>\n<p>The decision to state out loud: high contention and a short critical section want FOR UPDATE; low contention and cheap retries want optimistic, which scales better because nothing is held across user think time. SQL Server has no FOR UPDATE; its spelling is the UPDLOCK hint. The follow-up is usually what happens when the application never commits: the lock lives until the transaction ends, so a FOR UPDATE taken before a slow API call makes every other buyer queue, and that failure mode is why optimistic wins in web request paths.</p>"},{"difficulty":"Medium","question":"What goes wrong when a transaction stays open too long?","answer_html":"<p>Everything the transaction holds, it holds for the duration: its locks and its snapshot. Under MVCC the snapshot is what hurts, because old row versions cannot be reclaimed while any transaction might still need them: dead tuples pile up on PostgreSQL until VACUUM can pass, and InnoDB's history list grows until purge catches up. The worst case is idle in transaction, a session that opened a transaction and walked away, holding its snapshot and its locks while doing no work.</p>\n<pre class=\"iq-code\"><code>-- Find sessions parked inside a transaction (PostgreSQL):\nSELECT pid, state, now() - xact_start AS tx_age, left(query, 60) AS query\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\nORDER BY tx_age DESC;\n\n-- The guardrail: a timeout for idle transactions\nSET idle_in_transaction_session_timeout = '5min';</code></pre>\n<p>Name the damage per engine: PostgreSQL table and index bloat with VACUUM falling behind, InnoDB history-list growth slowing every consistent read, SQL Server tempdb version store growth under versioned isolation, and on SQL Server and InnoDB the log cannot truncate past the oldest open transaction. The trap is blaming long queries; a query at least does work, while a forgotten transaction, usually an error path that skipped its rollback, holds everything indefinitely. That is why the timeout and monitoring question comes next.</p>"},{"difficulty":"Medium","question":"What is a SAVEPOINT, and when would you roll back to one?","answer_html":"<p>A savepoint marks a position inside the current transaction so part of it can be undone without discarding the rest. ROLLBACK TO undoes everything since the named savepoint and keeps the transaction open; RELEASE SAVEPOINT keeps the work and drops the marker.</p>\n<pre class=\"iq-code\"><code>-- The standard frame: a batch import where one bad row\n-- should not kill the whole file\nBEGIN;\nSAVEPOINT row_10;\nINSERT INTO order_items (order_id, product_id, quantity)\nVALUES (42, 7, -3);         -- CHECK (quantity &gt; 0) fails here\nROLLBACK TO row_10;         -- the bad row is gone, the transaction lives\nINSERT INTO order_items (order_id, product_id, quantity)\nVALUES (42, 9, 1);          -- the next row imports normally\nCOMMIT;                     -- every good row is committed</code></pre>\n<p>Every engine here supports the syntax: PostgreSQL, MySQL InnoDB, SQL Server, Oracle and SQLite. Savepoint names are unique within the transaction and roll back in stack order, so rolling back to an early savepoint discards the later ones. The trap is reaching for nested transactions instead: SQL Server's BEGIN inside a transaction only increments @@TRANCOUNT and MySQL treats it the same way, so the outer COMMIT commits everything; the savepoint is the actual partial-rollback tool.</p>"},{"difficulty":"Hard","question":"What causes a deadlock, and how does each engine detect and resolve one?","answer_html":"<p>A deadlock is two transactions each holding a lock the other needs, so both wait forever: A locks row 42 and asks for row 43, B locks row 43 and asks for row 42. No amount of waiting fixes the geometry, so the engine must find the cycle and kill one transaction.</p>\n<pre class=\"iq-code\"><code>-- The classic: the same rows updated in opposite orders\n-- Session A: BEGIN; UPDATE orders ... WHERE order_id = 42; then ... 43;\n-- Session B: BEGIN; UPDATE orders ... WHERE order_id = 43; then ... 42;\n\n-- Who dies, and what the error looks like:\n-- PostgreSQL:  ERROR:  deadlock detected (after deadlock_timeout, 1s default)\n-- MySQL:       error 1213, InnoDB rolls back the smaller transaction\n-- SQL Server:  error 1205, victim chosen by cost unless DEADLOCK_PRIORITY says otherwise\n-- Oracle:      ORA-00060, and the failing transaction writes a trace file\n-- SQLite:      no row locks, so no cycle; the second writer gets SQLITE_BUSY</code></pre>\n<p>Diagnosis is the follow-up to have ready: InnoDB prints the last one under LATEST DETECTED DEADLOCK in SHOW ENGINE INNODB STATUS, SQL Server records deadlock graphs in the system_health session, and PostgreSQL logs both statements to the server log when the detector fires. The answers that land: keep a consistent lock order everywhere (update rows in sorted key order), keep transactions short, and retry the victim, because a deadlock is not an engine bug but a property of the locking pattern.</p>"},{"difficulty":"Hard","question":"How do you compute peak concurrent sessions from a session log?","answer_html":"<p>Overlapping intervals, solved with the same running-total pass as gaps and islands: a session start contributes +1, an end contributes -1, sort the events by time and accumulate.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL syntax; sessions(session_id, started_at, ended_at)\n-- is not in the shop schema:\nWITH events AS (\nSELECT started_at AS ts, 1 AS delta FROM sessions\nUNION ALL\nSELECT ended_at, -1 FROM sessions\n),\nordered AS (\nSELECT ts, SUM(delta) OVER (ORDER BY ts, delta) AS live\nFROM events\n)\nSELECT ts, live FROM ordered ORDER BY live DESC LIMIT 1;</code></pre>\n<p>Worked through: sessions from 09:00 to 10:00, 09:30 to 09:45 and 09:40 to 10:30 give sorted deltas +1, +1, +1, -1, -1, -1, and the running total peaks at 3 between 09:40 and 09:45. The ORDER BY ts, delta matters: when an end and a start share an instant, the end must subtract first or the peak overcounts, and surfacing that boundary rule yourself is what the interviewer is really asking. The tie-in to say out loud: run this over your transaction table before tuning isolation levels or locks, because knowing how many transactions actually overlap tells you whether concurrency is even your problem.</p>"}],"faqs":[{"question":"Which engines do the transaction answers cover?","answer":"PostgreSQL, MySQL InnoDB, SQL Server, Oracle and SQLite, and the value is mostly in where they disagree: default isolation levels, locking versus MVCC, how each engine picks its deadlock victim, and the different spellings for setting an isolation level."},{"question":"What schema do these answers use?","answer":"The same shop schema as every topic, printed at the top of the page. Concurrency needs rows that two transactions can fight over, so the transfer examples introduce an accounts table and the peak-concurrency question introduces a sessions log, each declared in a comment where it appears."},{"question":"Is there a question about deadlocks?","answer":"A hard one: what causes the cycle, which transaction each engine kills, how PostgreSQL, MySQL, SQL Server, Oracle and SQLite differ on detection, and how to read each engine's own deadlock report."},{"question":"What is the hardest question here?","answer":"Two of them: deadlock diagnosis per engine, and computing peak concurrent sessions from a session log with window functions, which is the gaps-and-islands pattern applied to overlapping intervals. Both are senior-level follow-ups."}]},"source_url":"https://sqlly.app/sql-interview-questions/transactions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-interview-questions/window-functions","corpus":"sql-interview-questions","engine":null,"language":"en","title":"SQL window function interview questions","description":"Practice SQL window function interview questions with worked answers: OVER, ROW_NUMBER vs RANK, running totals, LAG, frames and deduplication.","body":{"slug":"window-functions","name":"Window functions","h1":"SQL window function interview questions","lede":"A staple of senior-level screens: ranking without collapsing rows, running totals, LAG for period-over-period change, and frame traps.","questions":[{"difficulty":"Easy","question":"What does AVG(salary) OVER () do, and how is it different from GROUP BY?","answer_html":"<p>An empty OVER computes the aggregate over every row of the result and attaches it to each row, without collapsing rows the way GROUP BY does.</p>\n<pre class=\"iq-code\"><code>SELECT name, department, salary,\nAVG(salary) OVER () AS company_avg\nFROM employees;</code></pre>\n<p>GROUP BY would collapse the table to one row (or one per department); the window version returns every employee with the company average alongside, so salary - AVG(salary) OVER () gives each person's distance from the average in one pass. Without the window you need a subquery or a join back to an aggregate. The window is computed after WHERE, so filtering to one department changes the average too.</p>"},{"difficulty":"Medium","question":"What is the difference between ROW_NUMBER, RANK and DENSE_RANK?","answer_html":"<p>All three number rows within a partition in ORDER BY order. ROW_NUMBER gives every row a distinct number, breaking ties arbitrarily. RANK gives tied rows the same rank and skips the following numbers. DENSE_RANK gives tied rows the same rank and skips nothing.</p>\n<pre class=\"iq-code\"><code>SELECT name, department, salary,\nROW_NUMBER() OVER w AS rn,\nRANK()       OVER w AS rnk,\nDENSE_RANK() OVER w AS drnk\nFROM employees\nWINDOW w AS (PARTITION BY department ORDER BY salary DESC);</code></pre>\n<p>With salaries 2000, 2000, 1500 the outputs are 1, 2, 3 for ROW_NUMBER; 1, 1, 3 for RANK; 1, 1, 2 for DENSE_RANK. Say which you would use: exactly n rows per group needs ROW_NUMBER (with a tiebreaker in the ORDER BY so the result is repeatable), a leaderboard with ties wants RANK, and the nth distinct value wants DENSE_RANK. The named WINDOW clause works on PostgreSQL, MySQL 8, SQLite and SQL Server 2022+; older SQL Server needs the OVER (...) written out each time. The trap is trusting ROW_NUMBER with ties and no tiebreaker: which tied row gets 1 is arbitrary, so the \"top earner\" can change between runs and between engines. When the interviewer pushes on this, name the tiebreaker (salary, then employee_id) before anything else.</p>"},{"difficulty":"Medium","question":"Return the highest-paid employee in each department.","answer_html":"<p>Rank within each department partition, then filter the ranking outside the subquery. Window functions cannot appear in WHERE because WHERE runs first.</p>\n<pre class=\"iq-code\"><code>SELECT department, name, salary\nFROM (\nSELECT name, department, salary,\nROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn\nFROM employees\n) ranked\nWHERE rn = 1;</code></pre>\n<p>The follow-up to expect: what if two people tie for the top salary? ROW_NUMBER returns one arbitrarily; RANK with WHERE rnk = 1 returns both. Choosing deliberately is the difference between a memorized pattern and an understood one.</p>"},{"difficulty":"Medium","question":"Compute a running total of order revenue by date.","answer_html":"<p>OVER with ORDER BY: once a window has an ORDER BY, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, from the partition start to the current row and its peers, so the sum accumulates.</p>\n<pre class=\"iq-code\"><code>SELECT order_date,\nSUM(total) OVER (ORDER BY order_date) AS running_total\nFROM (\nSELECT order_date, SUM(total) AS total\nFROM orders\nGROUP BY order_date\n) daily;</code></pre>\n<p>Two details worth stating: ties on order_date all share the same running total because peers are in the same frame (use ORDER BY order_date, order_id for a strict order), and pre-aggregating to one row per day keeps the window small and the intent clear.</p>"},{"difficulty":"Medium","question":"What do LAG and LEAD do? Show month-over-month revenue change.","answer_html":"<p>LAG fetches a value from a previous row of the partition, LEAD from a following one, both offset by a count with a default for the edges.</p>\n<pre class=\"iq-code\"><code>SELECT month, revenue,\nLAG(revenue) OVER (ORDER BY month) AS prev_month,\nrevenue - LAG(revenue) OVER (ORDER BY month) AS change\nFROM (\nSELECT DATE_TRUNC('month', order_date) AS month, SUM(total) AS revenue\nFROM orders\nGROUP BY 1\n) monthly;</code></pre>\n<p>The first row returns NULL for prev_month, so change is NULL there, not zero, which is usually what a report should show. LAG(revenue, 1, 0) supplies an explicit default if you do want zero. A gotcha worth raising: LAG looks at the previous row, not the previous calendar month, so a month with no orders is silently skipped and the next change spans two months. Join to a month calendar first if gaps are possible. The query uses PostgreSQL's DATE_TRUNC; the aggregation questions show the other engines' spelling.</p>"},{"difficulty":"Medium","question":"Compute each employee's share of their department salary bill.","answer_html":"<p>Two window expressions over the same partition: the department total and the row-level division.</p>\n<pre class=\"iq-code\"><code>SELECT name, department, salary,\nSUM(salary) OVER (PARTITION BY department) AS dept_total,\nsalary * 100.0 / SUM(salary) OVER (PARTITION BY department) AS pct_of_dept\nFROM employees;</code></pre>\n<p>With GROUP BY you would lose the per-employee rows and need a join back to the aggregates. The window version does it in one pass, which is the standard answer to share-of-total questions.</p>"},{"difficulty":"Hard","question":"Compute a 3-day moving average of daily revenue.","answer_html":"<p>Restrict the frame with ROWS BETWEEN. The default frame runs from the partition start; a moving window needs explicit bounds.</p>\n<pre class=\"iq-code\"><code>SELECT order_date,\nAVG(total) OVER (\nORDER BY order_date\nROWS BETWEEN 2 PRECEDING AND CURRENT ROW\n) AS moving_avg_3day\nFROM (\nSELECT order_date, SUM(total) AS total\nFROM orders\nGROUP BY order_date\n) daily;</code></pre>\n<p>Note the edge behavior: the first two days average fewer than three values because the frame is truncated at the partition start. ROWS counts physical rows, so a day with no orders has no row and the window quietly stretches over four calendar days. PostgreSQL 11+ can express a true calendar window with RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW.</p>"},{"difficulty":"Medium","question":"Split employees into four salary quartiles with NTILE.","answer_html":"<p>NTILE(n) distributes partition rows as evenly as possible into n buckets, numbered 1 to n in the window order.</p>\n<pre class=\"iq-code\"><code>SELECT name, salary,\nNTILE(4) OVER (ORDER BY salary DESC) AS quartile\nFROM employees;</code></pre>\n<p>The follow-up is usually uneven divisions: with 10 rows and 4 tiles, the earlier tiles get the extra rows (3, 3, 2, 2). NTILE also ignores ties, so two people with the same salary can land in different quartiles. When that matters, PERCENT_RANK or CUME_DIST give each row a value between 0 and 1 that ties share, and you bucket on that instead.</p>"},{"difficulty":"Hard","question":"Gaps and islands: find each streak of consecutive active days per user.","answer_html":"<p>Number each user's active days in date order, then subtract that row number (as days) from the date. Consecutive days produce the same result, so that value labels an island.</p>\n<pre class=\"iq-code\"><code>-- PostgreSQL; logins(user_id, login_date) is not in the shop schema:\nWITH daily AS (\nSELECT DISTINCT user_id, login_date::date AS day\nFROM logins\n),\ngrouped AS (\nSELECT user_id, day,\nday - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) * INTERVAL '1 day' AS grp\nFROM daily\n)\nSELECT user_id, MIN(day) AS streak_start, MAX(day) AS streak_end, COUNT(*) AS days\nFROM grouped\nGROUP BY user_id, grp\nORDER BY user_id, streak_start;</code></pre>\n<p>Worked through: logins on Jan 1, 2, 3 and 5 get row numbers 1, 2, 3, 4, so date minus row number is Dec 31, Dec 31, Dec 31 and Jan 1. Two islands: Jan 1 to 3 (3 days) and Jan 5 (1 day). The SELECT DISTINCT matters, because two logins on one day would otherwise get two row numbers and break the streak. The trap is dropping the PARTITION BY user_id: without it the row numbers run across all users and everyone's streaks merge into one. The follow-up is usually the reverse problem, finding the gaps between islands, which is LEAD(streak_start) over the same grouped rows minus streak_end, filtered to where the distance is more than one day. The same trick finds gaps in invoice numbers or runs of failed jobs.</p>"},{"difficulty":"Medium","question":"Why does putting a window function in WHERE fail, and what do you do instead?","answer_html":"<p>WHERE runs before window functions are evaluated, so the window result does not exist yet. The fix is to compute the window in a subquery or CTE and filter outside it.</p>\n<pre class=\"iq-code\"><code>SELECT * FROM (\nSELECT name, department, salary,\nRANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk\nFROM employees\n) ranked\nWHERE rnk = 1;</code></pre>\n<p>Snowflake, BigQuery, DuckDB, Databricks and Teradata support QUALIFY, which filters on window results directly: QUALIFY RANK() OVER (PARTITION BY department ORDER BY salary DESC) = 1. PostgreSQL, SQL Server, MySQL, SQLite and Oracle do not, so the subquery or CTE form is the one to write in an interview unless you know the target engine.</p>"},{"difficulty":"Medium","question":"What does FIRST_VALUE do, and what is the LAST_VALUE trap?","answer_html":"<p>FIRST_VALUE and LAST_VALUE return an expression from the first and last row of the frame. The trap: with an ORDER BY, the default frame ends at the current row (plus any rows tied with it), so LAST_VALUE returns the current row or its last tied peer, not the partition's last row.</p>\n<pre class=\"iq-code\"><code>SELECT name, department, salary,\nFIRST_VALUE(name) OVER w AS top_earner,\nLAST_VALUE(name)  OVER w AS last_row_only,      -- usually wrong\nLAST_VALUE(name)  OVER (w ROWS BETWEEN UNBOUNDED PRECEDING\n                           AND UNBOUNDED FOLLOWING) AS lowest_earner\nFROM employees\nWINDOW w AS (PARTITION BY department ORDER BY salary DESC);</code></pre>\n<p>With salaries 2000, 2000 and 1500, last_row_only returns the second 2000 earner for both of the first two rows and the 1500 earner for the third. FIRST_VALUE escapes the trap only because the default frame starts at UNBOUNDED PRECEDING. When LAST_VALUE misbehaves, the fix is the frame: extend it to UNBOUNDED FOLLOWING, or use FIRST_VALUE with the ORDER BY reversed. A window that already has an ORDER BY can add a frame but cannot get a second ORDER BY, which is why the frame is appended to w here.</p>"},{"difficulty":"Hard","question":"Delete duplicate rows, keeping the latest one per natural key.","answer_html":"<p>Number duplicates by recency with ROW_NUMBER partitioned on the natural key, then delete where the number is greater than one.</p>\n<pre class=\"iq-code\"><code>WITH ranked AS (\nSELECT ctid AS row_id,\nROW_NUMBER() OVER (\n   PARTITION BY email ORDER BY updated_at DESC\n) AS rn\nFROM customers\n)\nDELETE FROM customers\nWHERE ctid IN (SELECT row_id FROM ranked WHERE rn &gt; 1);</code></pre>\n<p>ctid is PostgreSQL's physical row address, used here because true duplicates may have no distinguishing key; it is stable only within the statement, so never store it. Elsewhere, use the primary key; SQL Server can even delete through the CTE directly (WITH ranked AS (...) DELETE FROM ranked WHERE rn &gt; 1). ORDER BY updated_at DESC with rn &gt; 1 keeps the newest row, and if two rows share an updated_at the survivor is arbitrary unless you add a tiebreaker. Run the SELECT first to preview what will be deleted, then add a UNIQUE constraint on email so the duplicates cannot come back.</p>"}],"faqs":[{"question":"Which window function questions come up most in interviews?","answer":"ROW_NUMBER versus RANK versus DENSE_RANK, top-n per group, running totals, LAG for period-over-period change, and deleting duplicates with ROW_NUMBER. All are here with worked SQL."},{"question":"Do the answers explain OVER (PARTITION BY ...) versus OVER ()?","answer":"Yes. The first question contrasts an empty OVER, which aggregates over the whole table while keeping every row, with the partitioned form used for per-group shares."},{"question":"Is there a question about window frame boundaries?","answer":"Two: a moving average with ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, and the LAST_VALUE trap, where the default frame stops at the current row and its peers instead of the end of the partition."},{"question":"Why does my window function fail in WHERE?","answer":"Because WHERE runs before window functions are evaluated. One answer shows the portable subquery workaround and the QUALIFY clause that Snowflake, BigQuery, DuckDB and Databricks offer."}]},"source_url":"https://sqlly.app/sql-interview-questions/window-functions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
