SQL & Databases Masterclass Course
Welcome to the ultimate postgresql tutorial for beginners 2026. Work through interactive sql practice problems with solutions, master our comprehensive sql window functions tutorial modules, and prepare for tough sql interview questions at Google and Amazon entirely in your browser. Claim your course completion XP and build production-ready database mastery today!
How to Pivot Data in SQL: Rows to Columns
Introduction & Core Concept
In executive reporting, stakeholders frequently prefer reading summary metrics arranged horizontally as columns rather than vertical row stacks (e.g., displaying months or account types as separate column headers).
While certain database engines support proprietary PIVOT keywords, the most robust, highly standardized, and universally compatible technique across all SQL dialects is Conditional Aggregation (SUM or COUNT combined with CASE WHEN).
SELECT
customer_id,
SUM(CASE WHEN type = 'Savings' THEN balance ELSE 0 END) AS savings_val,
SUM(CASE WHEN type = 'Checking' THEN balance ELSE 0 END) AS checking_val
FROM accounts GROUP BY customer_id;Why & Where We Use It
Real-World Example
ApexBank auditing leadership wants a comprehensive breakdown of bank account balances arranged horizontally by customer, displaying their dedicated checking balances, savings balances, and gross net worth side-by-side.
Best Practices: What to Do & What NOT to Do
ELSE 0 (for SUM) or ELSE NULL (for COUNT) inside your conditional pivoting branches to guarantee clean mathematical calculations.Syntax & Pro Tips
SELECT category, SUM(CASE WHEN year = 2026 THEN sales ELSE 0 END) AS sales_2026 FROM orders GROUP BY category;