SQL PIVOT
Anonymous contributor
Published Oct 15, 2024
Contribute to Docs
In SQL, the PIVOT command transforms rows of a table into columns.
Syntax
SELECT column1, column2, ...
FROM table
PIVOT
(
aggregate_function(column_to_be_aggregated)
FOR pivot_column IN (pivot_column_values)
) AS alias_name;
alias_name: The temporary name for the newly created pivot table.
Example
The below example shows a table transactions containing three columns customer_name, book_genre, and price. Each row represents a transaction at a bookstore. The query below creates a temporary pivot table named pivot_table with columns customer_name, scifi, and romance. In this table, each row represents the aggregate price that the customers paid for books in each of these genres:
SELECTcustomer_name,scifi,romanceFROMtransactions PIVOT (SUM(price) FOR book_genre IN (scifi, romance)) AS pivot_table;
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SQL on Codecademy
- Learn to analyze data with SQL and prepare for technical interviews.
- Includes 9 Courses
- With Certificate
- Beginner Friendly.17 hours
- In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.
- Beginner Friendly.5 hours