I want to implement a not-null constraint on an attribute using a trigger. Here's my code:
create table mytable2(id int);
create or replace function p_fn() returns trigger as $prim_key$
begin
if (tg_op='insert') then
if (id is null) then
raise notice 'ID cannot be null';
return null;
end if;
return new;
end if;
end;
$prim_key$ language plpgsql;
create trigger prim_key
before insert on mytable2
for each row execute procedure p_fn();
But I get an error saying "control reached end of trigger procedure without RETURN" whenever I try to insert a null value. I tried placing the "return new" statement in the inner IF, but it still gave me the same error. What am I doing wrong?
NOT NULL?create table mytable2(id int not null);CHECKorNOT NULLconstraints. This is teaching students very bad habits, triggers are what you use when none of the declarative options are capable of solving the problem, not the tool you reach for first.