UNNEST WITH ORDINALITY Position

Expand arrays with unnest WITH ORDINALITY so each element keeps its original 1-based position through a LATERAL join instead of losing order.

SqlData Integrity

Code

snippet
-- 数组展开时保留原始位置:WITH ORDINALITY 给每行附加从 1 开始的下标
CREATE TABLE releases (
    id    bigserial PRIMARY KEY,
    app   text NOT NULL,
    hosts text[] NOT NULL
);
INSERT INTO releases (app, hosts) VALUES
    ('checkout', ARRAY['web-1', 'web-2', 'web-3']),
    ('ledger',   ARRAY['db-1']);

SELECT r.app, h.value, h.position
FROM releases r
CROSS JOIN LATERAL unnest(r.hosts) WITH ORDINALITY AS h(value, position)
ORDER BY r.app, h.position;

-- 不带 ORDINALITY 的 unnest 会丢掉数组顺序信息
SELECT unnest(ARRAY['a', 'b', 'c']);

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with releases and lateral among the objects involved.

Concretely, the SQL combines: 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 releases table is the working surface here.

Statements that matter

SELECT r.app, h.value, h.position
FROM releases r
CROSS JOIN LATERAL unnest(r.hosts) WITH ORDINALITY AS h(value, position)
ORDER BY r.app, h.position;
INSERT INTO releases (app, hosts) VALUES
('checkout', ARRAY['web-1', 'web-2', 'web-3']),
('ledger',   ARRAY['db-1']);
CREATE TABLE releases (
id    bigserial PRIMARY KEY,
app   text NOT NULL,
hosts text[] NOT NULL
);

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `releases`, `lateral`, with one join tying the pair together.