Insert 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
    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.

Hat tip to Matt Mongeau

13 thoughts on “Insert where not exists”

  1. Pingback: beat the bookstore
  2. Pingback: website url
  3. Pingback: Kompositfonster
  4. Pingback: reparatii laptop
  5. Pingback: seo tips n tricks
  6. Pingback: MySQL

Leave a Reply