Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Getting max free ID available in postgresql for int8

I have a table with few IDs say 100000, 99999, 99998, 1000, 10, 5. Now my requirement is to get max ID which is not used.

Sample data:

CREATE TABLE foo
AS
  SELECT *
  FROM ( VALUES (10000),(9999),(9998),(100),(5),(2) )
    AS t(id);

In above case, it should be 99997. Any query to get this max available ID?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

I've used lead() function to get difference between current id and next id on descending order.

with ct as
(
    select id, lead(id) over (order by id desc) as nextid
    from foo
)
select   id -1 as next_id
from     ct
where    id - nextid > 1
order by id desc
limit 1;

next_id
-------
 9997

drop table foo;

Rextester here

over 4 years ago · Santiago Trujillo Report

0

One method uses left join:

select t.id - 1
from t left join
     t tprev
     on t.id = tprev.id + 1
where tprev.id is null
order by t.id desc
limit 1;

Another uses lag():

select t.id - 1
from (select t.*, lag(id) over (order by id) as prev_id
      from t
     ) t
where prev_id <> id - 1
order by id desc
limit 1;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!