Converting rows to columns in SQL means rearranging data so that values stored in multiple rows appear as separate columns. This makes it easier to organize and compare data, such as monthly sales.
Pivot in SQL
The PIVOT operator uses a specified column to create new column headers and an aggregate function to calculate the corresponding values. The remaining columns determine how the results are grouped.
For example, monthly sales records can be displayed in separate columns for January, February, and March.
Syntax:
SELECT
non_pivoted_column,
[value_1],
[value_2]
FROM (
SELECT
non_pivoted_column,
pivot_column,
value_column
FROM table_name
) AS source_data
PIVOT (
aggregate_function(value_column)
FOR pivot_column IN ([value_1], [value_2])
) AS pivot_result;
Explanation:
Let's break down the syntax and understand each component:
- non_pivoted_column: The column used to identify or group rows in the result.
- pivot_column: The column whose selected values become column headers.
- value_column: The column containing the values to be aggregated.
- aggregate_function: The function used to summarize values, such as SUM(), COUNT(), or MAX().
- IN: Specifies the values that will become separate columns.
- source_data: The alias for the source query.
- pivot_result: The alias for the resulting pivoted table.
Example: Pivoting Sales Data by Month
First, we will create a demo SQL sales table and use sample records to understand the PIVOT operation.

We want to pivot this data to show the total sales for each product in each month. The query would look like this:
Query:
SELECT
product_name,
[Jan],
[Feb],
[Mar]
FROM (
SELECT
product_name,
sales_month,
sales_amount
FROM sales
) AS source_data
PIVOT (
SUM(sales_amount)
FOR sales_month IN ([Jan], [Feb], [Mar])
) AS sales_by_month;
Output:

Explanation: The query displays each product's sales in separate columns for Jan, Feb, and Mar. The SUM() function calculates the total sales for each product in each month.