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.

SqlData Fetching

Code

snippet
-- 应用层拿到的 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

FAQ

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