0

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:

DO $$ 
BEGIN
<code_block>
END
$$

But the error remains.

3
  • 1
    There is no IF in the SQL language Commented Mar 17, 2022 at 11:30
  • @a_horse_with_no_name. But I found it in the postgres documentation. Section 43.6 in 14 version Commented Mar 17, 2022 at 14:53
  • Not sure which version of the manual you refer to, but that's most likely the section about the PL/pgSQL procedural language you were looking at. The SQL language does not have an IF Commented Mar 17, 2022 at 14:58

1 Answer 1

1

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
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.