How to Transpose Rows to Columns in SQL
π‘ Concept Name
Transposing Rows to Columns in SQL β A method to pivot data horizontally, turning values from a row group into column headers using SQL techniques like PIVOT
or CASE WHEN
.
π Quick Intro
Transposing rows into columns in SQL helps build reports where you need a cross-tabular layout. Depending on the database system, you can use PIVOT
, CASE WHEN
, or dynamic SQL to achieve this transformation.
π§ Analogy / Short Story
Think of data like a guestbook: each row is a guestβs name and the event they attended. Transposing is like taking all events and laying them across the top like columns, with guest names down the sideβturning attendance rows into a neat attendance matrix.
π§ Technical Explanation
- π Use
PIVOT
in SQL Server or Oracle for fixed-value transformations. - π‘ Use
CASE WHEN
and aggregate functions in all RDBMS for manual transposition. - π Dynamic pivoting can be done using dynamic SQL for unknown columns.
- π Useful in reporting, matrix views, and comparative analytics.
- π οΈ Always ensure the grouped column is aggregated with SUM, MAX, COUNT, etc.
π» Real Code Example
-- Sample table: Sales (Year, Product, Revenue)
-- Transpose Years into Columns using PIVOT (SQL Server)
SELECT *
FROM (
SELECT Year, Product, Revenue
FROM Sales
) AS SourceTable
PIVOT (
SUM(Revenue)
FOR Year IN ([2022], [2023], [2024])
) AS PivotTable;
-- Alternative using CASE WHEN
SELECT
Product,
SUM(CASE WHEN Year = 2022 THEN Revenue ELSE 0 END) AS Revenue_2022,
SUM(CASE WHEN Year = 2023 THEN Revenue ELSE 0 END) AS Revenue_2023,
SUM(CASE WHEN Year = 2024 THEN Revenue ELSE 0 END) AS Revenue_2024
FROM Sales
GROUP BY Product;

π― Purpose & Use Case
- β Build matrix-style reports (e.g., revenue per year per product).
- β Compare metrics across time or categories side-by-side.
- β Reorganize long-form data into wide-form format for dashboards.
- β Simplify visual representation of grouped data.
β Interview Q&A
Q1: What is the purpose of transposing data in SQL?
A: To reshape row-wise data into columnar format for better comparison or reporting.
Q2: Which SQL Server feature helps in row-to-column conversion?
A: The PIVOT
operator.
Q3: Can all SQL databases use PIVOT?
A: No, databases like MySQL use CASE WHEN
logic instead.
Q4: What happens if the column values are not known in advance?
A: You must build a dynamic SQL query to handle such cases.
Q5: Why do we use aggregate functions in transposing?
A: Because pivoting groups rows and needs to combine data (e.g., SUM or COUNT) for each column value.
Q6: How does CASE WHEN
help in manual pivoting?
A: It checks for specific values and assigns them to virtual columns.
Q7: Can pivoted columns be filtered?
A: Yes, using WHERE or HAVING clauses on the final output.
Q8: What kind of data is best suited for pivoting?
A: Repetitive category or time-series data.
Q9: Can you pivot multiple columns at once?
A: It's possible but more complexβrequires multiple aggregations.
Q10: Is it possible to unpivot data later?
A: Yes, using the UNPIVOT
operator (in SQL Server) or restructuring CASE statements.
π MCQs
Q1. Which SQL clause transposes rows to columns?
- GROUP BY
- UNION
- PIVOT
- DISTINCT
Q2. What SQL construct is used in MySQL for pivoting?
- JOIN
- IF ELSE
- CASE WHEN
- UNION ALL
Q3. Which function is needed during aggregation?
- MIN
- SELECT
- SUM or COUNT
- IFNULL
Q4. How do you pivot unknown values?
- PIVOT normally
- Hardcode values
- Use dynamic SQL
- Use UNION
Q5. Which keyword comes after FOR in PIVOT?
- BY
- WHERE
- IN
- ON
Q6. What must you include in a PIVOT clause?
- Subquery
- HAVING
- Aggregate function
- ORDER BY
Q7. Which database supports PIVOT natively?
- SQLite
- SQL Server
- MySQL 5.5
- MongoDB
Q8. What’s the alternative to PIVOT in PostgreSQL?
- PIVOT
- JOIN
- CASE WHEN
- MERGE
Q9. Can pivoting be reversed?
- No
- Only with triggers
- Yes, using UNPIVOT
- Only in views
Q10. Why is pivoting used in reports?
- To merge databases
- To compare metrics side by side
- To enforce constraints
- To normalize data
π‘ Bonus Insight
For better flexibility, use stored procedures with dynamic SQL to handle unknown or changing pivot column values. Always validate and test with varied datasets to ensure no loss of data integrity during transposition.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!