HOWTO · MySQL

How to INSERT IF NOT EXISTS in MySQL

Learn how to insert a row in MySQL only when no row matches your chosen duplicate rule.

On this page

MySQL does not have a literal INSERT IF NOT EXISTS clause. To insert only when no row matches a chosen rule, use INSERT ... SELECT ... WHERE NOT EXISTS. The NOT EXISTS subquery checks that rule; it does not decide what counts as a duplicate for you.

For example, a student table might treat a first name as the match criterion for a demonstration. In a real application, choose columns that represent the identity you need to keep unique. A first name alone is usually not a suitable identity rule because different people can share it. The example below is illustrative; it does not connect to MySQL or execute SQL.

Choose the Duplicate Rule

Decide which existing values make a candidate row a duplicate before writing the query. The predicate inside NOT EXISTS must test those columns. If a student is identified by a student number, compare that number. If a registration is identified by both a course and a student, compare both values. A check on the wrong columns can skip a row you meant to insert or allow a logical duplicate through.

The pattern is conditional: the SELECT supplies the candidate values, and its WHERE NOT EXISTS condition permits the INSERT only when the subquery finds no match. MySQL has no special clause named INSERT IF NOT EXISTS; this is a normal INSERT ... SELECT query with a condition.

Prepare a Sample Table

For the SQL examples, use a table with an integer student ID and two name columns. One possible definition is CREATE TABLE student_details (stu_id INT PRIMARY KEY, stu_firstName VARCHAR(255), stu_lastName VARCHAR(255));. Seed it with a few rows, including (1, 'Preet', 'Sanghavi') and (2, 'Rich', 'John'), using a normal INSERT INTO student_details (stu_id, stu_firstName, stu_lastName) VALUES ... statement. These SQL fragments describe the setup; the Python illustration below models the decision separately and does not connect to MySQL.

Insert Only When No Matching Row Exists

For a table with columns stu_id, stu_firstName, and stu_lastName, use one statement for each candidate. The first candidate matches the existing first name Preet, so this statement inserts no row: INSERT INTO student_details (stu_id, stu_firstName, stu_lastName) SELECT 8, 'Preet', 'Shah' WHERE NOT EXISTS (SELECT 1 FROM student_details WHERE stu_firstName = 'Preet');. The second candidate has the nonmatching first name Dhruv, so this statement inserts id 9: INSERT INTO student_details (stu_id, stu_firstName, stu_lastName) SELECT 9, 'Dhruv', 'Shah' WHERE NOT EXISTS (SELECT 1 FROM student_details WHERE stu_firstName = 'Dhruv');. Both statements use the same first-name duplicate rule. These are SQL examples for a MySQL session; they are not executed by the Python illustration below.

Run this example:

students = [
    {"id": 1, "first_name": "Preet", "last_name": "Sanghavi"},
    {"id": 2, "first_name": "Rich", "last_name": "John"},
]

candidates = [
    {"id": 8, "first_name": "Preet", "last_name": "Shah"},
    {"id": 9, "first_name": "Dhruv", "last_name": "Shah"},
]

for candidate in candidates:
    match = any(
        student["first_name"] == candidate["first_name"]
        for student in students
    )
    if not match:
        students.append(candidate)

for student in students:
    print(student["id"], student["first_name"], student["last_name"])
1 Preet Sanghavi
2 Rich John
9 Dhruv Shah

This small program uses the same first-name comparison for both candidates: Preet is already present, while Dhruv is added. Change the comparison to the columns that define a duplicate in your own data. The Python list is only an illustration; it does not provide MySQL transaction or constraint behavior.

Verify the Insert and Skip Results

Run SELECT stu_id, stu_firstName, stu_lastName FROM student_details ORDER BY stu_id; after both SQL statements. Starting with the two seeded rows, the query returns (1, 'Preet', 'Sanghavi'), (2, 'Rich', 'John'), and (9, 'Dhruv', 'Shah'): id 8 is absent because Preet matched, and id 9 is present because Dhruv did not. The query targets the same student_details table as the setup and inserts.

The SQL outcomes above follow from the shown statements and sample data. The Python program separately models the same decision in a list; its printed rows illustrate the rule, but the program does not connect to MySQL or verify database state.

Enforce Uniqueness with a UNIQUE Constraint

A prior NOT EXISTS check alone does not guarantee uniqueness when multiple clients insert at the same time. Two statements can each check before either new row is visible, then both attempt to insert matching data. Add a UNIQUE constraint to the database column or column combination that defines the real duplicate rule. The constraint is the database enforcement; the conditional check can still avoid unnecessary insert attempts in ordinary use.

Choose a constraint that matches the intended identity. For instance, if a student number is the unique identifier, constrain that number rather than a first name. Handle a uniqueness conflict in the application according to its needs. This keeps the check, the database rule, and the reader’s definition of a duplicate aligned.