INSERT INTO WHERE NOT EXISTS

If you want to insert values into a MySQL table, but only if those values don’t already exist, and you don’t want to use a primary key on the table (and deal with the resulting error suppression ), here’s an elegant one-query method of doing so.

INSERT INTO [table name] SELECT '[value1]', '[value2]' FROM DUAL
WHERE NOT EXISTS(
SELECT [column1] FROM [same table name]
WHERE [column1]='[value1]'
AND [column2]='[value2]' LIMIT 1)

OK, technically it’s not a single query.
But it is only one round trip to the MySQL server.

No comments:

Post a Comment