array_position Custom Id Ordering
Sort results by the id order an application already chose: array_position returns each id's index in the list, and NULLS LAST decides where unknown ids land.
Code
-- 应用层拿到的 id 列表顺序就是业务优先级:
-- 直接 ORDER BY id 会按数值重排,array_position 按它在列表中的位置排序
SELECT
id,
name,
array_position(ARRAY[42, 7, 19]::bigint[], id) AS preferred_rank
FROM products
WHERE id = ANY (ARRAY[42, 7, 19]::bigint[])
ORDER BY array_position(ARRAY[42, 7, 19]::bigint[], id);
-- id 不在列表里时 array_position 返回 NULL:
-- 显式决定这些行排在前还是后(NULLS LAST 落到最后)
SELECT
id,
name,
array_position(ARRAY[42, 7, 19]::bigint[], id) AS preferred_rank
FROM products
ORDER BY
array_position(ARRAY[42, 7, 19]::bigint[], id) NULLS LAST,
id;How it works
Several statements share this file — SELECT, with products among the objects involved.
In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.
Applying it
The products table is the working surface here.
Statements that matter
SELECT
id,
name,
array_position(ARRAY[42, 7, 19]::bigint[], id) AS preferred_rank
FROM products
WHERE id = ANY (ARRAY[42, 7, 19]::bigint[])
ORDER BY array_position(ARRAY[42, 7, 19]::bigint[], id);
SELECT
id,
name,
array_position(ARRAY[42, 7, 19]::bigint[], id) AS preferred_rank
FROM products
ORDER BY
array_position(ARRAY[42, 7, 19]::bigint[], id) NULLS LAST,
id;
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.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.
FAQ
- Which tables does the SQL touch?
- `products` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.