Dynamic pivot
- SQL course
- Advanced
- Lesson 28/81
- 4 min
Pivot when the column count changes.
Dynamic pivot
Dynamic pivot makes categories into columns automatically. Not done directly with plain SQL.
-- adım 1: kategorileri bul
-- adım 2: SQL'i dinamik üret
-- adım 3: üretilen SQL'i çalıştırThis query requires a stored procedure.
Dynamic pivot — details
Dynamic pivot uses the database's dynamic SQL feature. Needed when the category count is unknown upfront.
In that case the category list is queried first, the query text is built from it and run with EXECUTE; if user input is involved you must watch out for SQL injection.
Practice Dynamic pivot
In a stored procedure, find the category list and generate dynamic pivot SQL.
Starter code
-- dynamic pivot
SELECT DISTINCTSample solution
SELECT DISTINCT category FROM sales;Expected output
category Kitap Elektronik
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Dynamic pivot: match the terms
| Term | Meaning |
|---|---|
dynamic |
automatic |
category |
column |
stored procedure |
procedure |
flexible |
variable |
2 Dynamic pivot
if the categories are not known ____ (dynamic pivot)
if the categories are not known in advance (dynamic pivot)
Explanation: A dynamic pivot is needed when the categories are not known in advance.
3 What does dynamic pivot require?
- TRIGGER
- INDEX
- VIEW
- Dynamic SQL Correct answer
Explanation: Dynamic pivot requires dynamic SQL.