Last Updated: February 25, 2016
·
646
· mcloide

SQL safe way for double run

I have learned this from a friend and co-worker of mine. If you have a sql script that requires to insert rows on a table and those rows can't be duplicated, even if the table has unique on the right columns, there is a trick that you can use that will avoid sql errors if the script is ran multiple times.

insert into a_table values (uuid(), 'a', 'b', 'c', now());

If you ran that sql multiple times, it can, insert the row multiple times or throw an error if there is a unique set for rows on the table. To avoid the SQL to throw an error or insert the row multiple times you can use the following trick:

insert into a_table
select uuid(), 'a', 'b', 'c', now() from (select 1) as `tmp` where 0 = (select count(id) from a_table where a_column = 'a');

If the count of the condition is 1 or higher, the insert will fail, avoiding a double insert.

It will be a much slower insert (keep that in mind for big inserts), but it is a bit safer.