How to Pivot Data in SQL?

Nicholas Bennett
2 min readJan 30, 2024

--

Pivoting data in SQL is a valuable tool. Its greatness lies in the ability to break down data into columns of various categories. For example, in a sports store, products can be categorized into columns, facilitating easier analysis, especially for common items like footballs, basketballs, or tennis rackets. This enables a sports store to efficiently analyze orders and determine their quantity within a specific period. Similar to Excel's data pivoting, there are situations where performing this on the backend in SQL or the database is preferable. This ensures aggregated data is readily available, eliminating the need for additional tools, especially when dealing with large datasets.

SELECT order_date
,SUM(CASE WHEN product = 'football' THEN order_amount ELSE 0 END) AS football_amount
,SUM(CASE WHEN product = 'basketball' THEN order_amount ELSE 0 END) AS basketball_amount
,SUM(CASE WHEN product = 'tennis racket' THEN order_amount ELSE 0 END) AS tennis_racket_amount
FROM sports_orders
GROUP BY 1;

To achieve this, utilizing a case statement is instrumental. A case statement breaks down categories, allowing for precise analysis. For instance, using a sum with a case statement can help calculate the order amount for specific products, like footballs. The structure involves specifying "when product equals football, then order amount" and handling non-football cases with "else zero." This approach ensures accurate summation of columns for different products.

Photo by NASA Hubble Space Telescope on Unsplash

The simplicity and power of case statements become evident in their versatility. They can be applied to various factors such as states or regions, providing a higher-level perspective on data analysis. Pivoting data in this manner, especially for broader categories like states or regions (e.g., Northeast or Midwest), significantly simplifies understanding trends in different areas. In conclusion, embracing data pivoting through case statements in SQL enables efficient and insightful analysis.

--

--