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.
Code
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
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 relations are involved here?
- The references are `deployments`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.