Pivot Table — SQL Technical Interview Questions & Answers
Pivot Table
Pivot Table
- MySQL has no PIVOT keyword. You fake a pivot with SUM(CASE WHEN subject='Maths' THEN score END) AS maths, … GROUP BY roll. That turns rows into columns.
- Fine for a few known subjects. Pain if subjects grow every week — keep a normalised marks table and pivot in the app.
- Trap: inventing PIVOT syntax from SQL Server in a MySQL viva.
- On the example next to this theory: Pivot Table: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.
Technical Interview Tip: SUM(CASE WHEN subject='Maths' THEN score END) GROUP BY roll.
Code Examples for Pivot Table
Pivot Table — sample query
-- Pivot Table
CREATE TABLE demo (
id INTEGER PRIMARY KEY,
label TEXT NOT NULL,
qty INTEGER DEFAULT 0
);
INSERT INTO demo (id, label, qty) VALUES
(1, 'alpha', 2),
(2, 'beta', 5);
SELECT label, qty FROM demo WHERE qty >= 2 ORDER BY qty DESC;Pivot Table: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.
How to Explain Pivot Table to an Interviewer
Does MySQL have PIVOT?
No Use CASE + GROUP BY