Knowledge Guide
HomeDatabasesSQL Practice Problems

Dynamic Pivoting of a Table

Problem

Table: Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store       | varchar |
| price       | int     |
+-------------+---------+
(product_id, store) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the price of product_id in store.
There will be at most 30 different stores in the table.
price is the price of the product at this store.

Problem Definition

Implement the procedure PivotProducts to reorganize the Products table so that each row has the id of one product and its price in each store. The price should be null if the product is not sold in a store. The columns of the table should contain each store and they should be sorted in lexicographical order.

The procedure should return the table after reorganizing it.

Return the result table in any order.

Example

Image
Image

Output

Image
Image

Solution

To transform the Products table into a pivoted format where each row represents a unique product_id with its corresponding prices across various stores, we need to dynamically generate SQL statements. This is essential because the number of stores can vary, and SQL doesn't inherently support dynamic column generation in static queries. The provided stored procedure PivotProducts accomplishes this using dynamic SQL, window functions, and conditional aggregation. Below is a comprehensive breakdown of the approach, step-by-step execution, and detailed explanations for each component of the SQL query.

Approach Overview

  1. Understand the Data Structure:

    • Each row in the Products table represents the price of a specific product in a particular store.
    • The combination of (product_id, store) is unique, ensuring that each product-store pair appears only once.
  2. Identify Unique Stores:

    • Since the number of stores can vary (up to 30 as per the problem statement), we need a dynamic way to handle each store as a separate column in the pivoted result.
  3. Construct Dynamic SQL for Pivoting:

    • Use GROUP_CONCAT to dynamically generate the SQL segments required for each store.
    • Aggregate the prices using conditional logic to place them under their respective store columns.
  4. Execute the Dynamic SQL:

    • Prepare, execute, and deallocate the dynamically constructed SQL statement to produce the final pivoted table.

SQL Query

CREATE PROCEDURE PivotProducts() BEGIN # Write your MySQL query statement below. SET group_concat_max_len = 1000000; #This is tricky. There's a length limit on GROUP_CONCAT. SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'SUM(IF(store = "', store, '", price, null)) AS ', store) ORDER BY store ASC) INTO @sql FROM Products; SET @sql = CONCAT('SELECT product_id, ', @sql, ' FROM Products GROUP BY product_id'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; END

Step-by-Step Explanation

Step 1: Increase GROUP_CONCAT Maximum Length

SET group_concat_max_len = 1000000; #This is tricky. There's a length limit on GROUP_CONCAT.

Step 2: Initialize the Dynamic SQL Variable

SET @sql = NULL;

Step 3: Dynamically Generate the SELECT Clause for Each Store

SELECT GROUP_CONCAT(DISTINCT CONCAT( 'SUM(IF(store = "', store, '", price, null)) AS ', store) ORDER BY store ASC) INTO @sql FROM Products;

Step 4: Construct the Final Dynamic SQL Statement

SET @sql = CONCAT('SELECT product_id, ', @sql, ' FROM Products GROUP BY product_id');

Step 5: Prepare and Execute the Dynamic SQL Statement

PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

Final Pivoted Output

Executing the stored procedure PivotProducts() will produce a result set similar to the following, depending on the data in the Products table:

+------------+-----------+-------+-------+-------+ | product_id | LC_Store | Nozama| Shop | Souq | +------------+-----------+-------+-------+-------+ | 1 | 100 | NULL | 110 | NULL | | 2 | NULL | 200 | NULL | 190 | | 3 | NULL | NULL | 1000 | 1900 | +------------+-----------+-------+-------+-------+
🤖 Don't fully get this? Learn it with Claude

Stuck on Dynamic Pivoting of a Table? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Dynamic Pivoting of a Table** (Databases) and want to truly understand it. Explain Dynamic Pivoting of a Table from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Dynamic Pivoting of a Table** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Dynamic Pivoting of a Table** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Dynamic Pivoting of a Table** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes