I want to write something like a CASE
statement in PostgreSQL in such a way that I want to SELECT
from a table, and if nothing is found I want to INSERT
into the table instead.
My example table allocated_ideas
looks like this:
challenge_id | user_id | idea_id | round | is_completed
-------------+------------+----------------+-------+-------------
'5d956daa' | '9afbca19' | '3798826ae522' | 5 | false
And I want to do something like this in a SQL function:
SELECT EXISTS (
SELECT 1 from allocated_ideas ai
where ai.user_id = '9afbca19'
and ai.challenge_id = '5d956daa'
and ai.is_completed is false
If this condition is true, return the idea_id
. Otherwise, insert values into the table. Pseudo-code:
if (above query is true) {
SELECT idea_id from allocated_ideas ai
where ai.user_id = '9afbca19'
and ai.challenge_id = '5d956daa'
and ai.is_completed is false
} else {
INSERT VALUES INTO allocated_ideas('67879', '46578', '978798', 6, false)
}