Parallel Unnest Zips Multiple Arrays

unnest accepts several arrays at once and zips them row by index, padding shorter arrays with nulls so ragged inputs still expand to a clean table.

SqlData Integrity

Code

snippet
-- parallel unnest:multiple arrays 按下标配对成行(zip 语义)
SELECT *
FROM unnest(
         ARRAY['alpha', 'beta', 'gamma'],
         ARRAY[12, 7, 30],
         ARRAY[true, false, true]
     ) AS t(token, score, active)
ORDER BY score DESC;

-- 数组长度不一致:短数组右侧补 NULL,行数取最长数组
SELECT *
FROM unnest(ARRAY['a', 'b', 'c'], ARRAY[1, 2]) AS t(label, value);

-- 常见落库形态:两条平行数组列展开成行后与表数据连接
CREATE TEMP TABLE import_batches (
    batch   text PRIMARY KEY,
    tokens  text[] NOT NULL,
    amounts numeric[] NOT NULL
);

INSERT INTO import_batches VALUES
    ('b1', ARRAY['sku-1', 'sku-2'], ARRAY[9.90, 24.50]),
    ('b2', ARRAY['sku-3'], ARRAY[7.25]);

SELECT
    i.batch,
    u.token,
    u.amount
FROM import_batches i
CROSS JOIN LATERAL unnest(i.tokens, i.amounts) AS u(token, amount)
ORDER BY i.batch, u.token;

What the code does

SELECT / INSERT / CREATE statements share the script, touching unnest, import_batches and lateral.

import_batches is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

Mechanically, the statements are built from: one JOIN combining rows across tables; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The file sets up its own scratch surface: it builds the session-local tables it works with (import_batches), so one full run against a throwaway database is enough.

Statements that matter

SELECT
    i.batch,
    u.token,
    u.amount
FROM import_batches i
CROSS JOIN LATERAL unnest(i.tokens, i.amounts) AS u(token, amount)
ORDER BY i.batch, u.token;
SELECT *
FROM unnest(
         ARRAY['alpha', 'beta', 'gamma'],
         ARRAY[12, 7, 30],
         ARRAY[true, false, true]
     ) AS t(token, score, active)
ORDER BY score DESC;
INSERT INTO import_batches VALUES
    ('b1', ARRAY['sku-1', 'sku-2'], ARRAY[9.90, 24.50]),
    ('b2', ARRAY['sku-3'], ARRAY[7.25]);

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`unnest`, `import_batches`, `lateral` — joined via one JOIN clause.