Unpivot SQL

Galaxy Glossary

How can you transform columns into rows in a SQL table?

Unpivot SQL is a technique used to transform columns into rows in a table. This is useful when you want to analyze data in a different format or aggregate data across different columns. It's the opposite of pivot.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

Unpivoting is a crucial data transformation technique in SQL. Imagine a table with multiple columns representing different metrics for various products. Unpivoting allows you to reshape this data so that each row represents a single metric for a specific product. This makes it easier to perform aggregations and comparisons across different metrics. The process essentially rotates the table, moving column headers into a new column containing the metric names. This is particularly helpful when you need to analyze data using tools or functions that expect a specific format. For instance, you might want to calculate the average sales across all products for each month. Unpivoting makes this calculation straightforward. Unpivoting is the reverse of pivoting, which transforms rows into columns.

Why Unpivot SQL is important

Unpivoting is essential for data analysis and reporting. It allows you to easily aggregate and compare data across different dimensions, making it easier to draw meaningful insights. This flexibility is crucial for creating dynamic reports and dashboards.

Example Usage


-- Sample table (Sales data)
CREATE TABLE SalesData (
    Product VARCHAR(50),
    Jan INT,
    Feb INT,
    Mar INT
);

INSERT INTO SalesData (Product, Jan, Feb, Mar)
VALUES
('Product A', 100, 120, 150),
('Product B', 110, 130, 140),
('Product C', 90, 100, 120);

-- Unpivot the table
SELECT
    Product,
    Metric,
    Value
FROM
    SalesData
UNPIVOT (
    Value
    FOR Metric IN (Jan, Feb, Mar)
);

Common Mistakes

Want to learn about other SQL terms?