SQLMarrow / Course Academy Experience

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!

COURSE PROGRESS
0%
0 of 40 Modules Solved
COURSE SYLLABUS
40 Lessons
LESSON WORKSPACEAdvanced

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
  • Why We Use It: Transforms raw transactional rows into presentation-ready horizontal spreadsheets that can be copied directly into executive briefing decks.
  • Where We Use It: Monthly financial revenue spreadsheets, quarterly sales comparative matrices, and multi-dimensional attendance tracking.
  • 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
  • What to Do: Always include ELSE 0 (for SUM) or ELSE NULL (for COUNT) inside your conditional pivoting branches to guarantee clean mathematical calculations.
  • What NOT to Do: Avoid hardcoding dozens of dynamic pivoting categories if new categories appear daily, as you would need to rewrite your SQL query every time a new category is created!
  • Syntax & Pro Tips
    SELECT category, SUM(CASE WHEN year = 2026 THEN sales ELSE 0 END) AS sales_2026 FROM orders GROUP BY category;
    Interactive Sandboxed Terminal (Preloaded DB Schema: APEXBANK)
    SQL Query WorkspaceSQLite v3.45 (WASM Mode)
    QUICK INSERT:
    1