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);
This question is related to
sql
postgresql
if-statement
plpgsql
From the docs
IF boolean-expression THEN
statements
ELSE
statements
END IF;
So in your above example the code should look as follows:
IF select count(*) from orders > 0
THEN
DELETE from orders
ELSE
INSERT INTO orders values (1,2,3);
END IF;
You were missing: END IF;
Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"
select
case
when stage = 1 then 'running'
when stage = 2 then 'done'
when stage = 3 then 'stopped'
else
'not running'
end as run_status from processes
You could also use the the basic structure for the PL/pgSQL CASE with anonymous code block procedure block:
DO $$ BEGIN
CASE
WHEN boolean-expression THEN
statements;
WHEN boolean-expression THEN
statements;
...
ELSE
statements;
END CASE;
END $$;
References:
Source: Stackoverflow.com