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

Re: [SQL] Auto increment field when updating?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Robin Keech <robin(at)dialogue(dot)co(dot)uk>
Cc: "'pgsql-sql(at)postgresql(dot)org'" <pgsql-sql(at)postgreSQL(dot)org>
Subject: Re: [SQL] Auto increment field when updating?
Date: 2000-02-16 14:36:56
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-sql
Robin Keech <robin(at)dialogue(dot)co(dot)uk> writes:
> ... Only some fields are written to each time the row is updated.
> There is one field called 'count' that ONLY needs to increment every
> time that particular row AND the field 'count' are updated.

> I know that I can select the information, increment it and update it
> back again, but is there any way of setting up the database to do this
> automatically?  I am using PostgreSQL 6.5.

Sure, use a trigger.  Here's one I use for a table that wants to attach
a globally new sequence number to each created or updated row:

  NEW.sequenceNo := nextval(''my_phistory_Seq'');
' LANGUAGE 'plpgsql';

CREATE TRIGGER my_phistory_trigger BEFORE INSERT OR UPDATE ON my_phistory
FOR EACH ROW EXECUTE PROCEDURE my_phistory_trigger();

but if you just want to increment the number that's there, you could do

  NEW.sequenceNo := OLD.sequenceNo + 1;

(bearing in mind that this'll only work as an UPDATE trigger, not
INSERT).  See the programmer's guide for doco on trigger functions.

			regards, tom lane

In response to

pgsql-sql by date

Next:From: Kovacs Zoltan SandorDate: 2000-02-16 15:58:45
Subject: Re: [SQL] Re: BSC
Previous:From: Vladimir TerzievDate: 2000-02-16 14:06:12
Subject: Re: BSC

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