generate_subscripts Enumerates Array Indexes
generate_subscripts emits the valid subscript range of one array dimension, and reverse walks it backwards; a missing dimension yields zero rows.
Code
SELECT ARRAY['ada','bo','cy'] AS team;
-- 一维数组:下标 1..3
SELECT generate_subscripts(ARRAY['ada','bo','cy'], 1) AS s;
-- reverse=true:倒着枚举
SELECT generate_subscripts(ARRAY['ada','bo','cy'], 1, true) AS s;
-- 下标与元素一起拿:子查询按下标取元素(数组下标从 1 起)
SELECT s AS idx, (ARRAY['ada','bo','cy'])[s] AS member
FROM generate_subscripts(ARRAY['ada','bo','cy'], 1) AS s;
-- 二维数组:dim=2 枚举第二维的下标
SELECT generate_subscripts(ARRAY[[1,2,3],[4,5,6]], 2) AS col;
-- 请求不存在的维度:零行返回,不报错
SELECT count(*) AS zero_rows
FROM generate_subscripts(ARRAY[1,2], 2);How the snippet works
SELECT statements share the script, touching generate_subscripts.
Breaking the statements into their working parts: COUNT aggregation.
Applying it
Run the statement against the generate_subscripts table.
Statements that matter
SELECT s AS idx, (ARRAY['ada','bo','cy'])[s] AS member
FROM generate_subscripts(ARRAY['ada','bo','cy'], 1) AS s;
SELECT count(*) AS zero_rows
FROM generate_subscripts(ARRAY[1,2], 2);
SELECT generate_subscripts(ARRAY['ada','bo','cy'], 1, true) AS s;
Interactive Tools for This Topic
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.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.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 tables does the SQL touch?
- `generate_subscripts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.