Last active
January 9, 2018 22:30
-
-
Save stellingsimon/0339e4529f8041c851258c948dd65741 to your computer and use it in GitHub Desktop.
Normalize SORT_ORDER column of a user-sortable Postgres table after DELETE/INSERTs
This file contains 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 INT, | |
sort_order INT | |
); | |
WITH updated_order(id, new_sort_order) AS ( | |
SELECT | |
id, | |
row_number() OVER (ORDER BY tbl.sort_order NULLS FIRST) | |
FROM tbl | |
) | |
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