Re: Resetting Serial Column Sequence Number

From: Shane Ambler <pgsql(at)007Marketing(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Resetting Serial Column Sequence Number
Date: 2006-10-14 07:32:41
Message-ID: 45309299.1060706@007Marketing.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Andreas Kretschmer wrote:
> Andreas Kretschmer <akretschmer(at)spamfence(dot)net> schrieb:
>
>> Adam <adam(at)spatialsystems(dot)org> schrieb:
>>
>>> I just emptied my table and I want all my new inserts to start with a
>>> 'location_id' of '1'. The table is named "locations" with a SERIAL column
>>> "location_id"

If you want to start at 1 why not
SELECT setval('locations_location_id_seq', 1);

>>> I tried the below SQL to rest the sequence ID but it's not working. What am I
>>> doing wrong?
>>>
>>> SELECT setval('locations_location_id_seq', (SELECT max(location_id) + 1 FROM
>>> locations));
>> The table locations are empty? Yeah, select max(location_id) from an
>> empty table is NULL, not 0. And NULL+1 -> NULL. You can't set a Sequence
>> to NULL, that makes no sense.
>
> Btw, to avoid this, you can use coalesce():
> SELECT setval('locations_location_id_seq', (SELECT coalesce(max(location_id),0) + 1 FROM locations));
>
> coalesce returns the first non-null value, either the result from max()
> or the second parameter, 0.
>
>
> Andreas

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Michael Fuhr 2006-10-14 09:04:15 Re: time type strange behaviour
Previous Message Thomas Kellerer 2006-10-14 07:31:36 Re: more anti-postgresql FUD