Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: insert where not exists

Tags:

sql

mysql

I'm trying to insert new user if not exist in users table, I tried this query but receive error:

INSERT INTO USER (name,email)
VALUES ('John','[email protected]')
WHERE NOT EXISTS
    (SELECT id FROM USER WHERE email = '[email protected]')

how to insert user if not exists ?

error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where not exists (select id from user where email = '[email protected]')' at line 5

thanks,

like image 707
mwafi Avatar asked Dec 01 '22 01:12

mwafi


2 Answers

Use insert . . . select:

INSERT INTO USER (name, email)
    SELECT 'John', '[email protected]'
    WHERE NOT EXISTS
        (SELECT id FROM USER WHERE email = '[email protected]');

I would write this as:

INSERT INTO USER (name, email)
    SELECT name, email
    FROM (SELECT 'John' as name, '[email protected]' as email) t
    WHERE NOT EXISTS (SELECT 1 FROM USER u WHERE u.email = t.email);

But a better approach is probably to just put in a unique index so the database protects the data:

create unique index idx_users_email on user(email);
like image 180
Gordon Linoff Avatar answered Dec 06 '22 18:12

Gordon Linoff


Use INSERT ... SELECT instead of INSERT.

INSERT INTO USER (name,email)
SELECT 'John','[email protected]'
WHERE NOT EXISTS
    (SELECT id FROM USER WHERE email = '[email protected]')

You also might consider using the ON DUPLICATE KEY UPDATE syntax extension of MySQL.

like image 27
Bacon Bits Avatar answered Dec 06 '22 18:12

Bacon Bits