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
Output details
- Compute
outstanding_balance as principal_amount minus the sum of amount for payments with status equal to successful.
- Treat loans without successful payments as having a successful-payment total of
0.
- Define the latest payment by greatest
payment_date, breaking ties with greatest payment_id.
- Return
NULL for latest_payment_date and latest_payment_status when a loan has no payments.