Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres syntax error in IF statement with NOT EXIST statement

I want to use IF statement in insertion.

INSERT INTO <table_name>(<columns>) 
VALUES (IF NOT EXISTS (<exist_statement>) THEN 
               (<first set of values>), 
               (<second set of values>) 
        ELSE 
               (<first set of values>) 
        END IF
);

But the following error appears:

syntax error at or near "NOT"
LINE 1: ...r_id, role_id, role_type, user_status) VALUES (IF NOT EXISTS...
                                                             ^

I tried putting this block of code in the DO:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DO $$ 
BEGIN
<code_block>
END
$$

But the error remains.

>Solution :

You need to use case:

INSERT INTO <table_name>(<columns>) 
VALUES (CASE WHEN NOT EXISTS (<exist_statement>) THEN 
               (<first set of values>), 
               (<second set of values>) 
        ELSE 
               (<fist set of values>) 
        END
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading