How can I do such query in Postgres?
IF (select count(*) from orders) > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are no procedural elements in standard SQL. The
IFstatement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with theDOcommand.You need a semicolon (
;) at the end of each statement in plpgsql (except for the finalEND).You need
END IF;at the end of theIFstatement.A sub-select must be surrounded by parentheses:
Or:
This is equivalent and much faster, though:
Alternative
The additional
SELECTis 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.