Skip to content

Instantly share code, notes, and snippets.

@stellingsimon
Last active January 9, 2018 22:29
Show Gist options
  • Save stellingsimon/0d551ea5396996cf7b6fb55fc1caba12 to your computer and use it in GitHub Desktop.
Save stellingsimon/0d551ea5396996cf7b6fb55fc1caba12 to your computer and use it in GitHub Desktop.
Reordering user-sortable Postgres tables in one `UPDATE` statement
CREATE TABLE tbl (
id UUID,
sort_order INT
);
-- 1 param of type UUID[]: pass in all IDs in the desired order
WITH updated_order(id, new_sort_order) AS (
SELECT tbl.id, u.new_sort_order
FROM tbl
LEFT OUTER JOIN unnest(? :: UUID []) WITH ORDINALITY AS u(id, new_sort_order) on tbl.id = u.id
)
UPDATE tbl
SET sort_order = updated_order.new_sort_order
FROM updated_order
WHERE tbl.id = updated_order.id
AND tbl.sort_order IS DISTINCT FROM updated_order.new_sort_order;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment