How would you optimize a database query that is performing slowly for a client with millions of records?
Using the provided PostgreSQL schema, return the latest completed attempt for each active candidate and active assessment since 2025-01-01. Include prior score information and recorded event metrics so the query can be evaluated for correctness and performance.
Output
- One row per candidate and assessment combination with a qualifying completed attempt.
- Columns:
candidate_name, assessment_name, completed_at, score, previous_score, score_change, event_count, and total_duration_seconds.
- Include candidates with no matching events, treating their event count and duration as zero.
- Sort by
completed_at descending, then candidate_name, then assessment_name.