array_positions Locates Every Occurrence

array_positions returns the subscripts of all occurrences of a value in a one-dimensional array, using IS NOT DISTINCT FROM so NULL can be searched too.

SqlData Fetching

Code

snippet
CREATE TABLE deployments (
    service  text   NOT NULL,
    replicas text[] NOT NULL
);

INSERT INTO deployments VALUES
    ('gateway', ARRAY['us-1', 'eu-1', 'us-1', 'ap-1']),
    ('billing', ARRAY['eu-1', 'eu-1']);

-- array_positions:该值出现的全部下标(找不到返回空数组,不是 NULL)
SELECT service,
       array_positions(replicas, 'us-1') AS us_slots
FROM deployments;

-- 也能搜 NULL 元素:比较用 IS NOT DISTINCT FROM 语义
SELECT array_positions(ARRAY['x', NULL::text, 'x'], NULL) AS null_slots;

-- array_position 只给第一处下标;没有则返回 NULL
SELECT service,
       array_position(replicas, 'ap-1') AS first_ap
FROM deployments;

-- 组合用法:命中数用 cardinality 数
SELECT service,
       cardinality(array_positions(replicas, 'eu-1')) AS eu_count
FROM deployments;

How it works

SELECT / INSERT / CREATE statements share the script, touching deployments.

Breaking the statements into their working parts: NOT NULL qualifiers on the required columns.

Putting it to use

The deployments table is the working surface here.

Core lines

INSERT INTO deployments VALUES
    ('gateway', ARRAY['us-1', 'eu-1', 'us-1', 'ap-1']),
    ('billing', ARRAY['eu-1', 'eu-1']);
SELECT service,
       cardinality(array_positions(replicas, 'eu-1')) AS eu_count
FROM deployments;
CREATE TABLE deployments (
    service  text   NOT NULL,
    replicas text[] NOT NULL
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `deployments`.