Great question!
Yes, there is a way to avoid the "cross join" (cartesian product) effect when unnesting multiple arrays in PostgreSQL. The cross join effect happens if you call unnest() on multiple arrays in the same SELECT list, like this:
SELECT
unnest(order_item_id),
unnest(order_id),
unnest(item_price),
unnest(quantity)
FROM order_item;
This produces every possible combination of elements from each array, which is not what you want.
The Correct Way: Unnest with Array Alignment
To keep the elements aligned by their index, you should use the unnest() with multiple arrays as arguments (PostgreSQL 9.4+), like this:
SELECT
rg_id,
item_idx,
order_item_id,
order_id,
item_price,
quantity
FROM order_item,
LATERAL unnest(
order_item_id,
order_id,
item_price,
quantity
) WITH ORDINALITY AS t(order_item_id, order_id, item_price, quantity, item_idx)
- This will align the elements by their index (i.e., the first element of each array is together, the second element is together, etc.).
- The
WITH ORDINALITY gives you the index (item_idx) if you need to filter for a specific position.
Example: Get the 100th Element from Each Array
SELECT
rg_id,
t.order_item_id,
t.order_id,
t.item_price,
t.quantity
FROM order_item,
LATERAL unnest(
order_item_id,
order_id,
item_price,
quantity
) WITH ORDINALITY AS t(order_item_id, order_id, item_price, quantity, idx)
WHERE t.idx = 100;
Example: Get Elements at Indices 1, 100, and 500
SELECT
rg_id,
t.order_item_id,
t.order_id,
t.item_price,
t.quantity,
t.idx
FROM order_item,
LATERAL unnest(
order_item_id,
order_id,
item_price,
quantity
) WITH ORDINALITY AS t(order_item_id, order_id, item_price, quantity, idx)
WHERE t.idx IN (1, 100, 500);
Summary
- Do not use multiple
unnest() calls in the same SELECT list (causes cross join).
- Do use a single
unnest() call with all arrays as arguments, plus WITH ORDINALITY for index alignment.
- This is the most efficient and correct way to access related elements across multiple arrays in PostgreSQL.
Let me know if you need more examples or have a specific query in mind!