-- DDL CREATE TABLE sales_transactions ( transaction_id INT PRIMARY KEY AUTO_INCREMENT, -- Or SERIAL for PostgreSQL transaction_date DATE NOT NULL, product_category VARCHAR(50) NOT NULL, revenue DECIMAL(10, 2) NOT NULL );
-- Pivot Query SELECT DATE_FORMAT(transaction_date, '%Y-%m') AS sales_month, SUM(revenue) FILTER (WHERE product_category = 'Electronics') AS Electronics_Revenue, SUM(revenue) FILTER (WHERE product_category = 'Clothing') AS Clothing_Revenue, SUM(revenue) FILTER (WHERE product_category = 'Home Goods') AS Home_Goods_Revenue FROM sales_transactions WHERE transaction_date >= '2023-01-01' AND transaction_date <= '2023-03-31' GROUP BY sales_month ORDER BY sales_month;
-- Expected Execution Plan Notes The query will likely perform a full table scan or an index scan on sales_transactions if an appropriate index exists on transaction_date and product_category. The WHERE clause will filter rows by date range early. The GROUP BY sales_month will then aggregate the filtered data. The FILTER clauses within the SUM functions are applied during the aggregation phase, effectively creating conditional sums for each product category. This approach avoids multiple passes over the data that separate subqueries might incur, but the aggregation step itself can be resource-intensive, especially with a large number of distinct categories or a very wide date range. The database optimizer will typically handle the FILTER clause efficiently, often as part of a single aggregation pass.
-- Index Recommendation CREATE INDEX idx_sales_date_category_revenue ON sales_transactions (transaction_date, product_category, revenue); This composite index would significantly improve performance.
transaction_date: Allows for efficient filtering by the WHERE clause, reducing the number of rows processed.product_category: Aids in the conditional aggregation within the FILTER clauses, as rows for specific categories can be quickly located or grouped.revenue: Included as a covering column, allowing the query to be satisfied entirely from the index without needing to access the base table for revenue values, further speeding up the aggregation.
-- Test Data INSERT INTO sales_transactions (transaction_date, product_category, revenue) VALUES ('2023-01-05', 'Electronics', 1200.50), ('2023-01-10', 'Clothing', 350.75), ('2023-01-15', 'Home Goods', 800.00), ('2023-01-20', 'Electronics', 950.25), ('2023-02-01', 'Clothing', 420.00), ('2023-02-08', 'Electronics', 1500.00), ('2023-02-12', 'Home Goods', 600.50), ('2023-02-25', 'Clothing', 280.00), ('2023-03-03', 'Electronics', 1100.00), ('2023-03-10', 'Home Goods', 750.25), ('2023-03-18', 'Clothing', 500.00), ('2023-03-22', 'Electronics', 1300.00), ('2023-03-28', 'Home Goods', 900.00);