Skip insert query if value is null
I have a postgreSQL trigger for my social media project where once a comment is inserted, the trigger inserts a new row into the commentData table and the subscriptions table as shown below.
create or replace function public.initialize_comment_data_subscribe()
returns trigger as $$
begin
INSERT INTO "commentData" (comment_id, post_id, vote_count, children_count)
VALUES (new.id, new.post_id, 0, 0);
INSERT INTO subscriptions (comment_id, post_id, user_id, email)
VALUES (new.id, new.post_id, new.author_id, (SELECT email from users WHERE user_id = new.author_id));
RETURN NEW;
end;
$$ language plpgsql;
create trigger on_create_comment
after INSERT on comments
for each row execute procedure public.initialize_comment_data_subscribe();
When the email is null in the users table for a specific user_id, the whole thing fails due to the following line
... (SELECT email from users WHERE user_id = new.author_id));
But instead I would like the first insert to continue working and the second one to be skipped if the email is null.
How do I go about doing this? Or is it better to split the insert queries and have 2 triggers instead.
Do a SELECT INSERT instead:
INSERT INTO subscriptions (comment_id, post_id, user_id, email)
SELECT new.id, new.post_id, new.author_id, email
from users WHERE user_id = new.author_id AND email is not null