Last active
March 9, 2024 20:43
-
-
Save rodo/7fb45f8a31b5775402c4f57ea17521a7 to your computer and use it in GitHub Desktop.
Want to fill the holes in a column previously defined with a serial in PostgreSQL
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
| -- Want to file the holes in a column previously defined with a serial | |
| -- Useful only with small tables with less than 10k rows, over the operation | |
| -- max() and the join will cost too much | |
| -- | |
| CREATE OR REPLACE FUNCTION nextid() | |
| RETURNS integer | |
| LANGUAGE plpgsql | |
| AS $$ | |
| DECLARE | |
| new_id integer; | |
| BEGIN | |
| WITH maxid AS ( | |
| SELECT COALESCE(max(id),0) + 1 as maxid FROM boat | |
| ), | |
| ids as ( | |
| SELECT generate_series(1,maxid,1) as id FROM maxid | |
| ) | |
| SELECT min(ids.id) INTO new_id | |
| FROM boat | |
| RIGHT JOIN ids ON boat.id = ids.id | |
| WHERE boat.id IS NULL; | |
| RETURN new_id; | |
| END; | |
| $$ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment