Search code examples
mysqlsqlmysql-workbenchmysql-pythonmysql-error-1064

Check before adding the data into table in mysql database


I am trying to insert data in table emp_master where token_no and vehicle_no is available, I am using mentioned below query to add and check the record

insert into emp_master (token_no, vehicle_no) values (1234,12345) where not exists (select * from emp_master where vehicle_no = '12345');

but whenever I am trying this then error comes in as

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where not exists (select * from emp_master where vehicle_no = '12345')' at line 1

The suggestion will be helpful


Solution

  • If you need to have this check in your insert statement, you can structure it like this:

    SQL Fiddle: http://sqlfiddle.com/#!9/d3dd77/1

    insert into emp_master (token_no, vehicle_no) 
    select 1234, 12345
    from dual
    where not exists (select * from emp_master where vehicle_no = '12345');
    

    Another way to do this on any DBMS:

    DB Fiddle Demo

    insert into emp_master (token_no, vehicle_no) 
    select token_no, vehicle_no
    from (
    select 1234 token_no, 12345 vehicle_no
    ) rec
    where not exists (select * from emp_master where vehicle_no = rec.vehicle_no);