Last chance! 50% off DataCamp Premium
Sale ends in
The `UNPIVOT` clause in SQL transformations is used to convert columns into rows, effectively transforming a wide table into a long format. While MySQL does not support the `UNPIVOT` clause natively, this operation can be simulated using a combination of `UNION ALL` and `SELECT` statements.
The `UNPIVOT` operation is typically used to normalize data by converting columns into rows, facilitating data analysis or reporting by restructuring the dataset. This can be achieved in MySQL by using a series of `SELECT` statements combined with `UNION ALL`.
Although MySQL lacks a direct `UNPIVOT` syntax, you can achieve similar results with:
```sql SELECT column_name AS new_column_name, 'column1' AS source_column FROM table_name UNION ALL SELECT column_name AS new_column_name, 'column2' AS source_column FROM table_name; ```In this syntax, replace `column_name`, `column1`, and `column2` with the actual column names you want to transform into rows.
This example turns `sales_q1` and `sales_q2` columns into rows under a single `sales` column with a corresponding `quarter` indicator.
Here, sales data for January, February, and March are unpivoted into a single `sales` column along with a `month` indicator.
This example demonstrates how to unpivot annual salary columns into a single `salary` column with a corresponding `year` label, allowing for easier temporal analysis.