Scenario-based SQL query interview questions
Practice scenario-based SQL query interview questions with PostgreSQL solutions, expected results, and checks for event order, missing replies, and time gaps.

Scenario-based SQL query interview questions ask you to turn a business problem into a query and justify the returned rows. These 10 original questions cover date filters, missing replies, current status, sessions, and ordered events, with model answers and two runnable PostgreSQL tasks. You'll also change an event timestamp to check whether a plausible answer follows the actual business sequence.
Reporting boundaries and counting units
Reporting boundaries and counting units define which records belong in your answer and what each result represents.
1. "A support manager wants tickets opened during March 2026. How would you filter the timestamps without including April tickets?"
Model answer: Use an inclusive lower boundary of March 1, 2026,
and an exclusive upper boundary of April 1, 2026. Confirm which
time zone defines the reporting month. Don't assume a final instant
on March 31 covers every possible timestamp precision.
The interviewer listens for: A half-open interval, meaning the start
is included and the end is excluded, plus explicit reporting boundaries.
2. "A ticket can have several replies. The manager asks how many tickets received a reply, not how many replies were sent. How would you calculate the answer?"
Model answer: Count distinct ticket identifiers among qualifying
reply events, or select tickets with at least one qualifying reply
and count those tickets. Counting reply rows answers a different
question because one ticket can contribute several replies.
The interviewer listens for: A clear counting unit and protection
against repeated replies inflating the ticket count.
Rehearse those distinctions with Interview questions: basics before moving to the query-writing tasks.
First responses and missing replies
First-response questions require the earliest valid reply, while missing-reply questions require the absence of any valid reply. Both tasks below use PostgreSQL and fictional data. Each WITH clause defines common table expressions: named query results used by the rest of the same statement.
Run question 3 unchanged first. Then, in the replies data, change ticket 1's 09:20 timestamp to 09:40 and rerun the entire statement. The existing 09:25 reply should become the first response, even though that reply appears later in the source.
-- 3. "Write a query returning tickets whose first valid reply arrived
-- within 30 minutes of opening. Ignore replies before opening."
-- Target: first valid reply is at or after opening and no later than
-- opening + 30 minutes. Return one row per qualifying ticket.
-- Starting data: three tickets and three replies, defined below.
-- Model: ticket 1 = 20 minutes; ticket 2 = 45 minutes;
-- ticket 3 has no reply. Only ticket 1 qualifies.
WITH tickets(ticket_id, opened_at) AS (
VALUES
(1, TIMESTAMP '2026-03-02 09:00:00'),
(2, TIMESTAMP '2026-03-02 10:00:00'),
(3, TIMESTAMP '2026-03-02 11:00:00')
), replies(ticket_id, replied_at) AS (
VALUES
(1, TIMESTAMP '2026-03-02 09:20:00'),
(1, TIMESTAMP '2026-03-02 09:25:00'),
(2, TIMESTAMP '2026-03-02 10:45:00')
)
SELECT t.ticket_id, MIN(r.replied_at) AS first_reply_at
FROM tickets AS t
JOIN replies AS r
ON r.ticket_id = t.ticket_id
AND r.replied_at >= t.opened_at
GROUP BY t.ticket_id, t.opened_at
HAVING MIN(r.replied_at) <= t.opened_at + INTERVAL '30 minutes'
ORDER BY t.ticket_id;
-- Expected output:
-- ticket_id | first_reply_at
-- 1 | 2026-03-02 09:20:00
--
-- Change: in replies, replace ticket 1's 09:20:00 with 09:40:00.
-- Rerun the entire statement.
-- New calculation: MIN(09:40, 09:25) = 09:25; elapsed = 25 minutes.
-- Expected changed output:
-- ticket_id | first_reply_at
-- 1 | 2026-03-02 09:25:00
--
-- Model answer: Match valid replies, group by ticket, and filter
-- the earliest reply with HAVING. MIN doesn't depend on source order.
-- The interviewer listens for: Correct aggregation, an inclusive
-- deadline, and independence from insertion order.
For question 4, run the next statement independently. Its starting data restores the original reply timestamps. NOT EXISTS tests whether the matching inner query returns no rows; a correlated query refers to the ticket currently being tested.
-- 4. "Write a query returning tickets with no valid reply at all.
-- A reply before the ticket opened doesn't count."
-- Target: return tickets with no reply at or after opening.
-- Starting data: three tickets and three replies, defined below.
-- Model: tickets 1 and 2 have valid replies; ticket 3 doesn't.
WITH tickets(ticket_id, opened_at) AS (
VALUES
(1, TIMESTAMP '2026-03-02 09:00:00'),
(2, TIMESTAMP '2026-03-02 10:00:00'),
(3, TIMESTAMP '2026-03-02 11:00:00')
), replies(ticket_id, replied_at) AS (
VALUES
(1, TIMESTAMP '2026-03-02 09:20:00'),
(1, TIMESTAMP '2026-03-02 09:25:00'),
(2, TIMESTAMP '2026-03-02 10:45:00')
)
SELECT t.ticket_id
FROM tickets AS t
WHERE NOT EXISTS (
SELECT 1
FROM replies AS r
WHERE r.ticket_id = t.ticket_id
AND r.replied_at >= t.opened_at
)
ORDER BY t.ticket_id;
-- Expected output:
-- ticket_id
-- 3
--
-- Model answer: Use NOT EXISTS to test the absence of a qualifying
-- reply for each ticket. Ticket 2 is late, but isn't unanswered.
-- The interviewer listens for: A correlated existence test and
-- the distinction between a late response and a missing response.
Try writing a fresh solution through Practice: query a table. The Work Gym checks exercises automatically and gives a hint that names the mistake.
Previous events and current status
Previous-event and current-status calculations need a separate sequence for each ticket and an explicit ordering rule. A window function calculates across related rows without collapsing them into one grouped result. PARTITION BY separates tickets; ORDER BY establishes the sequence within each ticket.
5. "Each ticket has several status events. How would you calculate the time between each event and the previous event for that ticket?"
Model answer: Use LAG to retrieve the preceding timestamp within
each ticket, ordered by event timestamp and a stable event identifier.
Subtract that timestamp from the current timestamp. The first event
has no predecessor, so its gap is NULL, not zero.
The interviewer listens for: Separation by ticket, explicit ordering,
a tie-breaker, and correct treatment of the missing predecessor.
6. "A ticket's history contains open, closed, and reopened events. How would you return each ticket's current status?"
Model answer: Order each ticket's events newest first, assign
ROW_NUMBER within each ticket, and select row number one in an outer
query. Use a documented tie-breaker for equal timestamps. Filtering
to closed events before numbering finds the latest closure, not
the current status.
The interviewer listens for: Ranking the complete relevant history,
repeatable selection, and recognition that reopened isn't closed.
Sessions and ordered funnels
A session is a group of activity events; a funnel is a required progression through steps. Clarify whether equal timestamps count as sequential events before choosing comparison operators.
7. "Group each user's activity into sessions. A new session starts only when the gap from the preceding event exceeds 30 minutes. How would you build the query?"
Model answer: First use LAG within each user to get the previous
timestamp. In a second query stage, mark the first event and every
gap greater than 30 minutes as a new session. In a third stage,
calculate a running SUM of those markers within each user, ordered
consistently. Use an explicit ROWS window frame, which defines the
rows included in each running calculation. Exactly 30 minutes stays
in the same session.
The interviewer listens for: Separate stages for dependent window
calculations, the exact boundary rule, and sequencing rather than
simply grouping activity by calendar day.
8. "Count users who viewed a product, then added it to their cart, then purchased it within 24 hours of that view. How would you prevent unrelated events from creating a false conversion?"
Model answer: Match events for the same user and product. For each
candidate view, require a strictly later cart event and a strictly
later purchase, with purchase no more than 24 hours after that view.
Count each qualifying user once. Independent flags for the three
event types don't prove their order.
The interviewer listens for: Matching identifiers, explicit timestamp
comparisons, a window measured from the view, and protection against
multiple matching combinations inflating the user count.
Late arrivals and result checks
Late arrivals reveal whether your query follows when an action happened or when its record reached the system. Event time records the action's time; ingestion time records receipt by the system. Those timestamps serve different reporting purposes.
9. "Yesterday's activity report changes after an older event arrives today. Which timestamp should drive the report, and how would you handle the update?"
Model answer: Use event time when reporting when activity happened.
Use ingestion time to identify newly received records, then recompute
affected periods or users under an explicit late-data policy.
Session calculations may need neighboring events because an inserted
event can change previously calculated gaps.
The interviewer listens for: Separation of event time and ingestion
time, an explicit reporting policy, and recognition that updating
only the newly arrived row can leave derived results wrong.
10. "Your event-sequence query returns plausible results. What checks would you run before presenting the answer?"
Model answer: Create small cases with no events, one event, repeated
events, equal timestamps, exact time boundaries, and out-of-order
arrival. Calculate expected results manually. Changing source row
order shouldn't change the answer. Adding an older event may change
the business sequence, so investigate affected results. Inspect the
execution plan separately to assess how the database runs the query.
The interviewer listens for: Concrete counterexamples, independent
expected results, repeatable answers, and separation of correctness
from performance.
- Name the entity: ticket, user, or user-product pair.
- State the sequence and whether boundaries include equal timestamps.
- Predict the result before running the query.
- Change one event and explain which results should change.
Small fictional cases expose logic errors, but they don't establish production performance or resolve ambiguous timestamps. If the source doesn't establish event order, describe the ambiguity rather than inventing a sequence.
Common questions
Which SQL dialect do these scenario solutions use? The runnable solutions use PostgreSQL, including its timestamp literals and interval arithmetic. SQL Server, MySQL, and other databases may require different date arithmetic syntax.
What should I clarify before writing an event-sequence query? Clarify the entity being tracked, the required sequence, the time boundary, and the reporting time zone. Also ask whether duplicate events, equal timestamps, and late arrivals have defined business rules.
How should I handle events with identical timestamps? Use a documented ordering field that establishes the required sequence. A stable identifier can make selection repeatable, but it doesn't necessarily prove business chronology; if no field establishes chronology, report the ambiguity.
Practice what this post teaches
Use SQL interview practice to rehearse explaining your assumptions, query, and result checks together.