Last active
January 9, 2018 22:29
-
-
Save stellingsimon/0d551ea5396996cf7b6fb55fc1caba12 to your computer and use it in GitHub Desktop.
Reordering user-sortable Postgres tables in one `UPDATE` statement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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