When working with SQL databases, scenarios often arise where you need to retrieve data that's not displayed in your initial query results. This is where the SQL PIVOT feature comes in handy, allowing you to convert rows into columns, or vice versa. In this guide, we'll delve into the world of SQL PIVOT using examples from w3schools.

To begin, let's understand a simple scenario. Suppose you have an Employee table with columns 'EmployeeName', 'Department', and 'Salary'. You want to switch the 'Department' and 'EmployeeName' columns so that the departments are displayed as separate columns, with employee names and salaries within them. This is exactly what SQL PIVOT helps you achieve.

Pivot Syntax
The basic syntax for the PIVOT command in SQL is as follows:

SELECT columnName, [col1], [col2], ... FROM tableName PIVOT ( aggregate_function (columnName) FOR columnName IN ([col1], [col2], ...)) AS PivotTable
Understanding the Syntax

In the syntax above, replace 'columnName' with the name of the column you want to use as the rows. Replace '[col1]', '[col2]', etc., with the values that you want to use as columns. 'aggregate_function' refers to the function you want to apply to the data, like SUM, COUNT, AVG, etc.
The 'tableName' is the name of your table. After executing the PIVOT transformation, the resulting table is given an alias 'PivotTable'.
Example from w3schools

Let's use an example from w3schools. We have a table 'OrderDetails' with columns 'Product', 'Quantity', and 'Price'. We want to convert the 'Product' column into columns, with 'Quantity' and 'Price' as the values within them. The SQL query would look like this:
SELECT Product, SUM(Quantity), SUM(Price * Quantity) FROM OrderDetails PIVOT (SUM(Quantity) FOR Product IN ( 'Apple', 'Banana', 'Cherry' )) AS PivotTable
In this query, we're using the SUM aggregate function to calculate the total quantity and total cost for each product.

SQL Server vs MySQL PIVOT
Although the concept of PIVOT is similar in both SQL Server and MySQL, the syntax and execution may differ slightly. In MySQL, you might need to use conditional aggregation (CASE statement) or dynamic SQL to achieve the same results as the PIVOT function in SQL Server.




















MySQL Example
Using the same 'OrderDetails' table, the equivalent MySQL query would be:
SELECT Product, SUM(CASE WHEN Product = 'Apple' THEN Quantity ELSE 0 END) as AppleQuant, SUM(CASE WHEN Product = 'Banana' THEN Quantity ELSE 0 END) as BananaQuant, SUM(CASE WHEN Product = 'Cherry' THEN Quantity ELSE 0 END) as CherryQuant FROM OrderDetails GROUP BY Product
In this MySQL example, we're using the CASE statement to treat the data as columns. For each product, the quantity is summed, and for products not present, it defaults to zero.
Learning to use the PIVOT function effectively can greatly enhance your data analysis capabilities in SQL. With practice, you'll find it easier to reshape your data to fit your analysis needs. Happy querying!