Explain how you would optimize a slow-running database query that handles millions of customer records at PayJoy.
For the practical portion, provide a PostgreSQL query that returns active customers with active loans, a positive outstanding balance, and no successful latest payment. Assume the query must remain correct at large scale.
Output
- One row per qualifying loan, with
customer_id, full_name, loan_id, outstanding_balance, latest_payment_date, and latest_payment_status
- Include only active customers and loans with a positive balance whose latest payment is missing or not successful
- Order by
outstanding_balance descending, then customer_id ascending