SQL Query Fundamentals Questions
Core SQL for reading and shaping data: SELECT, filtering with WHERE, sorting, DISTINCT, and single-table aggregation with GROUP BY, HAVING, and aggregate functions. Covers reasoning about NULL handling, grouping semantics, and writing correct queries against a given schema. The baseline query-writing surface most data and engineering interviews open with.
Given users(user_id, name, country) and orders(order_id, user_id, amount, occurred_at), write a query computing total revenue and distinct-buyer count per country for the last 30 days, including countries with zero revenue (not just zero-activity time periods).
Sample Answer
The zero-fill technique generalizes from time periods to any dimension: joining from a complete, independent list of dimension values (every country, not just the ones with activity) is what guarantees zero-activity dimension values appear explicitly rather than being silently absent.
Structured elaboration
SELECT u.country, COALESCE(SUM(o.amount), 0) AS total_revenue,
COUNT(DISTINCT o.user_id) AS unique_buyers
FROM users u
LEFT JOIN orders o ON o.user_id = u.user_id AND o.occurred_at >= (reference_date - interval '30 days')
GROUP BY u.country;
(reference_date stands in for CURRENT_DATE/CURRENT_TIMESTAMP, the moment the report is run; substitute it directly, or replace it with CURRENT_DATE outright, since it isn't a real column in either table.)
Here the "complete axis" is the distinct set of countries known from the users table (or a dedicated countries dimension table), not a generated date series; the same LEFT JOIN-from-the-complete-side principle applies: start from every country that should be represented, then LEFT JOIN the actual order activity onto it, so a country with zero recent orders still appears with revenue = 0 rather than being silently absent from the report.
The 30-day filter has to live inside the JOIN's ON clause, exactly as written above, not in a separate WHERE clause. Since this query needs to keep every country (via LEFT JOIN) even when it has zero recent orders, moving o.occurred_at >= (reference_date - interval '30 days') into WHERE would evaluate it AFTER the join has already happened, and WHERE only keeps rows where the condition is TRUE. For a country with no matching orders at all, the joined order columns are already NULL, so a WHERE condition comparing o.occurred_at to a date evaluates to UNKNOWN for that row, which WHERE treats the same as FALSE, silently dropping every zero-order country from the result. That turns the LEFT JOIN back into an effective INNER JOIN for exactly the countries this query exists to keep. Keeping the condition in ON instead restricts WHICH orders get joined in the first place, before the LEFT JOIN's NULL-padding behavior for unmatched countries even applies, so a country with no qualifying orders still gets exactly one output row, NULL-padded, rather than being filtered out entirely.
Worked example
Given users Ann (US) and Bo (US) and Cy (Canada), with two US orders in the last 30 days ($80 for Ann, $70 for Bo) and zero Canada orders: the query above correctly returns US with total_revenue = 150 and unique_buyers = 2, and Canada with total_revenue = 0 and unique_buyers = 0, exactly the zero-fill behavior the question asks for. Moving the same date condition into a WHERE clause instead, ... LEFT JOIN orders o ON o.user_id = u.user_id WHERE o.occurred_at >= (reference_date - interval '30 days') ..., silently drops Canada from the result entirely: US still shows 150/2, but Canada's LEFT-JOIN-produced NULL row fails the WHERE condition and vanishes, exactly the bug this pattern is built to avoid.
Trade-offs and pitfalls
The subtlety worth calling out explicitly: this is zero-filling over a DIMENSION (every country that exists), not over TIME (every month that exists), the distinction from the previous question. Both use the identical "start from the complete side, LEFT JOIN the activity" mechanic; recognizing the shared shape across dimension-completeness and time-completeness is more valuable than treating them as two unrelated tricks.
Given orders(order_id, customer_id, order_date, total_amount), write a query returning for each customer: first_order_date, last_order_date, total_orders, and lifetime_value (SUM of total_amount). Why are MIN/MAX useful for customer lifecycle reporting?
Sample Answer
A customer lifecycle summary combines four aggregates, first and last date via MIN/MAX, count via COUNT, and total revenue via SUM, in a single GROUP BY pass, since all four are independently computable from the same grouped rows.
Structured elaboration
SELECT customer_id,
MIN(order_date) AS first_order_date,
MAX(order_date) AS last_order_date,
COUNT(*) AS total_orders,
SUM(total_amount) AS lifetime_value
FROM orders
GROUP BY customer_id;
Each of the four aggregates operates independently over the same set of grouped rows; there's no ordering dependency or intermediate step needed between them; a single scan of each customer's orders is enough to compute all four simultaneously. MIN/MAX here answer "when did this relationship start and how recently was it active"; COUNT and SUM answer "how much has this customer engaged and spent".
Worked example
Given customer 1 with orders on 2025-01-01 ($100) and 2025-03-01 ($50): the query returns first_order_date 2025-01-01, last_order_date 2025-03-01, total_orders 2, lifetime_value $150, all computed in one pass over the customer's two order rows.
Trade-offs and pitfalls
This exact four-metric shape (first, last, count, sum) is common enough to be worth recognizing as its own named pattern (a basic customer-lifecycle or RFM (recency, frequency, monetary)-adjacent summary), rather than four separate ad hoc aggregate choices; interviewers sometimes extend it by asking for a fifth derived metric, like average days between orders, which needs the dates and count already computed here as inputs to a further calculation.
Given customers(email VARCHAR), write a query returning customers whose email domain is gmail.com or yahoo.com, case-insensitively. Show the PostgreSQL ILIKE form and a portable form using LOWER() for databases without ILIKE.
Sample Answer
PostgreSQL's ILIKE does case-insensitive pattern matching directly; for engines without it, wrapping both sides in LOWER() gets the same result.
Structured elaboration
-- PostgreSQL
SELECT email FROM customers WHERE email ILIKE '%@gmail.com' OR email ILIKE '%@yahoo.com';
-- Portable (no ILIKE)
SELECT email FROM customers WHERE LOWER(email) LIKE '%@gmail.com' OR LOWER(email) LIKE '%@yahoo.com';
Both domains need their own comparison, joined with OR: there's no single LIKE pattern that matches "ends in gmail.com or ends in yahoo.com" in one clause, since a pattern only expresses one shape at a time. Note the pattern literals themselves must already be lowercase in the second, portable form, since only the column side is being normalized by LOWER().
Worked example
Given emails 'a@Gmail.com', 'b@YAHOO.com', 'c@other.com': both queries correctly return the first two rows (matching regardless of how the domain's case varies) and exclude the third, since 'other.com' matches neither the gmail.com nor the yahoo.com branch of the OR.
Trade-offs and pitfalls
Wrapping the column in LOWER() (or any function) can prevent the engine from using a plain B-tree index on that column, since the index is built on the raw values, not their lowercased form; a functional index on LOWER(email) recovers the ability to seek instead of scan, at the cost of maintaining an extra index. This is worth mentioning but isn't required to answer the query itself correctly.
Describe how to write a parameterized SQL query for a report where the user can optionally filter by product_category and/or region. Show a template using placeholders, and how to make the filter a no-op when a parameter is NULL or not provided.
Sample Answer
A parameterized filter that should be a no-op when its parameter isn't supplied needs the "parameter is NULL, so don't filter" condition combined with the real comparison via OR, evaluated once per optional parameter.
Structured elaboration
SELECT order_id FROM orders
WHERE (:category IS NULL OR product_category = :category)
AND (:region IS NULL OR region = :region);
Each optional filter is wrapped in its own (:param IS NULL OR column = :param) clause: when the parameter is NULL, the left side of the OR is TRUE, making the whole clause TRUE regardless of the column's value (a no-op filter); when the parameter has a real value, the left side is FALSE, so the actual comparison on the right side is what determines whether the row qualifies. The same pattern generalizes cleanly to any number of independent optional filters, ANDed together.
Worked example
Given orders in categories electronics (region east) and toys (region west), with :category = 'electronics' and :region left unset (NULL): the query correctly returns only the electronics order, applying the category filter while the region clause is a no-op due to its NULL parameter.
Trade-offs and pitfalls
This pattern is convenient to write but has a real performance cost worth naming: the OR construction typically defeats a plain index on the filtered column, since the optimizer can't assume the comparison will always run; for a report with heavy, frequent optional-filter usage at scale, some engines and query builders instead generate the WHERE clause dynamically (omitting a condition entirely when its parameter is absent) rather than relying on this always-present-but-sometimes-no-op OR pattern, trading a bit of code-generation complexity for better index usage.
Discuss the trade-offs of referring to GROUP BY columns by ordinal position (GROUP BY 1, 2) versus repeating the full expression versus using a CTE/alias. When is each acceptable in production SQL?
Sample Answer
GROUP BY 1, 2 (positional) is terser but fragile under refactoring; repeating the full expression is explicit but verbose and error-prone to keep in sync; a CTE (Common Table Expression) with a named alias is usually the most maintainable middle ground.
Structured elaboration
-- Positional: fragile if SELECT list columns get reordered
SELECT region, DATE_TRUNC('month', order_date), SUM(amount) FROM orders GROUP BY 1, 2;
-- Repeated expression: verbose, and easy to accidentally diverge from the SELECT list
SELECT region, DATE_TRUNC('month', order_date) AS month, SUM(amount)
FROM orders GROUP BY region, DATE_TRUNC('month', order_date);
-- CTE with alias: compute once, group by the readable name
WITH base AS (
SELECT region, DATE_TRUNC('month', order_date) AS month, amount FROM orders
)
SELECT region, month, SUM(amount) FROM base GROUP BY region, month;
Positional GROUP BY is standard SQL and works everywhere, but if someone later reorders or adds a column to the SELECT list, the grouping silently changes to match different columns, a genuinely dangerous refactoring hazard. Repeating the expression avoids that but means the transformation logic is duplicated and can drift if only one copy is edited. A CTE materializes the computed expression once under a name, so both the SELECT list and the GROUP BY reference the same alias with no duplication.
Worked example
Given orders(region, order_date, amount) with rows (US, 2024-01-05, 100), (US, 2024-01-20, 50), (EU, 2024-01-10, 30), (US, 2024-02-01, 40): the original query, SELECT region, DATE_TRUNC('month', order_date), SUM(amount) FROM orders GROUP BY 1, 2, correctly returns three rows: EU/January 30, US/January 150, US/February 40.
Now suppose a teammate inserts customer_segment as a new first column in the SELECT list (every row here happens to be segment 'B2C') and forgets to update the GROUP BY: SELECT customer_segment, region, DATE_TRUNC('month', order_date), SUM(amount) FROM orders GROUP BY 1, 2. The GROUP BY clause still says 1, 2, but those ordinals now point at customer_segment and region, not region and the month expression. Because the third column (the month) is no longer part of the grouping, engines diverge sharply on what happens: strict engines like PostgreSQL raise an error (every non-aggregated SELECT column must appear in GROUP BY), while others (SQLite, and MySQL outside strict mode) silently pick an arbitrary month value per group and merge everything else. On the latter, the result silently collapses to two rows, B2C/EU 30 and B2C/US 190, with the January 150 and February 40 for US silently summed together into one bucket, no error and no warning that two different months got merged.
Trade-offs and pitfalls
For a one-off, throwaway query, positional GROUP BY is fine and common in ad hoc analysis. For anything that will live in a dashboard, a scheduled report, or a codebase, prefer the CTE-with-alias pattern: it reads clearly and is safe under later edits to the SELECT list.
Unlock Full Question Bank
Get access to all SQL Query Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.