Delete from multiple MySQL tables

I have just spent the last half hour scratching my head over how to delete from 2 tables, joined by a unique ID. For some reason, MySQL kept spitting out: Unknown table ‘myTable’ in MULTI DELETE. Many visits to the MySQL manual still made me scratching my head (Yes, looking back on the manual makes me hit my head for not noticing the “Note” about a third of the way down the page).

The syntax

The MySQL manual says the syntax is:

  1. DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
  2.     tbl_name[.*] [, tbl_name[.*]] ...
  3.     FROM table_references
  4.     [WHERE where_condition]

What the MySQL manual really means

I’m not exactly a God at SQL—I fully acknowledge that. I do ask questions from time-to-time, so the manual should be geared towards people like me. Shouldn’t it?

I fell into the trap by giving my tables aliases in the FROM table references bit, so my SQL looked like this:

  1. DELETE  `table1`,
  2.         `table2`
  3. FROM    table1 t1,
  4.         table2 t2
  5. WHERE   t1.row1    = t2.row1

Now, you can imagine how much sense the MySQL error was giving me. I knew the 2 tables existed, so it wasn’t “unknown” in that sense. Only upon scouring the Internet did I suddenly have a hand-to-forhead moment. When defining the “DELETE” tables, if you have used aliance in the table reference section then you need to use those instead! My query should have looked like this, which it now does and works spiffingly:

  1. DELETE  t1,
  2.         t2
  3. FROM    table1 t1,
  4.         table2 t2
  5. WHERE   t1.row1    = t2.row1

I hope that saves someone some trouble.


Related articles

Top | Post a comment | Permalink

User submitted comments

1 George Swan wrote

24th June, 2008


Don’t think I have ever needed to remove rows from more than one table at the same time, but that is some weird syntax but can see why they have done it—as the manual says you might want to only search one table but not delete from it.

2 Lig wrote

25th June, 2008


As George said, it is so you can select, but not delete, from some tables. The syntax may look a little strange for first timers though from the DELETE FROM syntax.


Penny for your thoughts

Comment posting guide

Your real name will be displayed as the author of the post. Real names are preferred, both first and second names, but nicknames/alter-egos are permitted. Any comments with the author name whose primary aim is to promote their website, and/or company will be removed.

If you supply a website URI then your real name will be clickable to that site. Only one sub-directory is permitted; e.g. http://www.example.org/directory.

Accepted comment input

  • <strong>…</strong>
  • <em>…</em>
  • <blockquote>…</blockquote>
  • <tt>…</tt>
  • <a href="…">…</a>
  • <code>…</code>




Recent articles

Other topics I ramble on about