mysql insert if row does not exist already in a table with NO UNIQUE FIELDS

Glenn picture Glenn · Dec 28, 2009 · Viewed 8.4k times · Source

Looking for a while now already for how to accomplish this.

Seems that all solutions need unique fields with indexes.

Answer

afftee picture afftee · Dec 28, 2009

there is no IF NOT EXISTS syntax in INSERT, but you could make use of the ON DUPLICATE KEY mechanism. Assuming you create a unique index on firstname, lastname, your update might read:

INSERT INTO tb (firstname, lastname) 
VALUES ('Jack', 'Doe') 
ON DUPLICATE KEY UPDATE lastname = lastname;

which renders the insert neutral.