Re: [NOVICE] Setting a DEFAULT when NULL is inserted - Mailing list pgsql-novice

From Andreas Kretschmer
Subject Re: [NOVICE] Setting a DEFAULT when NULL is inserted
Date
Msg-id d43660e7-3bb2-94f1-20a1-6dfbb022ceaf@a-kretschmer.de
Whole thread Raw
In response to Re: [NOVICE] Setting a DEFAULT when NULL is inserted  (Andreas Kretschmer <andreas@a-kretschmer.de>)
List pgsql-novice

Am 12.07.2017 um 12:32 schrieb Andreas Kretschmer:
> i would suggest a TRIGGER on Insert.

as a short example:

test=# CREATE TABLE my_table
(
id integer,
insertion_datetime timestamp DEFAULT now()
);
CREATE TABLE
test=*# create or replace function set_timestamp() returns trigger as
$$begin new.insertion_datetime := now(); return new; end; $$language
plpgsql;
CREATE FUNCTION
test=*# create trigger trg_set_timestamp before insert on my_table for
each row when (new.insertion_datetime is null) execute procedure
set_timestamp();
CREATE TRIGGER
test=*# commit;
COMMIT
test=# insert into my_table (id) values (1);
INSERT 0 1
test=*# commit;
COMMIT
test=# insert into my_table (id, insertion_datetime) values (2, NULL);
INSERT 0 1
test=*# commit;
COMMIT
test=# select * from my_table ;
  id |     insertion_datetime
----+----------------------------
   1 | 2017-07-12 15:44:57.946964
   2 | 2017-07-12 15:45:05.083043
(2 Zeilen)

test=*#

note that the trigger fires only if the new.insertion_datetime is null
(a so called conditional trigger)


Regards, Andreas

--
2ndQuadrant - The PostgreSQL Support Company.
www.2ndQuadrant.com



pgsql-novice by date:

Previous
From: Albe Laurenz
Date:
Subject: Re: [NOVICE] Setting a DEFAULT when NULL is inserted
Next
From: Aleksey Tsalolikhin
Date:
Subject: Re: [NOVICE] Bulk load billions of records into Postgres cluster