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.
customer_id, customer_name, active_account_count, transaction_total, latest_loan_id, latest_loan_amount, loan_payment_total.customer_id ascending.| Column | Type | Description |
|---|---|---|
| customer_idPK | INT | Customer identifier |
| customer_name | VARCHAR(100) | Customer name |
| customer_status | VARCHAR(20) | Customer lifecycle status |
| Column | Type | Description |
|---|---|---|
| account_idPK | INT | Account identifier |
| customer_id | INT | Owning customer |
| account_type | VARCHAR(30) | Bank account type |
| account_status | VARCHAR(20) | Account lifecycle status |
| Column | Type | Description |
|---|---|---|
| transaction_idPK | INT | Transaction identifier |
| account_id | INT | Account involved in the transaction |
| transaction_date | DATE | Transaction posting date |
| amount | NUMERIC(12,2) | Transaction amount |
| Column | Type | Description |
|---|---|---|
| loan_application_idPK | INT | Loan application identifier |
| customer_id | INT | Applicant customer |
| application_date | DATE | Loan application date |
| loan_amount | NUMERIC(12,2) | Requested or approved loan amount |
| loan_status | VARCHAR(20) | Loan application status |
| Column | Type | Description |
|---|---|---|
| payment_idPK | INT | Payment identifier |
| loan_application_id | INT | Related loan application |
| payment_date | DATE | Payment date |
| payment_amount | NUMERIC(12,2) | Payment amount |