Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql insert multiple rows if not exists

I have a sql table that has two columns id and name. I have list of names about 20 and I need to write a query that checks if name exists before insert.

Is there a better way of doing this rather then just having the below query 20 times but with different names (I need do this in t-sql):

IF NOT EXISTS(SELECT* 
              FROM   mytable 
              WHERE  name = 'Dan') 
  BEGIN 
      INSERT INTO mytable 
                  (name) 
      VALUES     ('dan') 
  END 
like image 479
user3884462 Avatar asked Aug 12 '14 14:08

user3884462


People also ask

How do I insert multiple rows at a time in SQL?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

How do you insert if row does not exist?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.

How do you insert value if not exists SQL?

The basic syntax for INSERT IF NOT EXISTS is as follows. Copy INSERT INTO name_of_the_table (column_name) SELECT * FROM (SELECT value_name) AS val WHERE NOT EXISTS (<conditonal expression>); In the name_of_the_table we insert the value_name in the column_name if the conditional expression is met.


Video Answer


3 Answers

INSERT INTO MyTable (Name)
SELECT  NewNames.Name
FROM    ( VALUES ('Name1'), ('Name2'), ('Name3') ) AS NewNames (Name)
WHERE   NOT EXISTS ( SELECT 1
                     FROM   MyTable AS MT
                     WHERE  MT.Name = NewNames.Name );
like image 96
Ralf Hundewadt Avatar answered Oct 04 '22 03:10

Ralf Hundewadt


I think you could use a merge statement:

MERGE INTO myTable AS Target
USING (VALUES ('name1'),('name2'),('...')) AS source (NAME)
ON Target.NAME = Source.NAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (NAME) VALUES (name)
like image 39
Dave.Gugg Avatar answered Oct 04 '22 04:10

Dave.Gugg


You can filter values with NOT EXISTS

INSERT INTO myTable (
    Name
)
SELECT DISTINCT
    Name
FROM (
        VALUES ('Name 1'),
               ('Name 2')
    ) AS NewNames(Name)
WHERE
    NOT EXISTS (SELECT 1 FROM TargetTable WHERE myTable.Name = NewNames.Name)

If your new names are in another table, you can change the select query in the above one.

Please note, that the DISTINCT keyword is necessary to filter out the duplications in the source data.

like image 20
Pred Avatar answered Oct 04 '22 03:10

Pred