Identify potential bottlenecks in a provided database query and suggest refactoring strategies.
Review the following query, then provide a refactored PostgreSQL query that preserves its intended result while addressing inefficient filtering, repeated calculations, duplicate rows, and aggregation.
SELECT DISTINCT
c.customer_id,
c.customer_name,
TO_CHAR(o.order_date, 'YYYY-MM') AS order_month,
(
SELECT SUM(oi2.quantity * oi2.unit_price)
FROM order_items oi2
WHERE oi2.order_id = o.order_id
) AS order_revenue
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE c.segment = 'Enterprise'
AND TO_CHAR(o.order_date, 'YYYY-MM') BETWEEN '2024-01' AND '2024-03'
ORDER BY c.customer_id, order_month;
Output
- One row per Enterprise customer and calendar month with orders in the inclusive January through March 2024 period.
- Columns:
customer_id, customer_name, order_month, order_count, and total_revenue.
- Sort by
customer_id, then order_month ascending.