Shortcuts
Settings
00:00:00

Flatten Nested JSON Array in SQL

MEDIUM
Companies

Problem

Flatten Nested JSON Array in SQL.

An e-commerce checkout service exports each order as a single row where all purchased items are packed into one delimited items column (for example Laptop|Mouse|Keyboard), the way an upstream API once serialized a JSON array. The analytics team needs this in relational form: one row per individual item. Flatten the items column by splitting it on the | separator, producing one output row per item that carries the order's order_id and customer_id, the item's 1-based position within the order as item_position, and the item text as item_name. Sort the result by order_id ascending, then by item_position ascending.

Schema columns: orders.order_id, orders.customer_id, orders.items

Output columns: order_id, customer_id, item_position, item_name

Examples

Example 1

Input:

orders:

order_idcustomer_iditems
1101Laptop|Mouse|Keyboard
2102Monitor
3103USB|HDMI|VGA
4101Laptop|Screen
5102Mouse|Keyboard|USB|Monitor
6104Headphones

Output:

order_idcustomer_iditem_positionitem_name
11011Laptop
11012Mouse
11013Keyboard
21021Monitor
31031USB
31032HDMI
31033VGA
41011Laptop

The output above is truncated; the input table also shows only a sample of the rows, and the full result (22 rows) reflects the full dataset.

Explanation: Order 1 contains three pipe-delimited items, so it expands to three rows with positions 1 through 3 in the order they appear in the string. Order 2 has a single item and produces exactly one row with item_position 1. Every output row repeats the parent order's order_id and customer_id.

Constraints

  • Split items on the | character; positions are 1-based and follow the left-to-right order of items in the string.
  • Sort by order_id ascending, then item_position ascending.
  • Result columns must be named exactly: order_id, customer_id, item_position, item_name.
  • item_position must be an integer.
  • Single-item orders produce exactly one row with item_position = 1.

Try solving it yourself before revealing more hints

We've added new questions. Found a bug? Submit it using the feedback button.

AI Code Review
Run
SubmitS

Output