Insert where… not exists

19 January 2015, by Baptiste Autin

Exercise of the day:

Let the TABLE stuff (name VARCHAR(200));
In MySQL dialect, what is the request that inserts the value ‘x’ in the column ‘name’, provided that a row containing that value does not already exist? (otherwise, the request must do nothing)

Reminder: INSERT INTO VALUES ... WHERE ... does not exist in MySQL.


Answer:
INSERT INTO stuff (name) SELECT 'x' FROM DUAL WHERE NOT EXISTS( SELECT 1 FROM stuff WHERE name = 'x');

Laisser une réponse

«     »