How would you optimize a slow-performing SQL query that retrieves data from multiple large tables?
Provide an optimized PostgreSQL query for the supplied schema and explain the execution-plan, indexing, filtering, join, and aggregation decisions. The result should report qualifying customer product totals for the first quarter of 2025.
Output
- One row per qualifying customer and top-two product, with
customer_id, customer_name, product_name, product_revenue, customer_total_revenue, and product_rank
- Include only completed orders from 2025-01-01 through 2025-03-31, with at most two products per customer
- Order by
customer_id, then product_rank, then product_id