Country or region and language

    Choose your country or region and your language.

    Suggested for you

      All countries and regions

        Choose your character

        It shows in the top bar and on your profile. Change it any time.

        Sign in or join

        8 tricky SQL queries for interviews

        Practice eight tricky SQL queries for interviews with PostgreSQL answers, small counterexamples, and result checks that expose subtly incorrect query rewrites.

        A person practicing on a laptop in a quiet workspace

        Tricky SQL queries for interviews test whether you understand which rows a query keeps, removes, combines, or calculates. These eight questions cover arithmetic, duplicates, missing values, aggregation, joins, and window functions, with runnable PostgreSQL answers and expected results. A strong answer explains why the query works and shows a small input that exposes an incorrect alternative.

        Eight queries with checkable answers

        Each answer uses a counterexample: an input that disproves a proposed rule. For example, two transactions with equal amounts expose why removing duplicate rows can change a total. All data is fictional, amounts represent Philippine pesos, and every example uses PostgreSQL syntax.

        Run each block independently. The WITH clause names temporary query results, and VALUES supplies starting rows, so you don't need to create tables. Lines beginning with two hyphens are comments, including the expected output.

        Arithmetic and repeated rows

        Arithmetic types and repeated rows can change results before joins enter the query. Integer division discards the fractional part, while SQL results can preserve repeated rows unless an operation removes them.

        -- 1. Question: Why does dividing 3 by 2 return 1, and how
        -- would you return 1.5 without rounding?
        -- Starting values: numerator 3; denominator 2.
        -- Target: preserve the fractional part.
        -- Model answer: PostgreSQL uses integer division for integer
        -- operands. Convert an operand to numeric before dividing.
        SELECT 3 / 2 AS integer_result,
               CAST(3 AS numeric) / 2 AS decimal_result;
        -- Expected values, possibly with additional trailing zeros:
        -- integer_result | decimal_result
        -- 1              | 1.5
        -- Calculation: integer division discards the fraction;
        -- numeric division preserves it.
        -- Common mistake: casting after division has lost the fraction.
        -- Interviewer listens for: operand types and conversion order.
        -- 2. Question: Can you replace UNION ALL with UNION when
        -- combining query branches? Show a counterexample.
        -- Starting values: two legitimate transactions of 100 pesos.
        -- Target: total both transactions, giving 200 pesos.
        -- Model answer: No. UNION removes duplicate result rows;
        -- UNION ALL preserves them.
        WITH preserved AS (
          SELECT 100 AS amount UNION ALL SELECT 100 AS amount
        ), deduplicated AS (
          SELECT 100 AS amount UNION SELECT 100 AS amount
        )
        SELECT (SELECT SUM(amount) FROM preserved) AS correct_total,
               (SELECT SUM(amount) FROM deduplicated) AS changed_total;
        -- Expected:
        -- correct_total | changed_total
        -- 200           | 100
        -- Calculation: 100 + 100 = 200; removing one row leaves 100.
        -- Common mistake: treating equal amounts as duplicate records.
        -- Interviewer listens for: duplicate result rows versus
        -- duplicate business records and their identifying columns.

        UNION compares the complete selected row. If you select only an amount, two different transactions can become indistinguishable. State what one output row represents before deciding whether deduplication is appropriate.

        Missing values and empty inputs

        Missing values affect comparisons and aggregate calculations differently. NULL represents a missing or unknown value; WHERE keeps only rows whose condition evaluates to true, not rows whose condition is unknown.

        -- 3. Question: Why can NOT IN return no rows when its list
        -- contains NULL, and how would you find unblocked IDs?
        -- Starting values: candidates 1 and 2; blocked IDs 2 and NULL.
        -- Target: return ID 1; NULL identifies no blocked candidate.
        -- Model answer: An unmatched NOT IN comparison becomes unknown
        -- when the list contains NULL. NOT EXISTS checks whether an
        -- actual matching row exists.
        WITH candidates(id) AS (VALUES (1), (2)),
        blocked(id) AS (VALUES (2), (NULL::integer))
        SELECT c.id
        FROM candidates AS c
        WHERE NOT EXISTS (
          SELECT 1 FROM blocked AS b WHERE b.id = c.id
        )
        ORDER BY c.id;
        -- Expected: one row, id = 1.
        -- Calculation: ID 1 has no matching blocked row; ID 2 does.
        -- Comparison: replace the entire NOT EXISTS (...) expression
        -- with c.id NOT IN (SELECT id FROM blocked), then rerun.
        -- Expected after replacement: no rows.
        -- Common mistake: assuming unknown means true or false.
        -- Interviewer listens for: unknown comparisons and an explicit
        -- rule for missing identifiers.
        -- 4. Question: What do SUM and COUNT return when no rows match,
        -- and how would you display a zero total instead of NULL?
        -- Starting value: one amount of 100 pesos.
        -- Target: count and sum an empty input; display zero as its total.
        -- Exact filter: WHERE false excludes the starting row.
        -- Model answer: Without GROUP BY, COUNT(*) returns zero and
        -- SUM returns NULL. COALESCE selects its first non-NULL argument.
        WITH payments(amount) AS (VALUES (100))
        SELECT COUNT(*) AS row_count,
               SUM(amount) AS raw_total,
               COALESCE(SUM(amount), 0) AS displayed_total
        FROM payments
        WHERE false;
        -- Expected:
        -- row_count | raw_total | displayed_total
        -- 0         | NULL      | 0
        -- Calculation: no rows contribute; COALESCE replaces NULL.
        -- Common mistake: expecting COALESCE to create missing groups.
        -- With GROUP BY, an absent group produces no output row.
        -- Interviewer listens for: empty input versus a missing group.

        Group filters and membership tests

        Group filters test calculated totals, while membership tests check whether a matching record exists. A group combines rows for an aggregate calculation; a join produces matching combinations of rows.

        Before reading the next solutions, try Interview questions: basics and state what each output row should represent.

        -- 5. Question: Return branches with total sales of at least
        -- 300 pesos. Can the total-sales condition move into WHERE?
        -- Starting sales: Cebu 100 and 200; Davao 400.
        -- Target: retain branches whose SUM(amount) is at least 300.
        -- Model answer: Use HAVING for the aggregate condition.
        -- WHERE filters individual sales before aggregation.
        WITH sales(branch, amount) AS (
          VALUES ('Cebu', 100), ('Cebu', 200), ('Davao', 400)
        )
        SELECT branch, SUM(amount) AS total
        FROM sales
        GROUP BY branch
        HAVING SUM(amount) >= 300
        ORDER BY branch;
        -- Expected:
        -- branch | total
        -- Cebu   | 300
        -- Davao  | 400
        -- Calculations: Cebu = 100 + 200; Davao = 400.
        -- Unsafe change: remove HAVING and insert WHERE amount >= 300
        -- immediately before GROUP BY, then rerun.
        -- Expected after replacement: Davao 400 only.
        -- Common mistake: testing each sale instead of the branch total.
        -- Interviewer listens for: row filtering versus group filtering.
        -- 6. Question: Return each customer who has an order exactly
        -- once. Is an INNER JOIN equivalent to EXISTS?
        -- Starting values: customers 1 and 2; customer 1 has orders
        -- 101 and 102; customer 2 has no orders.
        -- Target: one output row for customer 1.
        -- Model answer: EXISTS tests for a match without multiplying
        -- the customer row. INNER JOIN emits both matching pairs.
        WITH customers(id) AS (VALUES (1), (2)),
        orders(order_id, customer_id) AS (VALUES (101, 1), (102, 1))
        SELECT c.id
        FROM customers AS c
        WHERE EXISTS (
          SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
        )
        ORDER BY c.id;
        -- Expected: one row, id = 1.
        -- Calculation: customer 1 has a match; customer 2 doesn't.
        -- Unsafe change: replace the complete WHERE EXISTS (...) clause
        -- with INNER JOIN orders AS o ON o.customer_id = c.id, then rerun.
        -- Expected after replacement: two rows, both containing 1.
        -- Common mistake: using DISTINCT to hide unintended row growth.
        -- Interviewer listens for: one-to-many matches and row meaning.

        DISTINCT removes duplicate selected rows. Adding DISTINCT can make a join return the desired customer IDs, but EXISTS expresses the membership requirement directly. Neither spelling is automatically faster; correctness and execution behavior are separate questions.

        Window frames and calculation order

        Window functions calculate across related rows without collapsing those rows into groups. A window frame is the subset used for the current row's calculation, and peers are rows equal on the window's ordering expressions.

        -- 7. Question: Why can a running sum jump across equal amounts,
        -- and how would you calculate one row at a time?
        -- Starting values: IDs 1, 2, 3; amounts 100, 100, 200 pesos.
        -- Target: row-by-row totals ordered by amount, then ID.
        -- Model answer: PostgreSQL's default aggregate window frame
        -- with ORDER BY includes the current row's peers. Use an
        -- explicit ROWS frame and a unique ordering tie-breaker.
        WITH sales(id, amount) AS (
          VALUES (1, 100), (2, 100), (3, 200)
        )
        SELECT id,
               SUM(amount) OVER (ORDER BY amount) AS peer_total,
               SUM(amount) OVER (
                 ORDER BY amount, id
                 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
               ) AS row_total
        FROM sales
        ORDER BY amount, id;
        -- Expected:
        -- id | peer_total | row_total
        -- 1  | 200        | 100
        -- 2  | 200        | 200
        -- 3  | 400        | 400
        -- Calculations: first peer group = 100 + 100;
        -- row totals = 100; 100 + 100; 100 + 100 + 200.
        -- Common mistake: specifying ROWS without resolving ordering ties.
        -- Interviewer listens for: peers, frames, and deterministic order.
        -- 8. Question: Return rows whose running sales total is at
        -- least 300 pesos, calculated over every original sale.
        -- Where should the threshold filter go?
        -- Starting values: IDs 1, 2, 3; amounts 100, 200, 300 pesos.
        -- Target: calculate totals in ID order, then keep totals >= 300.
        -- Model answer: Calculate the window result in a subquery,
        -- then filter in the outer query. PostgreSQL doesn't allow
        -- window functions in the same query level's WHERE clause.
        WITH sales(id, amount) AS (
          VALUES (1, 100), (2, 200), (3, 300)
        )
        SELECT id, running_total
        FROM (
          SELECT id,
                 SUM(amount) OVER (
                   ORDER BY id
                   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
                 ) AS running_total
          FROM sales
        ) AS calculated
        WHERE running_total >= 300
        ORDER BY id;
        -- Expected:
        -- id | running_total
        -- 2  | 300
        -- 3  | 600
        -- Calculations: 100; 100 + 200; 100 + 200 + 300.
        -- Common mistake: filtering source amounts before calculating,
        -- which removes contributions from the running total.
        -- Interviewer listens for: calculation order and preserved input.

        The subquery in question 8 is a query inside another query. Its result becomes the outer query's input, making the calculated running total available for filtering.

        To rehearse separating inner calculations from outer filters, try Practice: nested queries.

        Counterexample rehearsal

        Counterexample rehearsal checks whether you can defend a query rather than repeat its syntax. Hide a solution, predict the output, run the query, and investigate the first difference.

        • State what one output row represents.
        • Identify where rows disappear, multiply, or contribute to calculations.
        • Test a duplicate, a missing value, an empty input, or an ordering tie.
        • Explain why an apparently simpler rewrite changes the answer.

        Retry the reasoning independently with SQL interview practice. The Work Gym's SQL course also has automatically checked exercises with hints that name the mistake.

        Small examples expose logical errors, but they don't establish performance on production-sized tables. Once the result is correct, examine execution behavior separately using representative data and the database's query-planning tools.

        Common questions

        Why can NOT IN return no rows when its subquery contains NULL? For an unmatched value, a NULL in the subquery makes the NOT IN condition unknown rather than true. WHERE rejects unknown conditions, so a list containing both a matching ID and NULL can exclude every candidate.

        When should I use EXISTS instead of an INNER JOIN? Use EXISTS when you need to test whether at least one matching row exists without repeating the outer row. Use an INNER JOIN when you need matching row combinations or columns from the matching records.

        Why does a running sum give equal amounts the same total? In PostgreSQL, an aggregate window ordered only by amount uses a default frame that includes peers with equal amounts. For row-by-row accumulation, specify a ROWS frame and add a unique ordering tie-breaker.

        Practice what this post teaches

        Do these PostgreSQL answers work unchanged in every SQL dialect? No. Integer division, type conversion syntax, and supported window features can differ between database systems. Keep the counterexample method, but check syntax and behavior in the database named by your interviewer.

        Practice what this post teaches

        Your Work Gym account

        Save your progress and pick up on another device. Your browser's progress comes with you.

        Your account can start a 5-day free trial: every course, unit, project and exam. Card needed; cancel any time and pay nothing.

        New accounts get 6 hours of full access: every course, unit, project and exam. The clock starts when you go past the free lessons.

        Plan your practice from a job ad or syllabus

        Have a referral code?

        or

        You can keep practicing without an account.

        Help and feedback

        Ask a question, tell us what is not working, or share an idea. We reply by email.

        What is it about?

        We use it only to reply to you.