How do you optimize complex queries that involve joining multi-million row tables?
Provide a PostgreSQL query for the report below and explain the performance decisions you would validate with EXPLAIN (ANALYZE, BUFFERS). The result should preserve matters with no matching events.
Output
- One row per qualifying matter, with
matter_id, organization_name, qualifying_event_count, and latest_activity_at
- Include open or paused matters for enterprise organizations created before 2025-04-01
- Count only
review and filing events during Q1 2025, while latest_activity_at considers all Q1 events
- Sort by qualifying event count descending, latest activity descending with nulls last, then matter ID ascending