Tuesday, July 1, 2008

[SQL] column default dependant on another columns value

Hi list,

Given a table with columns seconds and minutes, how can I have minutes be
computed automatically at the insert statement?

I tried:

ALTER TABLE table1 ALTER COLUMN minutes SET default (seconds/60);

Postgres' answer was:
ERROR: cannot use column references in default expression

So I gave rules a look but it seems rules apply to the entire row.

CREATE RULE "my_rule" AS ON
INSERT TO table1
WHERE minutes is null
DO INSTEAD
INSERT INTO table1 (column1, column2, seconds, minutes)
VALUES(new.column1, new.column2, new.seconds, new.seconds/60);

Is this correct? Is there another (better/simpler) way to achieve this?

Regards,
Fernando


--
Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql

No comments: