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 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 Convert Pandas Column To List
One of the common tasks when working with a DataFrame in Pandas is converting a column to a list. In this article we will learn how to convert a Pandas column to a list using various methods. 1. Using tolist()One can convert a pandas column to a list using tolist() function which works on the Pandas
4 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 Convert Pandas Columns to String
Converting columns to strings allows easier manipulation when performing string operations such as pattern matching, formatting or concatenation. Pandas provides multiple ways to achieve this conversion and choosing the best method can depend on factors like the size of your dataset and the specific
3 min read
How 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
Convert a column to row name/index in Pandas
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a column to row name/index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash",
2 min read
How to compare columns in two different tables in SQL
Here we are going to see how we can compare the columns of two different tables in SQL. We will be taking a few examples to see how we can do this in different ways. Overview :In this, we will understand overview of SQL query for required operation to perform How to compare columns in two different
4 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
How to Convert From BLOB to Text in MySQL?
In this article, we will see the conversion of a BLOB to TEXT in MySQL. BLOB: It stands for Binary Large Object. It is a kind of data type in MySQL that can store files or images in the database in binary format. It has four types i.e TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. All four types are simi
3 min read