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.

SqlData Fetching

Code

snippet
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

FAQ

Which tables does the SQL touch?
`generate_subscripts` — referenced directly, no join needed.