determine sequence name for a serial

From: Robby Russell <robby(at)planetargon(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: determine sequence name for a serial
Date: 2004-10-28 04:06:15
Message-ID: 1098936375.6766.14.camel@vacant
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I am trying to track down a method of determining what a sequence name
is for a SERIAL is in postgresql.

For example,

CREATE TABLE foo (id SERIAL PRIMARY KEY NOT NULL, bar TEXT);

\d foo
Table "public.foo"
Column | Type | Modifiers
--------+---------+-----------------------------------------------------
id | integer | not null default nextval('public.foo_id_seq'::text)
bar | text |
Indexes:
"foo_pkey" primary key, btree (id)

Now, I have figured out how to get a list of all the sequences with:

foo=> SELECT relname FROM pg_class WHERE relkind='S' AND relname !~ '^pg_';
relname
------------
foo_id_seq
(1 row)

I can find public.foo in pg_tables, but I am not sure how to relate pg_tables and pg_class in order to find the sequence for a specific field in public.foo.

Can anyone point me in the right direction? I am trying to get out of the habit of hard-coding the sequence names in my code.

Now that I think of it, I am lacking 'public.' as well from my query.

Ok, so how would I go about getting the sequence name for a SERIAL field on any given schema.table? I would like to build a function that would return this value if I pass it the schema and table (and fieldname is necessary)

Thanks,

Robby

--
/***************************************
* Robby Russell | Owner.Developer.Geek
* PLANET ARGON | www.planetargon.com
* Portland, OR | robby(at)planetargon(dot)com
* 503.351.4730 | blog.planetargon.com
* PHP/PostgreSQL Hosting & Development
* --- Now supporting PHP5 and PHP4 ---
****************************************/

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Robby Russell 2004-10-28 04:33:21 Re: determine sequence name for a serial
Previous Message Joel 2004-10-28 01:35:27 Re: compatibilityissues from 7.1 to 7.4