How do you optimize a slow-running SQL query containing multiple complex joins?
Assume the provided banking tables contain customers, accounts, transactions, loan applications, and loan payments. Write an optimized PostgreSQL query that returns active customers with active accounts, their in-period transaction totals, latest loan details, and payment totals. Avoid duplicate monetary totals caused by one-to-many joins.
Output
- One row per active customer with at least one active account.
- Columns:
customer_id, customer_name, active_account_count, transaction_total, latest_loan_id, latest_loan_amount, loan_payment_total.
- Include customers without loans or in-period transactions, using zero totals where appropriate.
- Sort by
customer_id ascending.
Output details
- Filter customers and accounts where their respective status equals
ACTIVE.
- Use
2025-01-01 inclusive through 2025-04-01 exclusive for both transaction and payment dates.
- Choose the latest loan by
application_date descending, breaking ties by loan_application_id descending.
- Leave
latest_loan_id and latest_loan_amount NULL when the customer has no loan.
- Consider all loan applications when selecting the latest loan, regardless of loan status.