Re: SELECT Question

From: Manfred Koizar <mkoi-pg(at)aon(dot)at>
To: Alex <alex(at)meerkatsoft(dot)com>
Cc: Lada 'Ray' Lostak <ray(at)unreal64(dot)net>, pgsql-general(at)postgresql(dot)org
Subject: Re: SELECT Question
Date: 2003-11-20 14:33:53
Message-ID: v6hprv808hieeqhunhvmucid6s6aap755v@email.aon.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-patches

On Thu, 20 Nov 2003 16:52:37 +0900, Alex <alex(at)meerkatsoft(dot)com> wrote:
>>>>Is there an easy way to write a select statement that returns me the
>>>>frist free number or any within the range of 200?
>>>>For example if 1-30, and 32-50 are occupied then i would like to fill in
>>>>the new entry with id 31.

Fortunately this is not the performance mailing list :-)

First free number:
SELECT max(t1.id) + 1
FROM t AS t1 INNER JOIN t AS t2
ON (t1.id < 200 AND t1.id < t2.id AND t2.id <= 200)
GROUP BY t2.id
HAVING max(t1.id) + 1 < t2.id
ORDER BY t2.id
LIMIT 1;

Make sure that there is always a row with id=0 and a row with id=200.

Any free number:
SELECT id - 1
FROM t
WHERE 1 < id AND id <= 200
AND NOT EXISTS (SELECT * FROM t AS t2 WHERE t2.id = t.id - 1)
LIMIT 1;

Always having a row with id=200 helps avoid unwanted corner cases.

One more:
SELECT coalesce(max(id), 0) + 1
FROM t
WHERE id <= 200
AND id = (SELECT count(*) FROM t AS t2 WHERE t2.id <= t.id);

This should work without any dummy rows. And it will not work, if id
is not unique or there is any row with id < 1.

Servus
Manfred

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2003-11-20 15:14:31 Re: ERROR: nodeRead: did not find '}' [x2]
Previous Message Franco Bruno Borghesi 2003-11-20 14:27:04 Re: pg_clog problems

Browse pgsql-patches by date

  From Date Subject
Next Message Joe Conway 2003-11-20 16:31:07 Re: SELECT Question
Previous Message Kris Jurka 2003-11-20 09:53:02 Re: SELECT Question