Reputation: 123
Part of my SQL definition (for hsqldb):
CREATE TABLE activities (
id BIGINT GENERATED BY DEFAULT AS IDENTITY,
group_id BIGINT NOT NULL
CONSTRAINT pk_activities PRIMARY KEY (id)
);
The scenario during and insert
is:
id
is auto generated / auto-incremented,group_id
when specified (non-null) is set to the given value,group_id
when not specified is set to the value of id
just generatedI target postgresql and hsqldb (for tests).
Can this be done?
Upvotes: 2
Views: 1302
Reputation: 116367
You cannot set default value to be that of another column.
However, you can create a TRIGGER that would accomplish this task.
This is an example for PostgreSQL. It automatically replaces column
with anothercolumn
if it is NULL
before INSERT
or UPDATE
:
CREATE OR REPLACE FUNCTION mytable_fn()
RETURNS trigger AS
$body$
BEGIN
IF NEW.column ISNULL THEN
NEW.column := NEW.anothercolumn;
END IF;
RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql';
CREATE TRIGGER mytable_trigger
BEFORE INSERT OR UPDATE ON mytable
FOR EACH ROW
EXECUTE PROCEDURE mytable_fn();
Upvotes: 1
Reputation: 190
This can be done using a trigger or if you dont want to use triggers is to handle the NULL when selecting rows like this:
SELECT id, isnull(group_id, id) group_id FROM activities;
Upvotes: 1