How do you optimize complex SQL queries for large-scale datasets?
Write a PostgreSQL query using the provided tables to calculate customer revenue by month, compare it with each customer's previous reported month, and rank customers within their region and month. Include only completed orders in 2024 and active products.
customer_name, region, month_start, monthly_revenue, prior_month_revenue, revenue_change, and regional_rank.month_start, region, regional_rank, and customer_name.| Column | Type | Description |
|---|---|---|
| customer_idPK | INT | Customer identifier |
| customer_name | VARCHAR(100) | Customer display name |
| region | VARCHAR(30) | Customer sales region |
| Column | Type | Description |
|---|---|---|
| order_idPK | INT | Order identifier |
| customer_id | INT | Customer who placed the order |
| order_date | DATE | Order creation date |
| status | VARCHAR(20) | Order processing status |
| Column | Type | Description |
|---|---|---|
| order_item_idPK | INT | Order line identifier |
| order_id | INT | Parent order identifier |
| product_id | INT | Purchased product identifier |
| quantity | INT | Units purchased |
| unit_price | NUMERIC(10,2) | Price per unit at purchase time |
| Column | Type | Description |
|---|---|---|
| product_idPK | INT | Product identifier |
| product_name | VARCHAR(100) | Product name |
| category | VARCHAR(50) | Product category |
| is_active | BOOLEAN | Whether the product is currently active |