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 transactions(transaction_id, user_id, amount DECIMAL(9,2), occurred_at), write a query returning transactions with amount between $50 and $500 inclusive. Show the equivalent query using explicit >= and <= instead of BETWEEN, and state whether BETWEEN is inclusive on both ends.
Sample Answer
BETWEEN is inclusive on both ends: amount BETWEEN 50 AND 500 means amount >= 50 AND amount <= 500.
Structured elaboration
The two forms are exactly equivalent:
-- BETWEEN
SELECT transaction_id FROM transactions WHERE amount BETWEEN 50 AND 500;
-- Explicit form
SELECT transaction_id FROM transactions WHERE amount >= 50 AND amount <= 500;
BETWEEN reads more naturally for a closed range and is the standard idiom; the explicit form is sometimes preferred when the range needs to be half-open (e.g., excluding the upper bound), since BETWEEN has no built-in way to express that.
Worked example
With amounts 49.99, 50.00, 300, 500.00, and 500.01: the query returns the middle three rows (50.00, 300, 500.00). 49.99 and 500.01 are correctly excluded, confirming both bounds are inclusive.
Trade-offs and pitfalls
On floating-point columns, a boundary value that "looks like" 500 might actually be stored as 499.9999999 due to representation error, silently falling outside an inclusive BETWEEN. This is one of several reasons DECIMAL/NUMERIC types are preferred over floating point for money. BETWEEN on TIMESTAMP columns has its own, more common trap: a date-only upper bound like occurred_at BETWEEN '2024-03-01' AND '2024-03-31' is interpreted as '2024-03-31 00:00:00', midnight at the very start of that day, so every transaction later that same day (say, 2024-03-31 18:00:00) is strictly greater than the upper bound and gets silently excluded, even though it clearly belongs in "March 2024" by any reasonable reading. The fix is the same half-open pattern used for numeric ranges: express the upper bound as the start of the NEXT period, exclusive, e.g. occurred_at >= '2024-03-01' AND occurred_at < '2024-04-01', which never depends on knowing the column's exact time precision.
Describe the practical differences between DELETE, TRUNCATE, and DROP. Cover transactional behavior and rollback, performance, permission requirements, and whether triggers fire for each.
Sample Answer
DELETE removes rows individually and can be filtered, rolled back, and will fire row-level triggers; TRUNCATE removes every row at once, is typically not filterable, is much faster since it deallocates storage pages rather than deleting row by row, and often can't be rolled back the same way (or fires no row-level triggers); DROP removes the table's structure entirely, not just its data.
Structured elaboration
- DELETE [FROM table WHERE ...]: a normal, logged, transactional operation. Can target a subset of rows via WHERE, participates in a transaction (rollback restores the deleted rows), and fires any row-level triggers defined on the table, once per deleted row.
- TRUNCATE TABLE: removes ALL rows (most engines don't support a WHERE clause on TRUNCATE at all), is minimally logged compared to DELETE (deallocating whole data pages rather than logging each row deletion), and is correspondingly much faster on a large table; in PostgreSQL it IS transactional and can be rolled back, but in some other engines it behaves as an auto-committing DDL (Data Definition Language: schema-altering commands like CREATE, ALTER, and DROP, as opposed to DML (Data Manipulation Language) commands like DELETE and INSERT that only touch row data)-like operation that cannot be rolled back once issued; row-level triggers typically do not fire for TRUNCATE, only certain engines' statement-level or TRUNCATE-specific triggers do.
- DROP TABLE: removes the table itself, structure, data, indexes, and constraints entirely; there's no table left to query afterward. On transactional behavior: DROP is DDL like TRUNCATE, and shares the same engine split, in PostgreSQL it runs inside a transaction block and can be rolled back like any other statement, while in some other engines (e.g., MySQL) it auto-commits immediately as DDL and cannot be undone once issued. On performance: DROP is at least as fast as TRUNCATE, typically faster, since it doesn't even need to keep an empty table structure around afterward, it just removes the storage and the catalog entry describing the table. On triggers: DROP fires no triggers at all, not row-level and not statement-level, because no row data is being touched, only the table's definition is being removed.
- Permissions: DELETE typically requires DELETE privilege on the table; TRUNCATE and DROP typically require a higher privilege level (often table-owner or a dedicated TRUNCATE/DROP grant), reflecting how much more destructive and irreversible-in-practice they are.
Worked example
Deleting all rows from a 10-million-row table with DELETE FROM t (no WHERE) works but is slow (logging each row individually) and, depending on engine and vacuum settings, may not immediately reclaim disk space; TRUNCATE TABLE t accomplishes the same "empty the table" goal far faster by deallocating storage directly, at the cost of losing per-row filtering and, on some engines, easy rollback.
Trade-offs and pitfalls
The practical decision rule: need to remove a SUBSET of rows, or need transactional rollback safety with certainty across all engines? Use DELETE. Need to empty an ENTIRE table fast and don't need row-level triggers to fire? TRUNCATE. Need the table to no longer exist at all, structure included? DROP. Confusing TRUNCATE for a "faster DELETE with a WHERE clause" is the most common practical mistake, since most engines simply don't support that.
Explain the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN, with a short example of when each would be used.
Sample Answer
INNER JOIN keeps only rows with a match on both sides; LEFT JOIN keeps every row from the left table, filling in NULLs for unmatched right-side columns; RIGHT JOIN is the mirror image (every right-table row kept); FULL OUTER JOIN keeps every row from both sides, matched or not.
Structured elaboration
Given customers and orders:
- INNER JOIN: only customers who have at least one order appear, one row per matching order.
- LEFT JOIN: every customer appears at least once, even those with zero orders (order columns come back NULL for them).
- RIGHT JOIN: every order appears, even one somehow pointing to a customer_id with no matching customer row (rare in practice with foreign keys enforced, but the join type still matters conceptually, and RIGHT JOIN A B is exactly equivalent to LEFT JOIN B A with sides swapped).
- FULL OUTER JOIN: every customer AND every order appear, matched where possible, NULL-padded where not; useful for reconciliation tasks (e.g., "which customers have no orders, and which orders point to no customer").
Worked example
Given customers Ann (id 1) and Bo (id 2), with only Ann having an order (order 10): INNER JOIN returns only (Ann, order 10). LEFT JOIN returns (Ann, order 10) AND (Bo, NULL), since Bo is kept even without a match.
Now add order 20, which points to customer_id 3 (no matching customer row, e.g. because the customer was deleted after placing the order, or bad data): RIGHT JOIN returns (Ann, order 10) AND (NULL, order 20), keeping order 20 even though it has no matching customer, mirroring how LEFT JOIN kept Bo despite no matching order. FULL OUTER JOIN returns all three rows: (Ann, order 10), (Bo, NULL), and (NULL, order 20), the union of everything LEFT JOIN and RIGHT JOIN would each produce separately, capturing both the customer with no order and the order with no customer in one result.
Trade-offs and pitfalls
The choice isn't stylistic: "how many customers do we have" needs a query that includes zero-order customers (LEFT JOIN, or better, no join at all if orders data isn't needed), while "what's our order fulfillment rate" naturally starts from an INNER JOIN or the orders table directly. Choosing INNER JOIN by habit when LEFT JOIN was needed is a common way to silently under-report a metric (e.g., "average orders per customer" excluding the zero-order customers entirely, inflating the average).
Given customers(id), orders(order_id, customer_id), and order_items(order_item_id, order_id, product_id, qty, unit_price), compute total revenue per customer. Explain why joining customers directly to order_items and then grouping can silently double-count revenue, and show the safe pattern: pre-aggregate order_items to order totals first, then join up to customers.
Sample Answer
Joining a customers table directly to order_items and summing produces an inflated total whenever a customer has more than one order, because each order's line items get re-multiplied by however many order rows are being joined through; pre-aggregating order_items to order-level totals first, then joining up, avoids the inflation.
Structured elaboration
-- WRONG shape (works fine for a single order, but is a latent bug)
SELECT c.id, SUM(oi.qty * oi.unit_price) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.id;
-- SAFE shape: pre-aggregate order_items to order totals, then join up
WITH order_totals AS (
SELECT order_id, SUM(qty * unit_price) AS order_revenue
FROM order_items GROUP BY order_id
)
SELECT c.id, COUNT(o.order_id) AS order_count, SUM(ot.order_revenue) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_totals ot ON ot.order_id = o.order_id
GROUP BY c.id;
The bug in the first shape isn't in the SUM itself, it's that the join produces one row per (order, order_item) pair, and a customer-level COUNT or a mis-scoped aggregate over that joined result silently reflects the item-level grain, not the order-level or customer-level grain you're mentally picturing.
Worked example
A customer with one order containing two line items ($100 and $30, order total $130): a naive COUNT(o.order_id) after joining through order_items returns 2 (one count per line item), not 1 (the actual number of orders), even though SUM(qtyunit_price) happens to still total correctly to $130 in this single-order case. Pre-aggregating order_items to order totals first, then joining, correctly reports order_count = 1 and revenue = $130. The risk compounds with more orders: any customer-level COUNT taken directly off the item-joined result will always be inflated by however many items each order has, while SUM(qtyunit_price) itself stays numerically correct only because multiplication and summation happen to commute here, a coincidence that doesn't extend to non-additive metrics like COUNT or AVG taken at the wrong grain.
Trade-offs and pitfalls
The general rule: whenever a query joins through a one-to-many (or many-to-many) relationship, ask explicitly "what does one row of this joined result actually represent" before writing any aggregate on top of it, and pre-aggregate to the coarser grain BEFORE joining up to an even coarser one, rather than aggregating across every level in a single pass.
Why should production dashboards and ETL queries avoid SELECT *? Give at least three concrete reasons (performance, schema drift, readability) with examples of better alternatives.
Sample Answer
SELECT * pulls back every column, including ones the query doesn't need, ones that might be large (long text/blob columns), and ones that could change shape entirely if the table's schema evolves, none of which serve a production dashboard or ETL (extract, transform, load) job well.
Structured elaboration
Three concrete reasons to avoid SELECT * outside of quick ad hoc exploration:
- Performance: pulling unnecessary columns (especially wide or large ones) wastes I/O and network transfer, particularly costly at scale or across a network boundary (an API layer, a BI (business intelligence) tool's live connection).
- Schema drift: if a column is later added to the table, SELECT * silently starts returning it too, potentially breaking a downstream consumer that assumes a fixed column count or order, or bloating a report that never needed the new column in the first place. If a column is renamed or dropped, SELECT * consumers may break in ways an explicit column list would have caught earlier, at the point of the schema change rather than downstream.
- Readability: an explicit column list documents, right in the query, exactly what data is being used; SELECT * forces a reader to go look up the table's current schema to understand what's actually being returned.
Worked example
A dashboard query using SELECT * FROM orders continues to "work" (no error) after a new internal_notes text column is added to the orders table, but now silently transmits and potentially displays that column's contents, information the dashboard's author never intended to expose and the report's consumers never asked for.
Trade-offs and pitfalls
The better alternative is always naming the specific columns needed, even when that's more typing up front; some teams additionally rely on a view (a stored, named SELECT with an explicit column list) as a stable interface layer specifically so downstream consumers are insulated from the base table's schema evolving underneath them.
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.