Re: calculated default

From: Richard Huxton <dev(at)archonet(dot)com>
To: SunWuKung <Balazs(dot)Klein(at)t-online(dot)hu>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: calculated default
Date: 2006-11-16 10:13:52
Message-ID: 455C39E0.3050204@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

SunWuKung wrote:
> I have a table with a sequence as its primary key.
> On insert I would like to have all its fields (except the primary key)
> default to the last one in the table (order by id desc limit 1).
> I guess I should use a trigger to do this but I don't know how.

I'm not sure you can really change the DEFAULT clause with a trigger,
but you can get close.

You'll want a BEFORE INSERT trigger (in plpgsql).
Select into a variable of type RECORD your last row (... ORDER BY id
DESC LIMIT 1)
Update the values of the NEW variable where they are currently NULL.
Return NEW

Two points to consider:
1. Consider locking the table to prevent inserts while doing this.
Whether you need to do so depends on what you want to happen when two
inserts happen at the same time.
2. What happens if there is no previous row in the table?

--
Richard Huxton
Archonet Ltd

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Albert 2006-11-16 10:20:44 Re: PostGreSql cannot start after windows update
Previous Message Richard Huxton 2006-11-16 10:09:45 Re: PostGreSql cannot start after windows update