Given a dataset, how would you optimize a slow-running query or pipeline?
Use the provided dataset to demonstrate an optimized PostgreSQL query that calculates completed event activity for active accounts during January 2025. The query should avoid unnecessary rows and preserve accounts whose qualifying events have no item value.
Output
- Return at most five rows with
account_id, account_name, event_count, and total_value.
- Include only active accounts with completed January events.
- Order by
total_value descending, then account_id ascending.
Output details
- Treat January as inclusive of
2025-01-01 00:00:00 and exclusive of 2025-02-01 00:00:00.
- Count each distinct
event_id once in event_count.
- Calculate
total_value as the sum of quantity * unit_price across event items.
- Return
total_value as 0 when qualifying events have no item value.
- Preserve the reference numeric precision without rounding.