MySQL DELETE Join example
A very useful helper in your join toolbox can be a delete join. Even though it’s not a special join type but a join used within DELETE statements, it’s still worth mentioning. However, from time to time when I want to make use of delete joins on my own, I somehow managed it to forgot the syntax and have to look it up somewhere. Therefor, here is a description as well as an example.
Take care: A delete join is a very powerful weapon. And with great power comes great responsibility! I recommend to develop the delete join on a development database. At least, make sure you have a working an recent backup before trying to delete things. A delete statement that uses joins makes it easy to shot yourself in the foot. And if you do, it probably blows away your hole leg.
DELETE join syntax
When you delete data in MySQL using DELETE statements you are able to define a condition which specifies which rows should be removed. Take a look at the following database model:
In our example the table files keeps track of filenames. Now, when a user wants to delete a file we first have to delete the file itself. Afterwards we can remove the record from our database. But since it could take a little while until we’re done and don’t want our users to wait, we are simply adding a record to the table delete_queue and wait for a background process to clean up. This isn’t a far fetched scenario, especially in the web environment.
Our background process could use the following statement that uses inner join to add the WHERE condition:
DELETE f FROM files f INNER JOIN delete_queue USING (file_id)
You can add additional join clauses to your statement like in SELECT statements for example. Adding a WHERE-clause is possible as well:
DELETE f FROM files f INNER JOIN delete_queue USING (file_id) WHERE file_id > 100
For more information about MySQL joins please also see: