I writing a stored procedure in postgres where I need to check if a row exists then act accordingly. something along the line.
IF SELECT * FROM foo WHERE x = 'abc' AND y = 'xyz' THEN
-- do something here
ELSE
-- do something else
END;
I have googled a bit but got no good hits.
Use
PERFORMand theFOUNDautomatic variable:This will succeed if one or more rows is returned. If you want to constrain the result to exactly one row use
GET DIAGNOSTICSto get the row count, or useSELECT INTOto store thecount(...)of the rows into aDECLAREd variable you then test. If it’s an error to get no results, useSELECT INTO STRICTto require that exactly one row be obtained and stored into the target variable.Beware of concurrency issues when doing anything like this. If you’re attempting to write an upsert/merge function this approach will not work. See “why is upsert so complicated”.