latest row per customer without a correlated subquery that takes 40 minutes?
doing a take-home for a data engineering role (job hunt day 187, grand, all grand). table is basically:
customer_events (
id bigint primary key,
customer_id bigint,
event_type text,
payload jsonb,
created_at timestamptz
)
about 120M rows in their description, i've a 5M sample locally. they want the latest event per customer. my first go:
SELECT e.*
FROM customer_events e
WHERE e.created_at = (
SELECT MAX(created_at)
FROM customer_events e2
WHERE e2.customer_id = e.customer_id
);
on the 5M sample i killed it after 25 minutes. in spark i'd just do a window function and go home, but the brief says plain SQL, postgres 15, and "portable where possible". also two events can have the same created_at and they want exactly one row per customer. what's the proper way to do this, and is there an index that makes it not awful? sure look, any help appreciated
Accepted answer
Get the best of #select-star-anonymous weekly
One email each Monday with the most useful posts. No spam; unsubscribe in one click.
Comments
Sign in to join the conversation.
Sign in to commentAccepted answer