Skip to content
Advertisement

If statement with select in Postgresql

I’ve having trouble to do a if with select, e.g:

In SQL Server I can do this:

IF NOT EXISTS (SELECT  1 FROM mytable where "name" = 'myname')
BEGIN
    /*Do something*/
END
GO

But in postgresql I don’t have any idea how handle this. I’ve tring some ways to do this, but unfortunately I have not success.

Advertisement

Answer

The syntax for an IF in Postgres (or rather PL/pgSQL) is IF ... THEN ... END IF;, so you can use the one you have and replace BEGIN with THEN and END with END IF;. Remove the GO.

IF NOT EXISTS (SELECT *
                      FROM mytable
                      WHERE name = 'myname') THEN
  ...
END IF;

If that code piece is embedded in any PL/pgSQL function, procedure, etc. that’s it. If not, i.e. you want to execute it ad hoc, you need to enclose it in a DO block.

DO
$$
BEGIN
  IF NOT EXISTS (SELECT *
                        FROM mytable
                        WHERE name = 'myname') THEN
    ...
  END IF;
END;
$$
LANGUAGE plpgsql;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement