Skip to content

Instantly share code, notes, and snippets.

@stellingsimon
Last active January 9, 2018 22:30
Show Gist options
  • Save stellingsimon/0339e4529f8041c851258c948dd65741 to your computer and use it in GitHub Desktop.
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
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