Home  >  Q&A  >  body text

How to implement "insert if not exists" operation in MySQL?

<p>I first found this article through a Google search, <em>How to write an INSERT if NOT EXISTS query in standard SQL</em>, which discusses mutually exclusive tables. </p> <p>I have a table with about 14 million records. If I want to add more data in the same format, is there a way to ensure that the record I want to insert does not exist without using a pair of queries (i.e. one query to check and one query to insert, with the result set is empty)? </p> Does the <code>unique</code> constraint on the <p>field guarantee that <code>insert</code> will fail if it already exists? </p> <p>Looks like <em> is just </em> a constraint, and when I issue the insert via PHP, the script rattles. </p>
P粉005105443P粉005105443418 days ago504

reply all(2)I'll reply

  • P粉338969567

    P粉3389695672023-08-30 10:05:32

    solution:

    INSERT INTO `table` (`value1`, `value2`) 
    SELECT 'stuff for value1', 'stuff for value2' FROM DUAL 
    WHERE NOT EXISTS (SELECT * FROM `table` 
          WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1)

    illustrate:

    Innermost query

    SELECT * FROM `table` 
          WHERE `value1`='stuff for value1' AND `value2`='stuff for value2' LIMIT 1

    Used as a WHERE NOT EXISTS condition to detect whether a row containing the data to be inserted already exists. The query may stop after finding a row of this class, so LIMIT 1 (micro-optimization, can be omitted).

    Intermediate query

    SELECT 'stuff for value1', 'stuff for value2' FROM DUAL

    represents the value to be inserted. DUAL refers to a special single row single table that exists by default in all Oracle databases (see https://en.wikipedia.org/wiki/DUAL_table). On MySQL-Server version 5.7.26, I get valid queries when FROM DUAL is omitted, but older versions (like 5.5.60) seem to require the FROM information. By using WHERE NOT EXISTS, if the innermost query finds matching data, the intermediate queries will return an empty result set.

    External query

    INSERT INTO `table` (`value1`, `value2`)

    Insert data (if intermediate query returns any data).

    reply
    0
  • P粉521013123

    P粉5210131232023-08-30 00:40:11

    Use INSERT IGNORE INTO table.

    There is also INSERT … ON DUPLICATE KEY UPDATE syntax, which you can use in 13.2.6.2 INSERT … ON DUPLICATE KEY UPDATE statement .


    Post from bogdan.org.ua According to Google's web cache:

    reply
    0
  • Cancelreply