How to Convert Rows into Columns in MySQL?
Last Updated :
04 Apr, 2024
Converting rows into columns, also known as pivoting or transposing, is a common operation in DBMS, and MySQL provides robust functionality for achieving this transformation.
This process is useful to reshape data for better analysis or reporting. This guide will explore the syntax, usage, and examples of converting rows into columns in MySQL.
Transpose Rows into Columns in MySQL
Transposing rows into columns means, rearranging a table such that the columns become the rows, and rows become the columns. It is useful in data analysis to organize data for effective reporting or visualization.
The basic syntax to convert rows into columns in MySQL involves using the CASE statement in combination with the MAX function.
Syntax
SELECT
MAX(CASE WHEN condition1 THEN value1 END) AS column1,
MAX(CASE WHEN condition2 THEN value2 END) AS column2,
FROM your_table
GROUP BY common_column;
- Conditions and Values: Define conditions based on which the rows will be converted into columns. Specify the corresponding value to be displayed in the new column for each condition.
- GROUP BY: Use the GROUP BY clause to group the results by a common column. This column helps aggregate rows into distinct sets with each set corresponding to a new column in the result.
Demo MySQL Database
For Understanding, how to convert rows into columns in MySQL, we will use the following table in our examples.
product | month | revenue |
---|
A | January | 1000 |
A | February | 1200 |
B | January | 800 |
B | February | 900 |
C | January | 1500 |
C | February | 1800 |
To create this table on your MySQL Workbench, Copy-Paste and Run the following MySQL queries:
MySQL
CREATE DATABASE Convert_db;
USE Convert_db;
CREATE TABLE sales_data (
product VARCHAR(50),
month VARCHAR(20),
revenue INT
);
INSERT INTO sales_data (product, month, revenue) VALUES
('A', 'January', 1000),
('A', 'February', 1200),
('B', 'January', 800),
('B', 'February', 900),
('C', 'January', 1500),
('C', 'February', 1800);
Transforming Rows into Columns in MySQL Examples
Let's look at some examples on how to transform rows into columns in MySQL:-
Example 1: Simple Conversion
In this example, we want to pivot the data to display monthly revenues for each product as columns. This is static pivot and can be done with following MySQL query.
SELECT product,
MAX(CASE WHEN month = 'January' THEN revenue END) AS January,
MAX(CASE WHEN month = 'February' THEN revenue END) AS February
FROM sales_data
GROUP BY product;
Output:
Output of Simple Conversion MySQL CodeExplanation: The SQL query retrieves the maximum revenue for each product in January and February from the sales_data table. The output displays a summary with columns for each month, showing the highest revenue achieved by each product during the specified months. The result is grouped by the product.
Example 2: Dynamic Pivot
In some cases, you might not know the exact values for pivoting in advance. Here's an example using a dynamic pivot based on distinct months with MySQL query:
SET SESSION group_concat_max_len = 1000000;
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
'MAX(CASE WHEN month = "', month, '" THEN revenue END) AS "', month, '"')
INTO @sql
FROM sales_data;
SET @sql = CONCAT('SELECT product, ', @sql, ' FROM sales_data GROUP BY product;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Output:
Output Dynamic Pivot MySQL CodeExplanation: The SQL code dynamically generates a pivot table, transforming the sales_data table. It sets the group_concat_max_len session variable, creates a dynamic SQL statement to pivot the data, and then executes it. The output displays a summary with product-wise maximum revenue for each month, effectively transposing the original data.
Conclusion
Converting rows into columns in MySQL is a powerful technique to reshape your data for better analysis. By using the CASE statement along with aggregate functions like MAX, you can efficiently pivot your data. Whether you need a static or dynamic pivot, MySQL provides the flexibility to transform your dataset to meet your analytical requirements.
Similar Reads
How to Concat Two Columns Into One in MySQL?
Concatenating columns in MySQL is a key operation for combining data from multiple fields into a single, unified column. This process is essential for generating comprehensive reports and merging data elements like names or addresses. This article explores two effective methods for column concatenat
3 min read
How to Get Column Names in MySQL?
To get column names in MySQL use techniques such as the DESCRIBE statement, INFORMATION_SCHEMA.COLUMNS, and SHOW COLUMNS FROM commands. Here will cover these techniques, with explained examples, and help to get a better understanding on how to get column names in MySQL. MySQL Fetch Column Names from
3 min read
How to Efficiently Convert Rows to Columns in SQL?
In SQL, rows and columns are the fundamental building blocks of a database. Rows represent individual records, while columns represent the attributes or characteristics of those records. However, there may be instances where we need to convert rows to columns in order to better analyze and manipulat
5 min read
How to Convert BLOB into VARCHAR in MySQL?
In this article, we would be learning a SQL query to convert a column of BLOB Data Type to VARCHAR Data Type. To execute this query we would need to alter the table and subsequently a column's definition. We would first need to use the ALTER TABLE command to change the table. ALTER TABLE: ALTER TABL
2 min read
How to Efficiently Convert Rows to Columns in PostgreSQL?
Converting rows to columns, often referred to as pivoting or transposing, is a crucial aspect of data transformation in SQL. This technique is useful for improving data readability, facilitating analysis, aligning data formats with the requirements of reporting tools, and optimizing queries. In Post
5 min read
How to Efficiently Convert Rows to Columns in PL/SQL?
In Oracle PL/SQL, converting rows into columns is a common operation, especially useful for reporting, data analysis, and reformatting data for easy visualization. PL/SQL, or Procedural Language/Structured Query Language, is a powerful procedural extension to SQL, created by Oracle, that integrates
5 min read
How to Get the Type of Columns in SQL
In SQL, the types of columns in a database table play a fundamental role in data management and query execution. Each column is designed to store specific types of data, such as numbers, text, dates, or binary data. Understanding these column types is essential for effective database design, query o
4 min read
How to Efficiently Convert Rows to Columns in MariaDB?
In the area of database management, the ability to convert rows to columns efficiently is a valuable skill. MariaDB, a popular open-source relational database management system offers various methods to achieve this transformation. In this article, we'll learn about How to Convert Rows into Columns
3 min read
How to Delete Column in SQL
In SQL, deleting a column from an existing table is a straightforward process, but it's important to understand the implications and the correct syntax involved. While there is no direct DELETE COLUMN command in SQL, we can achieve this by using the ALTER TABLE command combined with DROP COLUMN.In t
5 min read
How to Rename a Column in MySQL?
Renaming columns in MySQL is a frequent task to keep data organized and flexible. It helps adjust database layouts to fit new needs without losing information. This article will show you different ways to rename columns in MySQL, making it easier to manage and update your database structure as your
4 min read