Reconstruct the Latest State of Every Listing
SQL & DataModel answerLast updated
Query an event-log table to produce one row per listing showing its most recent status and total lifespan in hours.
Background
A marketplace platform records every status change for its listings in an event log. Each row captures a single transition — nothing is ever updated in place. To answer business questions you need to reconstruct the current state of every listing from that history.
Table: listing_events
| Column | Type | Description |
|---|---|---|
event_id | INT | Unique identifier for this log entry |
listing_id | INT | The listing this event belongs to |
status | VARCHAR | New status after the transition (e.g. 'ACTIVE', 'PENDING', 'SOLD', 'WITHDRAWN') |
occurred_at | TIMESTAMP | When the transition happened |
Your Task
Write a SQL query that returns one row per listing with three columns:
| Column | Definition |
|---|---|
listing_id | The listing identifier |
current_status | The status from the most recent event for that listing |
lifespan_hours | Elapsed hours between the listing's very first and very last event; 0.0 for listings with only one event |
Order the results by listing_id ascending.
Example
Input
| event_id | listing_id | status | occurred_at |
|---|---|---|---|
| 1 | 201 | ACTIVE | 2024-03-01 08:00:00 |
| 2 | 201 | PENDING | 2024-03-01 11:30:00 |
| 3 | 201 | SOLD | 2024-03-02 08:00:00 |
| 4 | 202 | ACTIVE | 2024-03-01 09:00:00 |
Expected Output
| listing_id | current_status | lifespan_hours |
|---|---|---|
| 201 | SOLD | 24.0 |
| 202 | ACTIVE | 0.0 |
Constraints
listing_idvalues repeat across rows (one listing has many events).occurred_atis strictly increasing within a single listing — no two events for the same listing share the same timestamp.- Every row in the table belongs to a listing with at least one event.
- Return
lifespan_hoursas a decimal, not truncated to an integer (3.5, not3).
Hints
Hint 1
The most recent status is not MAX(status) — that gives the alphabetically last value, not the chronologically last one. You need the status that belongs to the row with the latest occurred_at.
Hint 2
ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY occurred_at DESC) lets you tag the latest event as rn = 1. On that row, occurred_at is already the maximum, so you don't need a separate MAX pass — attach MIN(occurred_at) as a window function on the same partition and subtract.
Hint 3
Watch out for integer division when converting seconds to hours. Divide by 3600.0 (a float literal), not 3600, or a 90-minute lifespan silently becomes 1 instead of 1.5.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The output needs two different kinds of facts per listing:
- An aggregate fact — the earliest and latest timestamps, which
MIN/MAXcan compute across the whole group. - A row-level fact — the
statusvalue that lives on the latest-timestamp row specifically.
MAX(status) does not solve the second need. It returns the alphabetically greatest status string, which has nothing to do with chronological order. The core challenge is retrieving a column value from a specific row within a group — exactly what window functions are designed for.
Window-function solution (PostgreSQL)
WITH ranked AS (
SELECT
listing_id,
status,
occurred_at,
MIN(occurred_at) OVER (PARTITION BY listing_id) AS first_event,
ROW_NUMBER() OVER (
PARTITION BY listing_id
ORDER BY occurred_at DESC,
event_id DESC -- deterministic tie-break (constraints rule these out, but good habit)
) AS rn
FROM listing_events
)
SELECT
listing_id,
status AS current_status,
EXTRACT(EPOCH FROM (occurred_at - first_event)) / 3600.0 AS lifespan_hours
FROM ranked
WHERE rn = 1
ORDER BY listing_id;
On the rn = 1 row, occurred_at is the latest timestamp for that listing, so there's no need for a separate MAX pass. Subtracting first_event from it gives the total span. For a listing with one event the two values are identical, so lifespan_hours is 0.0 with no special-case logic required.
Dialect differences for the timestamp subtraction:
| Dialect | Expression |
|---|---|
| PostgreSQL | EXTRACT(EPOCH FROM (max_t - min_t)) / 3600.0 |
| MySQL / MariaDB | TIMESTAMPDIFF(SECOND, min_t, max_t) / 3600.0 |
| SQL Server | DATEDIFF(SECOND, min_t, max_t) / 3600.0 |
| SQLite | (julianday(max_t) - julianday(min_t)) * 24.0 |
Alternative: aggregate then self-join
SELECT
agg.listing_id,
e.status AS current_status,
EXTRACT(EPOCH FROM (agg.last_event - agg.first_event)) / 3600.0 AS lifespan_hours
FROM (
SELECT listing_id,
MIN(occurred_at) AS first_event,
MAX(occurred_at) AS last_event
FROM listing_events
GROUP BY listing_id
) agg
JOIN listing_events e
ON e.listing_id = agg.listing_id
AND e.occurred_at = agg.last_event
ORDER BY agg.listing_id;
This works on any engine, but it has a latent bug: if two events ever share the maximum timestamp, the join produces duplicate rows. The ROW_NUMBER approach always emits exactly one row per listing regardless, which is why it's the preferred answer.
Python / pandas solution
import pandas as pd
def listing_summary(events: pd.DataFrame) -> pd.DataFrame:
"""Return listing_id, current_status, lifespan_hours for each listing."""
if events.empty:
return pd.DataFrame(
columns=["listing_id", "current_status", "lifespan_hours"]
)
df = events.copy()
df["occurred_at"] = pd.to_datetime(df["occurred_at"])
# Sort so that .first() / .last() within each group reflect chronological order
df = df.sort_values(["listing_id", "occurred_at", "event_id"])
summary = df.groupby("listing_id", as_index=False).agg(
current_status=("status", "last"),
first_event=("occurred_at", "first"),
last_event=("occurred_at", "last"),
)
summary["lifespan_hours"] = (
(summary["last_event"] - summary["first_event"]).dt.total_seconds() / 3600.0
)
return summary[["listing_id", "current_status", "lifespan_hours"]]
The sort before groupby is critical. Pandas' "last" aggregator means the last row in dataframe order, not the latest timestamp. Sorting first makes the two definitions equivalent.
Complexity
- Time: O(n log n) to sort the rows within each partition. With a covering index on
(listing_id, occurred_at DESC)the engine reads rows already in order, making the effective cost O(n). - Space: O(n) for the window buffer; the output is O(L) where L is the number of distinct listings.
Edge cases to cover in an interview
- Single-event listings. The subtraction yields zero naturally — no
CASEorNULLIFneeded. - Integer division.
/ 3600truncates;/ 3600.0preserves the decimal. Always use the float literal. - Timestamp ties. The problem rules them out, but adding
event_id DESCas a secondary sort key costs nothing and keeps results deterministic if the constraint is ever relaxed. - NULL timestamps.
MIN/MAXskip NULLs silently. In PostgreSQL,ORDER BY occurred_at DESCplaces NULLs first by default, so a NULL row could claimrn = 1. Defend withORDER BY occurred_at DESC NULLS LASTor aWHERE occurred_at IS NOT NULLfilter. - Time-zone mismatches. Mixing
TIMESTAMPandTIMESTAMPTZ, or events logged across a DST boundary, can shift duration calculations by an hour. Normalize all timestamps to UTC at ingestion.
Common mistakes
- Using
MAX(status)for the current status — wrong for any status vocabulary that isn't already sorted chronologically. - Forgetting to sort before aggregating in pandas, then returning the status from an arbitrary row.
- Using the join approach without guarding against duplicate rows when timestamps are not strictly unique.
- Returning
lifespan_hoursas an integer type, which silently drops fractional hours.
Likely follow-ups
Time spent in each status. Use LEAD to find when the next transition happened, then sum by status. The last interval has no end time — decide whether to count it as zero, or as still-running by using CURRENT_TIMESTAMP.
Handling millions of rows. Add a composite index on (listing_id, occurred_at DESC) with status and event_id as included columns so the query is index-only. For truly large tables, maintain a denormalized listing_summary table updated via an upsert on each new event batch, storing first_event, last_event, and current_status directly.
Non-monotone status sequences (e.g. a listing goes ACTIVE → SOLD → ACTIVE after a dispute). The window-function query handles this correctly already — it picks the most recent row rather than applying status precedence. The bug to avoid is logic like "if any event is SOLD, the listing is sold."