Hot off the workshop vol. 2
MySQL conditional insert
Sometimes I need to insert some values into the database but only when a certain condition is met. The best example is a newsletter sign up. If someone has already signed up to your newsletter, don’t add his email address again. Of course we can run one query to check if this email address already exists and if not run another query to save it in our database.
If for any reason you need to do the whole operation in one query things get a little more complicated.
Lets say we want to insert some data only when field
First, select data:
SELECT `id` FROM `table` WHERE `email` = '[email protected]';
if this email address already exists in our database we can let our users know about it. If no records were returned we can continue to insert new data:
INSERT INTO `table` (`email`) VALUES ('[email protected]');
In a way we combine those two above queries into one:
INSERT INTO `table` (`email`) SELECT '[email protected]' FROM DUAL WHERE NOT EXISTS ( SELECT `id` FROM `table` WHERE `email` = '[email protected]' LIMIT 1 );
If the subquery doesn’t return any rows the insert will be carried out. In case of subquery finding this given email address, condition is not met and data doesn’t get inserted.