Skip site navigation (1) Skip section navigation (2)

Re: tricky query

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: Merlin Moncure <merlin(dot)moncure(at)rcsonline(dot)com>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: tricky query
Date: 2005-06-28 15:12:46
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-performance
On Tue, Jun 28, 2005 at 10:21:16 -0400,
  Merlin Moncure <merlin(dot)moncure(at)rcsonline(dot)com> wrote:
> I need a fast way (sql only preferred) to solve the following problem:
> I need the smallest integer that is greater than zero that is not in the
> column of a table.  In other words, if an 'id' column has values
> 1,2,3,4,6 and 7, I need a query that returns the value of 5.
> I've already worked out a query using generate_series (not scalable) and
> pl/pgsql.  An SQL only solution would be preferred, am I missing
> something obvious?

I would expect that using generate series from the 1 to the max (using
order by and limit 1 to avoid extra sequential scans) and subtracting
out the current list using except and then taking the minium value
would be the best way to do this if the list is pretty dense and
you don't want to change the structure.

If it is sparse than you can do a special check for 1 and if that
is present find the first row whose successor is not in the table.
That shouldn't be too slow.

If you are willing to change the structure you might keep one row for
each number and use a flag to mark which ones are empty. If there are
relatively few empty rows at any time, then you can create a partial
index on the row number for only empty rows.

In response to

pgsql-performance by date

Next:From: Cosimo StrepponeDate: 2005-06-28 15:20:13
Subject: Re: tricky query
Previous:From: John A MeinelDate: 2005-06-28 15:07:50
Subject: Re: tricky query

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group