How would you optimize a slow-running SQL query?
Given the supplied PostgreSQL schema and data, rewrite the query so it returns the same business result while reducing unnecessary scans and aggregation work. The result should include active loans with payments during the specified date range and more than 1,000 in total payments.
Output
- One row per qualifying active loan
- Columns:
loan_id, borrower_name, and total_paid
- Include payments from 2025-01-01 through 2025-02-28
- Sort by
total_paid descending, then loan_id ascending