There is no need for a PL/pgSQL block.
This can be done with a single SQL statement using writeable CTE:
with updated as (
UPDATE NOTES
SET NOTES='MY notes'
WHERE USER_ID = 2
AND EVENT_ID = 4
returning *
)
INSERT INTO NOTES (notes_id, event_id, user_id, notes)
select (SELECT max(NOTES_ID)+1 FROM NOTES), --<< Do NOT do this!!
4,
2,
'My notes'
where not exists (select * from updated);
Note that generating "unique" IDs using max(notes_id) + 1
is not safe for concurrent usage and will not scale well if the table size increase.
Also: you should use numeric literals for numbers, not strings. 2
is a number '2'
is a string.
If you have a unique index on (user_id, event_id)
(which you should given the nature of your question) you can also use insert on conflict
which was introduced in Postgres 9.5
INSERT INTO NOTES (notes_id, event_id, user_id, notes)
VALUES (
(SELECT max(NOTES_ID)+1 FROM NOTES), --<< Do NOT do this!
4, 2, 'My notes')
ON CONFLICT (user_id, event_id)
DO UPDATE set notes = excluded.notes;
A word of warning:
If you want to generate unique IDs in a reliable, concurrency-safe and scalable way you have to use a sequence. Do NOT use the anti-pattern max() + 1