3

have an array of values. I wish to INSERT each of them as records if it does not already exist. can this be done in one statement in SQL?

traditional javascript approach:

[4,5,8]forEach( x => queryParams(
   insert into t1( c1 ) values( $1 )
   where not exists( select 1 from t1 where c1 = $1`,
   [x]
);

what would be ideal is something like

queryParams(
 `some fancy SQL here`,
 [ `{${join[4,5,8]}}` ]
);

many reasons for this, including limiting the cost of server round trips and transactions.

1 Answer 1

2

You can use a correlated sub-query to find the values that don't exist matching a condition:

INSERT INTO Records (X)
    SELECT X
    FROM unnest(ARRAY[4,5,8]) T (X)
    WHERE NOT EXISTS (SELECT * FROM Records WHERE X = T.X);

SQL Fiddle: http://sqlfiddle.com/#!15/e0334/29/0

Edited above to use unnest

Sign up to request clarification or add additional context in comments.

2 Comments

that works, but not very elegant, esp if the array is very long. would be nice to have one SQL statement where the array is an argument, rather than creating the statement anew with each array.
You can also unnest an array like updated answer above.

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.