Watch 10 video solutions for Dynamic Pivoting of a Table, a hard level problem involving Database. This walkthrough by Sahil & Sarra has 656,651 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Important note: This problem targets those who have a good experience with SQL. If you are a beginner, we recommend that you skip it for now.
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.
The result format is in the following example.
Example 1:
Input: Products table: +------------+----------+-------+ | product_id | store | price | +------------+----------+-------+ | 1 | Shop | 110 | | 1 | LC_Store | 100 | | 2 | Nozama | 200 | | 2 | Souq | 190 | | 3 | Shop | 1000 | | 3 | Souq | 1900 | +------------+----------+-------+ Output: +------------+----------+--------+------+------+ | product_id | LC_Store | Nozama | Shop | Souq | +------------+----------+--------+------+------+ | 1 | 100 | null | 110 | null | | 2 | null | 200 | null | 190 | | 3 | null | null | 1000 | 1900 | +------------+----------+--------+------+------+ Explanation: We have 4 stores: Shop, LC_Store, Nozama, and Souq. We first order them lexicographically to be: LC_Store, Nozama, Shop, and Souq. Now, for product 1, the price in LC_Store is 100 and in Shop is 110. For the other two stores, the product is not sold so we set the price as null. Similarly, product 2 has a price of 200 in Nozama and 190 in Souq. It is not sold in the other two stores. For product 3, the price is 1000 in Shop and 1900 in Souq. It is not sold in the other two stores.
Problem Overview: You are given a table where each row stores a product_id, a store name, and its price. The goal is to pivot the table so each store becomes a separate column and every product appears once with its price in each store column. The challenge is that the list of stores is not fixed, so the pivot must be generated dynamically.
Approach 1: Static Pivot Using CASE Aggregation (O(n * m) time, O(1) extra space)
If the set of stores is known ahead of time, you can pivot the table using conditional aggregation. For each store, create an expression like MAX(CASE WHEN store = 'StoreA' THEN price END). Group the results by product_id. This works because the CASE expression selects the price only for matching rows, and MAX collapses the grouped rows into a single value. The database scans n rows and evaluates conditions across m stores, giving roughly O(n * m) time complexity and constant auxiliary space. The downside is maintainability—every new store requires changing the query.
Approach 2: Dynamic Pivot with GROUP_CONCAT and Prepared Statements (O(n + m) time, O(m) space)
When store names are not known beforehand, build the pivot query dynamically. First, scan the table to collect distinct store values and construct conditional aggregation expressions using GROUP_CONCAT. Each generated expression looks like MAX(CASE WHEN store = 'X' THEN price END) AS `X`. The concatenated string becomes part of a dynamic SQL query that groups by product_id. Execute it using PREPARE and EXECUTE. The initial step processes all rows once to discover stores, then the final pivot query scans the dataset again. The total complexity is roughly O(n + m) with O(m) memory for the generated column list.
This method is common in reporting systems where schema flexibility matters. It leverages features specific to SQL engines like MySQL. The heavy lifting happens in aggregation rather than application code, which keeps the solution concise and efficient for database-centric workflows.
Recommended for interviews: Start by explaining the static pivot using CASE and GROUP BY. It demonstrates understanding of conditional aggregation. Then move to the dynamic pivot using GROUP_CONCAT and prepared SQL statements. Interviewers typically expect the dynamic approach because the problem explicitly requires handling unknown columns at runtime.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Static Pivot with CASE Aggregation | O(n * m) | O(1) | When all store columns are known beforehand and rarely change |
| Dynamic Pivot with GROUP_CONCAT + Prepared SQL | O(n + m) | O(m) | When pivot columns are unknown and must be generated dynamically at runtime |