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 orders(order_id, created_at TIMESTAMP), explain why filtering March 2024 with created_at BETWEEN '2024-03-01' AND '2024-03-31' can miss rows, since created_at includes a time-of-day. Write a correct, index-friendly query using a half-open range instead.
Sample Answer
A TIMESTAMP column includes a time-of-day component, so a date-only BETWEEN upper bound like '2024-03-31' is treated as midnight at the start of that day, silently excluding every row later that same day; a half-open range using the next day's start avoids the gap.
Structured elaboration
-- Misses late-March-31 rows
SELECT order_id FROM orders WHERE created_at BETWEEN '2024-03-01' AND '2024-03-31';
-- Correct half-open range
SELECT order_id FROM orders WHERE created_at >= '2024-03-01' AND created_at < '2024-04-01';
BETWEEN '2024-03-01' AND '2024-03-31' is shorthand for >= '2024-03-01' AND <= '2024-03-31', and that upper bound, when compared against a TIMESTAMP, is interpreted as 2024-03-31 00:00:00. Any row timestamped later that same day (say, 2024-03-31 23:00:00) is strictly greater than midnight and gets excluded, even though it clearly belongs in "March 2024" by any reasonable interpretation.
Worked example
Given orders at 2024-03-31 23:00:00 and 2024-03-15 10:00:00: the BETWEEN version returns only the March 15 order, silently dropping the March 31 order entirely. The half-open version (< '2024-04-01') correctly returns both orders.
Trade-offs and pitfalls
The half-open-range fix generalizes to any period boundary (a single day, a month, a quarter, a year): always express the upper bound as "the start of the next period, exclusive" rather than "the last moment of this period, inclusive", since the latter requires knowing the column's precision exactly (is it seconds? milliseconds? does '2024-03-31 23:59:59' actually cover a row at '2024-03-31 23:59:59.500'?) while the former never does. This same half-open form is also what makes the query index-friendly, which the question asks for by name: created_at >= '2024-03-01' AND created_at < '2024-04-01' compares the raw created_at column directly against two literal bounds, exactly the shape a B-tree index (the default index structure in most relational engines, storing column values in sorted order) on created_at can use for a plain range scan. A common alternative fix, wrapping the column instead of the bound, e.g. WHERE DATE(created_at) BETWEEN '2024-03-01' AND '2024-03-31' or CAST(created_at AS DATE) = ..., looks similarly correct but applies a function to every row's created_at value before comparing it, which prevents a plain index on created_at from being used at all, since the engine can no longer look up sorted values directly and instead has to compute the expression for every row. Keeping the column bare on one side of a plain comparison is what index-friendly means in practice.
Explain why WHERE user_id NOT IN (SELECT user_id FROM deactivated_users) can return zero rows whenever the subquery returns even one NULL. Provide the corrected version using NOT EXISTS and an example demonstrating the difference.
Sample Answer
When the subquery in NOT IN (SELECT ...) returns even a single NULL, the entire NOT IN comparison becomes UNKNOWN for every outer row, silently returning zero results. NOT EXISTS doesn't have this problem.
Structured elaboration
user_id NOT IN (2, NULL) conceptually expands to user_id != 2 AND user_id != NULL. The second comparison is UNKNOWN for every row (per the NULL-equality rule above), and TRUE AND UNKNOWN is UNKNOWN, not TRUE. So no row can ever satisfy the whole predicate once the list contains a NULL, no matter what user_id is. NOT EXISTS avoids this because it's checking for the existence of a matching row, not comparing values directly against a NULL, so a NULL in the subquery's rows simply fails to match rather than poisoning the entire comparison.
Worked example
Given deactivated_users(2, NULL) and users(1, 2, 3): WHERE user_id NOT IN (SELECT user_id FROM deactivated_users) returns zero rows for all three users, including users 1 and 3 who clearly aren't deactivated. The corrected version, WHERE NOT EXISTS (SELECT 1 FROM deactivated_users d WHERE d.user_id = u.user_id), correctly returns users 1 and 3.
Trade-offs and pitfalls
This is a genuinely dangerous bug because it fails silently: no error, just an empty or wrong result set, and it only shows up once the subquery's source table happens to accumulate a NULL, which might be well after the query was written and tested. The safest habit is to default to NOT EXISTS for any "not in this other set" logic, and treat NOT IN (subquery) as something to double-check for NULLability every time, or guard it explicitly with WHERE user_id NOT IN (SELECT user_id FROM deactivated_users WHERE user_id IS NOT NULL).
Given events(event_id, user_id, event_type, occurred_at), write a query computing Daily Active Users (DAU) for the last 30 full days: count of distinct users per UTC day, treating multiple same-day events per user as one. Compare writing this with COUNT(DISTINCT ...) versus GROUP BY, and note performance considerations at scale.
Sample Answer
A distinct-count-per-period metric like Daily Active Users needs COUNT(DISTINCT user_id) specifically, not a plain COUNT, because a plain COUNT would count every event, over-counting any user who was active more than once in the same period.
Structured elaboration
SELECT DATE(occurred_at) AS day, COUNT(DISTINCT user_id) AS dau
FROM events
GROUP BY day;
COUNT(DISTINCT user_id) deduplicates within each day's group, so a user who logged three events on the same day still contributes exactly 1 to that day's count, correctly answering "how many distinct users were active", not "how many events happened". The GROUP BY-based alternative pushes the deduplication into an inner query instead of an aggregate function: SELECT day, COUNT(*) AS dau FROM (SELECT DISTINCT DATE(occurred_at) AS day, user_id FROM events) t GROUP BY day. The inner SELECT DISTINCT collapses each user down to at most one row per day first, so by the time the outer COUNT(*) runs there's nothing left to deduplicate, it's just counting already-unique rows.
Worked example
Given events for user 1 twice and user 2 once, all on 2025-01-01, and user 3 once on 2025-01-02: the query correctly returns DAU of 2 for 2025-01-01 (users 1 and 2, with user 1's repeat event not double-counted) and 1 for 2025-01-02 (user 3).
Trade-offs and pitfalls
Both forms are logically equivalent and, on the worked example below, return the identical numbers; which one an optimizer executes faster can differ by engine and data distribution, so it's worth trying both against real data rather than assuming one is always better.
COUNT(DISTINCT ...) is measurably more expensive than a plain COUNT at large scale, since the engine typically needs to sort or hash the values to deduplicate them; for very high-cardinality, very large-scale distinct counting (billions of events per day), an approximate distinct-count function (HyperLogLog-based, such as Postgres's hll extension or BigQuery's APPROX_COUNT_DISTINCT) trades a small, bounded error for dramatically better performance, a trade-off worth naming even though it's outside this topic's core scope.
A global dashboard aggregates orders by day. Describe a strategy for correct daily aggregation across time zones: storing timestamps in UTC, converting to a target time zone at aggregation time, and handling daylight saving time. Give sample SQL computing daily revenue in a specific time zone (e.g., America/Los_Angeles).
Sample Answer
Correct daily aggregation across time zones for a global dashboard starts with storing every timestamp in UTC, then converting to a target display time zone only at the point of aggregation, being careful that daylight saving transitions can make some local days 23 or 25 hours long.
Structured elaboration
A dependable strategy:
- Store in UTC. Every timestamp column should be UTC internally (or a genuine TIMESTAMP WITH TIME ZONE type that normalizes to UTC); never store "local time" without also storing which time zone it's local to.
- Convert at aggregation time, not at storage time:
date_trunc('day', created_at AT TIME ZONE 'America/Los_Angeles')groups rows by their LOCAL calendar day in that specific time zone, computed fresh from the UTC-stored value. - Account for daylight saving transitions. A "day" in a DST-observing time zone can be 23 or 25 hours long on the transition dates; a naive fixed-offset conversion (UTC-8 always) will misclassify some rows near the DST boundary, while using the time zone's actual rules (via
AT TIME ZONE 'America/Los_Angeles'rather than a hardcoded- interval '8 hours') handles the transition correctly.
SELECT date_trunc('day', created_at AT TIME ZONE 'America/Los_Angeles') AS local_day,
SUM(amount) AS daily_revenue
FROM orders
GROUP BY local_day
ORDER BY local_day;
Worked example
Consider an order placed at 2024-03-11 07:30:00 UTC, the day after the US 2024 spring-forward transition (clocks in America/Los_Angeles jumped from 2:00am to 3:00am, PST to PDT, on 2024-03-10, so by 2024-03-11 the zone is already on PDT, UTC-7). The correct conversion, date_trunc('day', '2024-03-11 07:30:00' AT TIME ZONE 'America/Los_Angeles'), resolves the timestamp's local time using PDT's actual UTC-7 offset: 2024-03-11 07:30:00 UTC becomes 2024-03-11 00:30:00 local, landing correctly in the 2024-03-11 bucket. A naive fixed-offset conversion that assumes PST (UTC-8) year-round, '2024-03-11 07:30:00 UTC' - interval '8 hours', instead computes 2024-03-10 23:30:00, misclassifying the exact same order into the 2024-03-10 bucket, a full day off from where it actually belongs in local time. The one-hour DST gap is enough to flip which calendar day an order near local midnight gets attributed to, and it only shows up on the handful of days per year straddling a transition, which is exactly what makes it easy to miss in testing and painful in production.
Trade-offs and pitfalls
A dashboard that needs to show "today's revenue" simultaneously and correctly for users in multiple time zones fundamentally cannot show one universal number; either pick one canonical reporting time zone company-wide and be explicit about it in the UI, or let each viewer see their own local-day aggregation, computed fresh per viewer rather than pre-aggregated once and reused.
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.
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.