How would you convert rows to columns in SQL, and why might you do it?
Instruction: Explain the process of pivoting data in SQL and provide a use case.
Updated
Official answer
Pivoting turns category values into result columns, usually after aggregation. It is useful for a fixed reporting layout, such as monthly totals per product. This self-contained PostgreSQL example uses conditional aggregation:
WITH sales(product, month_no, amount) AS (
VALUES ('A',1,10), ('A',1,5), ('A',2,7), ('B',1,4)
)
SELECT product,
SUM(CASE WHEN month_no = 1 THEN amount ELSE 0 END) AS jan,
SUM(CASE WHEN month_no = 2 THEN amount ELSE 0 END) AS feb
FROM sales
GROUP BY product
ORDER BY product;
It returns A=(15,7) and B=(4,0). Here absent rows mean no sales and amounts are complete; unknown or missing measurements should not silently become zero. Repeated product/month rows are summed deliberately.
Some engines provide PIVOT syntax, which is not universal. Fixed SQL result columns must be specified; a dynamic category set may require controlled query generation or pivoting in a reporting layer. Bind values, and allowlist or safely quote identifiers rather than concatenating user input. Preserve a long-form source when it suits downstream analysis better.