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.
Code
-- 数组展开时保留原始位置: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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- The references are `releases`, `lateral`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.