Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: Get next free id inside a table in a specific range (not using sequences)

Tags:

postgresql

I have a table t_user:

CREATE TABLE t_user
(
  c_id bigint NOT NULL,
  c_lastname character varying(255)
)

The table is not using any sequences to generate the IDs, instead these are calculated outside of Postgres (don't ask, and don't care about possible problems that this can cause). Now there are some "holes" in a range from 0 to 1000 that I need to know of and fill up.

Is it possible to formulate a Postgres query that gives me all unused IDs in that table in a range from 0 to 1000?

like image 616
Wolkenarchitekt Avatar asked Jan 29 '13 16:01

Wolkenarchitekt


1 Answers

It's a classic case of using generate_series and an outer join:

SELECT i FROM t_user RIGHT JOIN generate_series(0,1000) as i ON (c_id=i)
 WHERE c_id is null;
like image 148
Daniel Vérité Avatar answered Sep 29 '22 20:09

Daniel Vérité