Product's Price for Each Store - Problem

Given a Products table that stores product prices for different stores, write a SQL query to find the price of each product in each store.

The Products table has the following structure:

  • product_id: Integer representing the product identifier
  • store: Enum with values ('store1', 'store2', 'store3') indicating which store sells the product
  • price: Integer representing the price of the product at that store

The combination of (product_id, store) is the primary key, meaning each product can have different prices at different stores.

Goal: Transform the data to show each product as a row with columns for each store's price. If a product is not available at a store, the price should be NULL.

Table Schema

Products
Column Name Type Description
product_id PK int Product identifier
store PK enum Store name ('store1', 'store2', 'store3')
price int Price of product at this store
Primary Key: (product_id, store)
Note: Each row represents a product available at a specific store with its price

Input & Output

Example 1 — Multiple Products and Stores
Input Table:
product_id store price
0 store1 95
0 store3 105
0 store2 70
1 store1 110
Output:
product_id store1 store2 store3
0 95 70 105
1 110
💡 Note:

Product 0 is available in all three stores with different prices (95, 70, 105). Product 1 is only available in store1 for 110, so store2 and store3 show NULL values.

Example 2 — Single Product Single Store
Input Table:
product_id store price
5 store2 200
Output:
product_id store1 store2 store3
5 200
💡 Note:

Product 5 is only available at store2 for 200. The other stores (store1 and store3) show NULL since this product is not sold there.

Constraints

  • 1 ≤ product_id ≤ 1000
  • 1 ≤ price ≤ 3000
  • store is one of 'store1', 'store2', or 'store3'
  • Each (product_id, store) combination appears at most once

Visualization

Tap to expand
Product Price Pivot: Rows to ColumnsInput: Normalized Dataproduct_idstoreprice0store1950store2700store31051store1110PIVOTOutput: Pivoted Viewproduct_idstore1store2store3095701051110NULLNULLSame products, different structureMultiple rows per product → One row per product
Understanding the Visualization
1
Input
Products table with separate rows per store
2
Pivot
GROUP BY + CASE WHEN to create columns
3
Output
One row per product with store price columns
Key Takeaway
🎯 Key Insight: Use conditional aggregation to pivot normalized data into a cross-tabular format
Asked in
Amazon 15 Microsoft 12 Google 8
23.4K Views
Medium Frequency
~8 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