Skip to main content
Documents
Clauses StatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL PIVOT Clauses

The PIVOT clause in MySQL is not natively supported as a direct SQL command but can be simulated to transform rows into columns, effectively pivoting data for reporting purposes. It is often used to aggregate and display data in a more user-friendly format.

Usage

The PIVOT operation is typically used when you need to convert row data into columns for better analytical insight, often employing custom SQL queries or stored procedures. The syntax involves using aggregate functions and CASE statements to simulate a PIVOT table.

SELECT 
  aggregate_function(column) AS alias,
  CASE WHEN condition THEN result END AS pivot_column
FROM 
  table_name
GROUP BY 
  grouping_column;

In this syntax, aggregate_function applies to the column you want to transform, while CASE statements help pivot row values into columns.

Examples

1. Basic Pivot Simulation

SELECT 
  department,
  SUM(CASE WHEN month = 'Jan' THEN sales ELSE 0 END) AS Jan_Sales,
  SUM(CASE WHEN month = 'Feb' THEN sales ELSE 0 END) AS Feb_Sales
FROM 
  sales_data
GROUP BY 
  department;

This example demonstrates a basic pivot operation where sales data is transformed from rows into columns for each month.

2. Pivot with Multiple Aggregates

SELECT 
  product_id,
  SUM(CASE WHEN region = 'North' THEN quantity ELSE 0 END) AS North_Quantity,
  SUM(CASE WHEN region = 'South' THEN quantity ELSE 0 END) AS South_Quantity,
  SUM(CASE WHEN region = 'North' THEN revenue ELSE 0 END) AS North_Revenue,
  SUM(CASE WHEN region = 'South' THEN revenue ELSE 0 END) AS South_Revenue
FROM 
  sales
GROUP BY 
  product_id;

Here, the query pivots both quantity and revenue data across different regions, providing a detailed product-wise report.

3. Pivot with Dynamic SQL

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN month = ''',
      month,
      ''' THEN sales ELSE 0 END) AS ',
      CONCAT(month, '_Sales')
    )
  ) INTO @sql
FROM sales_data;

SET @sql = CONCAT('SELECT department, ', @sql, ' FROM sales_data GROUP BY department');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

This example uses dynamic SQL to handle an unknown number of pivot columns, creating a flexible pivot table based on the available months.

Tips and Best Practices

  • Simulate with CASE. Use CASE statements creatively to simulate pivoting in MySQL.
  • Utilize Dynamic SQL for Flexibility. When working with unpredictable column sets, dynamic SQL can automate the pivoting process. Be cautious of security risks such as SQL injection when using dynamic SQL.
  • Aggregate Wisely. Choose the right aggregate functions (e.g., SUM, AVG) to ensure meaningful summaries in your pivot table.
  • Consider Performance. Pivot operations can be resource-intensive; optimize queries and indexes to maintain performance. Large datasets may impact performance significantly.
  • Handle NULL Values. Consider how NULL values might affect your aggregate functions and adjust your queries accordingly to avoid unexpected results.
  • Context on PIVOT Support. MySQL does not natively support a PIVOT clause as it aims to maintain simplicity and relies on its flexible SQL capabilities to achieve similar results through custom queries.

SQL Upskilling for Beginners

Gain the SQL skills to interact with and query your data.
Start Learning for Free