I got table with 3 columns (Primary)id, type, name. I am inserting data into this table, and I need to prevent multiple rows with the same type and name. How can I check this and insert in one query?
I was trying
IF ((select id from models where type = 1 and name = 'test') is null)
THEN insert into models(type, name) values(1, 'test');
END IF;
but it is not working and I have no idea why( 0 experience with conditions in mysql) – it is giving me syntax error
#1064 - 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 'IF ((select id from models where type = 1 and name = 'test') is null)
THEN inse' at line 1
If this is needed in general (not only for this Insert), you should add a
UNIQUEconstraint on the(type, name)combination:Then you can simply add rows and if the combination exists in the table, the Insert will fail:
For one-time check only, try this instead: