Unpivot
- SQL course
- Advanced
- Lesson 27/81
- 4 min
Turn columns into rows.
Unpivot
Unpivot turns columns into rows. It converts a wide table to a narrow format.
SELECT 'Kitap' AS category, kitap AS amount FROM monthly
UNION ALL
SELECT 'Elektronik', elektronik FROM monthly;This query converts two columns into two rows.
'Kitap' AS category, kitap AS amount is selected from monthly.
Unpivot — details
Unpivot is done with UNION ALL. Each column becomes a separate SELECT.
For example, you turn the books and electronics columns into rows with two columns, category name and amount; this shape suits charts and grouping better.
Practice Unpivot
Turn kitap and elektronik columns into rows with UNION ALL.
Starter code
-- unpivot
SELECT 'Kitap' AS category, kitap AS amount FROM monthlySample solution
SELECT 'Kitap' AS category, kitap AS amount FROM monthly
UNION ALL
SELECT 'Elektronik', elektronik FROM monthly;Expected output
category amount Kitap 200 Elektronik 1500
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does unpivot turn into rows?
- Rows
- Indexes
- Columns Correct answer
- Triggers
Explanation: Unpivot turns columns into rows.
2 Add UNION ALL
SELECT 'Kitap' AS category, kitap AS amount FROM monthly
____
SELECT 'Elektronik', elektronik FROM monthly;
SELECT 'Kitap' AS category, kitap AS amount FROM monthly
UNION ALL
SELECT 'Elektronik', elektronik FROM monthly;
Explanation: UNION ALL is the right answer.
3 Unpivot: match the terms
| Term | Meaning |
|---|---|
unpivot |
column→row |
UNION ALL |
combine |
narrow |
few columns |
wide |
many columns |