How to check if a row exists in a PostgreSQL stored procedure?

ams picture ams · Oct 11, 2012 · Viewed 18.7k times · Source

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.

Answer

Erwin Brandstetter picture Erwin Brandstetter · Oct 11, 2012

Or even simpler with EXISTS:

IF EXISTS (SELECT 1 FROM foo WHERE x = 'abc' AND y = 'xyz') THEN
    ....
END IF;