CodeBlanks Logo Icon CodeBlanks

Dynamic pivot

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ır

This 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

query.sql
-- dynamic pivot
SELECT DISTINCT

Sample solution

query.sql
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

Question
if the categories are not known ____ (dynamic pivot)
Answer
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.

All lessons in Advanced