Dynamic Pivoting of a Table - Problem
Dynamic Pivoting of a Table

Imagine you're working with an e-commerce database where products are sold across multiple stores, and you need to transform the data for better analysis. You have a Products table that stores each product-store-price combination as a separate row, but you want to reorganize it into a pivot table format where each row represents one product with columns for each store.

The Challenge: Create a stored procedure PivotProducts that dynamically transforms the table structure. Since store names can vary and change over time, your solution must be dynamic - it should automatically detect all store names and create columns for them.

Table Schema:
Column NameType
product_idint
storevarchar
priceint

Goal: Transform rows into columns where:
• Each row represents one unique product
• Each column represents a store (sorted alphabetically)
• Cell values show the price (or NULL if not sold in that store)
• Maximum of 30 different stores

Input & Output

example_1.sql — Basic Pivot
$ Input: Products table:\n| product_id | store | price |\n|------------|---------|-------|\n| 1 | LCStore | 100 |\n| 1 | Nozama | 200 |\n| 2 | LCStore | 300 |
Output: | product_id | LCStore | Nozama |\n|------------|---------|--------|\n| 1 | 100 | 200 |\n| 2 | 300 | null |
💡 Note: Product 1 is sold in both stores, so both prices appear. Product 2 is only sold in LCStore, so Nozama column shows null. Stores are ordered alphabetically (LCStore, Nozama).
example_2.sql — Multiple Products and Stores
$ Input: Products table:\n| product_id | store | price |\n|------------|-----------|-------|\n| 1 | Shop | 110 |\n| 1 | LCStore | 100 |\n| 1 | Nozama | 200 |\n| 2 | LCStore | 300 |\n| 3 | Shop | 260 |\n| 3 | Nozama | 270 |
Output: | product_id | LCStore | Nozama | Shop |\n|------------|---------|--------|------|\n| 1 | 100 | 200 | 110 |\n| 2 | 300 | null | null |\n| 3 | null | 270 | 260 |
💡 Note: Three stores (LCStore, Nozama, Shop) create three columns in alphabetical order. Each product shows its price per store, with null for stores where it's not sold.
example_3.sql — Edge Case: Single Store
$ Input: Products table:\n| product_id | store | price |\n|------------|---------|-------|\n| 1 | OnlyOne | 100 |\n| 2 | OnlyOne | 200 |
Output: | product_id | OnlyOne |\n|------------|---------|\n| 1 | 100 |\n| 2 | 200 |
💡 Note: When there's only one store, the pivot still works correctly, creating a single store column. This demonstrates the dynamic nature of the solution.

Visualization

Tap to expand
Database Table Transformation AnalogyBefore: Individual Transaction FilesProduct 1 → Store A → $100Product 1 → Store B → $200Product 2 → Store A → $300Product 3 → Store B → $400TransformAfter: Organized Summary SheetProduct | Store A | Store B1 | $100 | $2002 | $300 | NULL3 | NULL | $400⬆ Easy to compare prices across storesThe Dynamic Challenge:🔍 Step 1: Discover all unique store names (could be any number)📝 Step 2: Generate column headers dynamically (sorted alphabetically)🔨 Step 3: Build SQL query with runtime-discovered columns⚡ Step 4: Execute dynamic pivot transformationReal-World Benefits:✅ Works with any number of stores (up to 30)✅ Automatically adapts when new stores are added✅ Maintains consistent alphabetical ordering✅ Handles missing data gracefully (NULL values)✅ Perfect for business intelligence and reporting💡
Understanding the Visualization
1
Analyze Original Structure
Each row represents one product sold at one store with its price
2
Identify Unique Stores
Scan through all data to find every unique store name
3
Create Column Headers
Sort store names alphabetically and prepare them as column headers
4
Transform Data
Group by product and spread store prices across columns
Key Takeaway
🎯 Key Insight: Dynamic SQL enables runtime schema adaptation, making the pivot operation truly flexible for changing business requirements while maintaining optimal performance.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Two passes: first to discover stores O(n), then to execute pivot query O(n)

n
2n
Linear Growth
Space Complexity
O(s + p)

Where s is number of unique stores and p is number of unique products

n
2n
Linear Space

Constraints

  • 1 ≤ product_id ≤ 104
  • 1 ≤ price ≤ 104
  • There will be at most 30 different stores in the table
  • store names are valid SQL identifiers
  • Advanced SQL knowledge required - dynamic SQL and stored procedures
Asked in
Amazon 45 Microsoft 38 Google 32 Oracle 28
24.6K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen