I wrote a query for my API where I must return a conflict
if the resource is not in a valid state for the request or not found
if the resource does not exists.
I do not want to send 2 queries to the database (to check whether the resource exists first, then update it). Because just checking if the row was updated is not enough, maybe the resource does not exists.
I always want a row returned which look like this:
exists | updated
--------+---------
t | t
(1 row)
My query works, I just wonder if there's a simpler approach to...
WITH updates AS (
UPDATE abc
SET status = 'cancelled'
WHERE id = $1 AND status = 'active' RETURNING 1
)
SELECT
EXISTS(SELECT 1 FROM abc WHERE id = $1) as exists,
EXISTS(SELECT 1 FROM updates) as updated