In one SQL statement, I am trying to insert a row, and if that fails due to a constraint, then return the existing row.
I have:
INSERT INTO session (token, expiry) SELECT 'abcdefg', '2014-05-14 20:25:12.279667' WHERE NOT EXISTS (SELECT * FROM session where token= 'abcdefg');
The token
column has a unique constraint. I've tried appending RETURNING *
at the end, but that still does not return the existing row.
Why is this? I thought my last SELECT
statement will be executed and returned. Any ideas?
Note: I cannot use a Postgres function or multiple SQL statements due to some complicated race condition.