Pivot and unpivot concepts in SQL - Time & Space Complexity
When using pivot and unpivot in SQL, we want to know how the time to run the query changes as the data grows.
We ask: How does the work increase when there are more rows or columns?
Analyze the time complexity of the following SQL pivot operation.
SELECT Product,
SUM(CASE WHEN Year = 2022 THEN Sales ELSE 0 END) AS Sales_2022,
SUM(CASE WHEN Year = 2023 THEN Sales ELSE 0 END) AS Sales_2023
FROM SalesData
GROUP BY Product;
This query turns rows of sales data by year into columns for each year, grouped by product.
Look for repeated work inside the query.
- Primary operation: Scanning all rows in the SalesData table.
- How many times: Once over all rows, but with conditional checks for each year column.
As the number of rows grows, the query must check each row once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks |
| 100 | About 100 row checks |
| 1000 | About 1000 row checks |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run the pivot grows in a straight line as the data size grows.
[X] Wrong: "Pivoting makes the query run much faster because it groups data into columns."
[OK] Correct: Pivoting changes how data looks but still needs to scan all rows, so the time depends on data size, not just format.
Understanding how pivot and unpivot scale helps you explain query performance clearly and shows you know how data size affects work done.
"What if we added more years to pivot on? How would that affect the time complexity?"
Practice
PIVOT operation in SQL?Solution
Step 1: Understand what pivot does
PIVOT changes the orientation of data by turning row values into columns.Step 2: Compare with other options
Only To convert rows into columns for easier data summarization correctly describes this; B describes unpivot, C and D are unrelated.Final Answer:
To convert rows into columns for easier data summarization -> Option AQuick Check:
Pivot = rows to columns [OK]
- Confusing pivot with unpivot
- Thinking pivot deletes data
- Mixing pivot with join operations
Q1, Q2, Q3 into rows in SQL Server?Solution
Step 1: Recall UNPIVOT syntax
UNPIVOT requires specifying the value column and the column that holds the original column names (FOR clause).Step 2: Check each option
SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt correctly uses UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])). Others misuse PIVOT or omit FOR clause.Final Answer:
SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt -> Option BQuick Check:
UNPIVOT syntax = SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt [OK]
- Using PIVOT instead of UNPIVOT
- Swapping value and FOR column names
- Omitting the FOR clause
Sales with columns Product, Year, Quarter, Amount, what will be the result of this query?SELECT * FROM Sales PIVOT (SUM(Amount) FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])) AS Pvt;
Solution
Step 1: Understand PIVOT with aggregation
PIVOT with SUM aggregates Amount values grouped by Product and Year, creating columns for each Quarter.Step 2: Analyze query output
The output will have Product, Year, and one column per quarter (Q1 to Q4) with summed amounts.Final Answer:
A table with columns Product, Year, Q1, Q2, Q3, Q4 showing summed amounts per quarter -> Option CQuick Check:
PIVOT with SUM aggregates rows into columns [OK]
- Expecting original rows unchanged
- Thinking PIVOT cannot use aggregation
- Confusing column order in output
SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN (Q1, Q2, Q3)) AS Unpvt;
But it returns an error. What is the likely cause?
Solution
Step 1: Check syntax for column names in UNPIVOT
In SQL Server, column names in the IN list must be enclosed in square brackets if they are identifiers like Q1, Q2, Q3.Step 2: Identify error cause
Missing brackets cause syntax error; other options are incorrect syntax rules.Final Answer:
The column names in IN clause must be enclosed in square brackets -> Option DQuick Check:
Use brackets for column names in UNPIVOT IN list [OK]
- Omitting brackets around column names
- Misplacing FOR clause
- Incorrect alias syntax
MonthlySales with columns Store, Jan, Feb, Mar representing sales per month. You want to create a report listing Store, Month, Sales rows. Which SQL approach correctly unpivots this data?Solution
Step 1: Identify the goal
We want to transform columns Jan, Feb, Mar into rows with Month and Sales columns.Step 2: Choose correct SQL operation
UNPIVOT converts columns into rows; Use UNPIVOT:SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt;uses correct syntax for this.Step 3: Evaluate other options
PIVOT aggregates rows into columns (wrong direction), JOIN is complex and unnecessary, GROUP BY alone doesn't reshape columns.Final Answer:
Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; -> Option AQuick Check:
Unpivot columns to rows = Use UNPIVOT:SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt;[OK]
- Using PIVOT instead of UNPIVOT
- Trying to reshape with GROUP BY only
- Overcomplicating with JOINs
Ready to prove it?
Pass the test and this pattern moves unknown
