How to Do an Unpivot in MySQL
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Unpivoting in MySQL involves transforming columns into rows, effectively normalizing data that was previously denormalized. This guide demonstrates how to perform an unpivot operation in MySQL, converting columnar data into a more query-friendly row format.
In MySQL, unpivoting is not a direct, single-command process as it is in some other SQL databases. Instead, it requires a combination of SQL operations to achieve the same result. The goal is to transform data from a wide format (with many columns) to a long format (with more rows and fewer columns).
Consider a table named sales_data with the following structure:
| product_id | Jan_sales | Feb_sales | Mar_sales |
|------------|-----------|-----------|-----------|
| 1 | 150 | 200 | 250 |
| 2 | 300 | 350 | 400 |
Our aim is to unpivot the monthly sales columns into a format with two columns: month and sales.
The following query uses a combination of UNION ALL and SELECT statements to unpivot the data:
SELECT product_id, 'Jan' as month, Jan_sales as sales FROM sales_data
UNION ALL
SELECT product_id, 'Feb', Feb_sales FROM sales_data
UNION ALL
SELECT product_id, 'Mar', Mar_sales FROM sales_data;
This query produces an output like:
| product_id | month | sales |
|------------|-------|-------|
| 1 | Jan | 150 |
| 1 | Feb | 200 |
| 1 | Mar | 250 |
| 2 | Jan | 300 |
| 2 | Feb | 350 |
| 2 | Mar | 400 |
If your table has a large number of columns, manually writing a UNION for each one can be impractical. In such cases, consider automating this process with a dynamic SQL query or using an external tool to generate the query for you.
UNION ALL instead of UNION to avoid the overhead of removing duplicate rows, assuming your data does not have duplicates.If this query pattern is part of recurring reporting, Basedash helps you turn it into reusable, AI-native BI workflows: prompt-to-SQL, shared dashboards, and trusted answers that stay aligned with your data model.
Written by
Senior Engineer at Basedash
Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.