Skip to content
Advertisement

PostgreSQL IF statement

How can I do such query in Postgres?

Advertisement

Answer

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

Or:

This is equivalent and much faster, though:

Alternative

The additional SELECT is not needed. This does the same, faster:

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement