Calculating... until our next FREE Code-Along Session. Secure your spot now

MySQL: Transpose Rows to Columns

Ryan Forrester
Jun 5th, 2024

There is always situations where information is spread across multiple rows, making analysis and reporting a challenge. This is where the concept of data transposition comes in. Transposing rows to columns essentially flips the table, organizing your data in a more column-oriented way.

For example, if you have sales figures for different product categories across various months. Transposing rows to columns can bring all those monthly sales figures together under each product category, creating a cleaner and more concise view for reports or further analysis.

This article will specifically guide you through various methods for achieving this data transformation in MySQL, focusing on the popular sql transpose rows to columns techniques.

Methods for Transposing Rows to Columns

PIVOT Function:

The PIVOT function is a powerful tool in MySQL for transposing rows to columns. It allows you to reorganize data based on a specific column value, bringing together related information into a single row. Here’s a breakdown of the PIVOT function and its usage:


    FOR pivot_column IN (value1, value2, ...)
  ) AS pivoted_data
FROM source_table;


  • [original_column1], [original_column2]: These represent columns you want to retain from the original table.
  • aggregate_function: This specifies the function to use for aggregating the target values (e.g., SUM, AVG, COUNT).
  • target_value: This refers to the column containing the data points you want to bring into new columns.
  • pivot_column: This is the column that will define the new column names based on its distinct values (e.g., month, product category).
  • (value1, value2, ...): This list explicitly defines the values from the pivot_column that will be used as new column names.

Test Your Data Transposition Skills With Five

If you are learning about transposing rows to columns, Five is the perfect platform to practice your SQL skills. Five is a development environment pre-packaged with a ready-to-use, customizable MySQL. Five also lets you write queries and build a responsive admin panel on top of your data.

Often the best way to learn is to build a web application for yourself. Five makes this process a lot easier and doesn’t completely throw you into the deep end. Plus there are plenty of guides available to help you get started including this one: Build & Deploy a Full-Stack Web App

Build Your Web App In 4 Steps
Start Developing and Learning For Free


Let’s consider a table named sales with columns product, month, and sales_amount. We want to transpose the data to show monthly sales figures for each product.

SELECT product,
    FOR month IN ('Jan', 'Feb', 'Mar')
  ) AS sales_by_month
FROM sales;

This query will create a new table structure with the product names in the first column. It will then add three new columns named ‘Jan’, ‘Feb’, and ‘Mar’ containing the total sales amount for each product in those respective months.


  • The PIVOT function requires you to pre-define the list of new column names based on the distinct values in the pivot_column. This can be limiting if you have a large or dynamic number of columns.
  • PIVOT might become complex for intricate data manipulation scenarios.

Despite these limitations, the PIVOT function remains a valuable method for transposing rows to columns, especially when you have a well-defined set of new column names.


The CASE WHEN expressions combined with GROUP BY offer another effective way to transpose rows to columns in MySQL. This approach leverages conditional logic to dynamically create new columns based on your data. Here’s how it works:


  1. CASE WHEN Expressions: We use multiple CASE WHEN statements to check the value of a specific column (often the one defining the “pivot”).
  2. Conditional Assignment: Within each CASE WHEN statement, we assign a value to a new column name that reflects the condition being checked.
  3. GROUP BY Clause: The GROUP BY clause groups the data based on the original columns you want to retain.


This method shines when you have a dynamic number of columns to create. Unlike the PIVOT function, you don’t need to pre-define the list of new column names. The CASE WHEN expressions handle that dynamically based on the data itself.


Imagine a table named customers with columns customer_id, city, and country. We want to transpose the data to show the number of customers from each city within each country.

SELECT customer_id, country,
  SUM(CASE WHEN city = 'New York' THEN 1 ELSE 0 END) AS num_customers_NY,
  SUM(CASE WHEN city = 'Los Angeles' THEN 1 ELSE 0 END) AS num_customers_LA,
  ... (Add more CASE WHEN statements for other cities)
FROM customers
GROUP BY customer_id, country;

This query will create a result set with the customer ID and country in the first two columns. It will then dynamically generate new columns named num_customers_NY, num_customers_LA, and so on, based on the distinct city values present. Each new column reflects the count of customers from that specific city within each country.

XML Method:

For experienced users seeking an alternative approach to transposing rows to columns with even greater flexibility, the XML method exists. This technique leverages MySQL’s XML capabilities to manipulate data and achieve the desired transformation.

Why Consider XML?

Similar to the CASE WHEN approach, the XML method excels when dealing with dynamic columns. It doesn’t require pre-defined column names, dynamically generating them based on your data.

Targeted for Advanced Users:

While powerful, the XML method involves more intricate steps compared to the previously discussed methods. It’s recommended for users comfortable with XML functions in MySQL.

Further Exploration:

If you’re interested in delving deeper into the XML method for transposing data, you can find a comprehensive explanation here.

Conclusion – MySQL: Transpose Rows to Columns

We explored three primary methods:

  • PIVOT Function: Ideal for scenarios with a well-defined set of new columns based on distinct values.
  • CASE WHEN with GROUP BY: A flexible approach that thrives when dealing with dynamic columns.
  • XML Method (Optional): An advanced technique offering even greater control for experienced users.

Remember, the best method depends on your specific data structure and the number of columns you need to create. Consider the factors mentioned throughout this guide to make the best choice.

Bonus: Transposing Columns to Rows with UNPIVOT

While this article focused on transposing rows to columns, MySQL offers another handy function for those who might have encountered the opposite situation: data spread across multiple columns that you want to consolidate into rows. Introducing the UNPIVOT function.

UNPIVOT in Action:

The UNPIVOT function essentially reverses the logic of PIVOT, taking data from multiple columns and transforming it into rows. This can be beneficial for tasks like:

  • Data normalization: Simplifying complex table structures with many columns.
  • Reporting: Presenting information from various columns in a single row for easier analysis.


Imagine a table named sales_by_month with columns product, Jan, Feb, Mar. This table stores monthly sales figures for each product. We can use UNPIVOT to transform this data into a structure with separate rows for each month, showing the product and its corresponding sales amount for that month.

Here’s the UNPIVOT query:

SELECT product,
FROM sales_by_month
  sales_amount FOR month IN (Jan, Feb, Mar)
) AS unpivoted_data;


  • This query selects the product column and creates new columns named month and sales_amount.
  • The UNPIVOT clause uses the Jan, Feb, and Mar values as the source for the new month column.
  • The sales_amount column is populated with the corresponding sales figures based on the chosen month.

The result will be a table with one row for each product in the original table, and three additional columns: product, month (containing “Jan”, “Feb”, or “Mar”), and sales_amount showing the sales figure for that specific product in that month.

Start developing your first application!

Get Started For Free Today

Sign Up Free Book a demo
Develop your first application with Five now. Start Free

Thank you for your message!

Our friendly staff will contact you shortly.