Question

Iam trying to insert a record and i want to check that it is not already present in the table.

I try

INSERT INTO emp (empno, name) 
VALUES(2, 'ram') 
WHERE empno NOT IN (select empno from emp);

but it shows error 'incorrect syntax near where'

Was it helpful?

Solution

You can use following query to insert records into emp If you are inserting one record at a time then following query will work as best as it can ...

insert into emp (empno,empname)
    select distinct empno,empname
      from ( 2 empno, 'ram' empname ) as a 
     where  a.empname not in ( select empname from emp )

If you are willing to insert multiple records then just find below query

insert into emp (empno,empname)
    select max(empno),empname 
      from ( select 2 empno, 'ram' empname 
              union 
             select 3 empno, 'ram1' empname 
              union 
             select 4 empno, 'ram' empname 
           ) as a 
     where a.empname not in ( select empname from emp )
     group by empname 

OTHER TIPS

You can't have WHERE clause on INSERT statements, you have WHERE clause only with SELECT/UPDATE

If you work with MySQL, you could do something like:

insert into emp (empno, name) values(2, 'ram') ON DUPLICATE KEY UPDATE name = 'ram'

And if you have a unique index on name column, you will be safe

You can use INSERT IGNORE to fail silently if the row exists. It will attempt the insert, but if the key exists it will do nothing.

INSERT IGNORE INTO emp (empno, name) VALUES (2, 'ram')

You might also want to take a look at INSERT ... ON DUPLICATE KEY UPDATE

you'd probably be looking for something like

insert into emp (empno, name) 
SELECT 2 , 'ram'
FROM emp 
WHERE 2 not in (select empno from emp) 

???

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top