Skip to content

Instantly share code, notes, and snippets.

@rodo
Last active March 9, 2024 20:43
Show Gist options
  • Select an option

  • Save rodo/7fb45f8a31b5775402c4f57ea17521a7 to your computer and use it in GitHub Desktop.

Select an option

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
-- 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