MySQL IntroductionComment MySQLInstall MySQL container with Docker-ComposeMySQL AdminMySQL ALTER TABLEMySQL ArithmeticMySQL BackticksMySQL Backup using mysqldumpMySQL Change PasswordMySQL Character Sets and CollationsMySQL clientMySQL ClusteringMySQL Configuration and tuningMySQL Connecting with UTF-8 Using Various Programming language.MySQL Converting from MyISAM to InnoDBMySQL Create New UserMySQL Creating databasesMySQL Customize PS1MySQL Data TypesMySQL Date and Time OperationsMySQL Dealing with sparse or missing dataMySQL DELETEMySQL Drop TableMySQL Dynamic Un-Pivot Table using Prepared StatementMySQL ENUMMySQL Error 1055: ONLY FULL GROUP BY: something is not in GROUP by clause ...MySQL Error codesMySQL EventsMySQL Extract values from JSON typeMySQL Full-Text searchMySQL Group byMySQL Handling Time ZonesMySQL Indexes and KeysMySQL INSERTMySQL JoinsMySQL JOINS: Join 3 table with the same name of id.MySQL JSONMySQL Limit and OffsetMySQL LOAD DATA INFILEMySQL LOCK TABLEMySQL Log filesMySQL Many-to-many Mapping tableMySQL MyISAM EngineMySQL mysqlimportMySQL NULLMySQL One to ManyMySQL ORDER byMySQL PartitioningMySQL Performance TipsMySQL Performance TuningMySQL Pivot queriesMySQL PREPARE StatementsMySQL Recover from lost root passwordMySQL Regular ExpressionsMySQL ReplicationMySQL Reserved WordsMySQL Security via GRANTsMySQL SELECTMySQL Server InformationMySQL SSL Connection SetupMySQL Stored routines (procedures and functions)MySQL String operationsMySQL Table CreationMySQL Temporary TablesMySQL Time with subsecond precisionMySQL TransactionMySQL TRIGGERSMySQL UNIONMySQL UnionsMySQL UPDATEMySQL Using VariablesMySQL VIEWRecover and reset the default root password for MySQL 5.7+

MySQL Pivot queries

From WikiOD

Remarks[edit | edit source]

Pivot query creation in MySQL relies upon the GROUP_CONCAT() function. If the result of the expression that creates the columns of the pivot query is expected to be large, the value of the group_concat_max_len variable must be increased:

set session group_concat_max_len = 1024 * 1024; -- This should be enough for most cases

Creating a pivot query[edit | edit source]

MySQL does not provide a built-in way to create pivot queries. However, these can be created using prepared statements.

Assume the table tbl_values:

Id Name Group Value
1 Pete A 10
2 Pete B 20
3 John A 10

Request: Create a query that shows the sum of Value for each Name; the Group must be column header and Name must be the row header.

** 1. Create an expression that builds the columns
set @sql = (
    select group_concat(distinct 
            "sum(case when `Group`='", Group, "' then `Value` end) as `", `Group`, "`"
    from tbl_values
** 2. Complete the SQL instruction
set @sql = concat("select Name, ", @sql, " from tbl_values group by `Name`");
** 3. Create a prepared statement
prepare stmt from @sql;
** 4. Execute the prepared statement
execute stmt;


Name A B
John 10 NULL
Pete 10 20

Important: Deallocate the prepared statement once it's no longer needed:

deallocate prepare stmt;

Example on SQL Fiddle