608

Here is the script to create my tables:

CREATE TABLE clients (
   client_i INT(11),
   PRIMARY KEY (client_id)
);
CREATE TABLE projects (
   project_id INT(11) UNSIGNED,
   client_id INT(11) UNSIGNED,
   PRIMARY KEY (project_id)
);
CREATE TABLE posts (
   post_id INT(11) UNSIGNED,
   project_id INT(11) UNSIGNED,
   PRIMARY KEY (post_id)
);

In my PHP code, when deleting a client, I want to delete all projects posts:

DELETE 
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;

The posts table does not have a foreign key client_id, only project_id. I want to delete the posts in projects that have the passed client_id.

This is not working right now because no posts are deleted.

5
  • 13
    I think Yehosef answer should be the accepted one, since he uses Join as you asked and that it performs better than using an IN clause as yukondude proposed... Commented Apr 22, 2014 at 19:34
  • 3
    The preferred pattern is a DELETE posts FROM posts JOIN projects ..., rather than an IN (subquery) pattern. (The answer from Yehosef gives an example of the preferred pattern.) Commented May 25, 2015 at 17:41
  • 1
    @GerardoGrignoli, it performs better for a particular engine or version of MySQL? There's no reason why the two queries should perform any differently, since AFAIK they are identical. Of course, if I had a nickel for everytime my query optimizer did something stupid.... Commented Feb 12, 2016 at 1:12
  • You can also use alias for the table name and use that.
    – biniam
    Commented Jul 4, 2016 at 15:54
  • Only fools think they can predict performance by looking at a query. A query that looks 10x more difficult to execute can be much faster. It depends a lot on the keys.
    – doug65536
    Commented Nov 25, 2021 at 20:36

14 Answers 14

1515
+50

You just need to specify that you want to delete the entries from the posts table:

DELETE posts
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id

EDIT: For more information you can see this alternative answer

15
  • 130
    It should be noted that this is the correct answer because the join forces you to use "DELETE posts FROM posts" instead of the normal "DELETE FROM posts", since the table to delete is no longer unambiguous. Thanks! Commented Apr 12, 2012 at 20:23
  • 11
    Note you cannot use the 'as' method here e.g inner join projects as p on p.project_id ...
    – zzapper
    Commented Apr 26, 2012 at 17:01
  • 17
    Actually you can use an alias for joined tables, but not for the main table (posts). "DELETE posts FROM posts INNER JOIN projects p ON p.project_id = posts.project_id"
    – Weboide
    Commented May 29, 2012 at 15:44
  • 100
    "If you declare an alias for a table, you must use the alias when referring to the table" like so DELETE d FROM posts AS d JOIN projects AS p ON ...
    – KCD
    Commented Oct 30, 2012 at 22:11
  • 15
    this is the best answer because you can even delete from both tables in one action DELETE posts , projects FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id Commented Apr 22, 2014 at 9:52
132

Since you are selecting multiple tables, The table to delete from is no longer unambiguous. You need to select:

DELETE posts FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id

In this case, table_name1 and table_name2 are the same table, so this will work:

DELETE projects FROM posts INNER JOIN [...]

You can even delete from both tables if you wanted to:

DELETE posts, projects FROM posts INNER JOIN [...]

Note that order by and limit don't work for multi-table deletes.

Also be aware that if you declare an alias for a table, you must use the alias when referring to the table:

DELETE p FROM posts as p INNER JOIN [...]

Contributions from Carpetsmoker and etc.

7
  • 5
    @Yehosef, There's a group of people who find the CAPS really glaring. I believe I'm not the only one, I've seen quite a few people going lowercase style too.
    – Pacerier
    Commented Apr 13, 2015 at 12:09
  • 2
    fair enough - I respect your right to write your answer in the style that you like ;)
    – Yehosef
    Commented Apr 13, 2015 at 14:02
  • 1
    You really don't like capitalized keywords, don't you? :D I just saw you writing <!doctype..>, when other people would write <!DOCTYPE..>^^ But your answer still helped me, so take my upvote :) Commented Apr 4, 2016 at 12:59
  • 10
    To add to the caps/no caps discussion, true, you can use whichever style you like, but in your answer, you're actually mixing styles where you find convenient - the ON is capitalized. To less-experienced developers, it may convey that it's OK to be messy and inconsistent in terms of style.
    – Shade
    Commented Jul 4, 2016 at 15:08
  • 29
    CAPS KEYWORDS are not glaring. they ARE MAKING the QUERIES READABLE ;)
    – Sachem
    Commented Nov 23, 2017 at 21:18
57

You can also use ALIAS like this it works just used it on my database! t is the table need deleting from!

DELETE t FROM posts t
INNER JOIN projects p ON t.project_id = p.project_id
AND t.client_id = p.client_id
3
  • 1
    this is useful on compound key joins to avoid repeating the table names
    – Marquez
    Commented Jun 23, 2014 at 19:25
  • 1
    "Actually you can use an alias for joined tables, but not for the main table (posts). 'DELETE posts FROM posts INNER JOIN projects p ON p.project_id = posts.project_id'" —@Weboide Commented Oct 23, 2014 at 9:54
  • 3
    Actually (quoting from dev.mysql.com/doc/refman/5.0/en/delete.html) "If you declare an alias for a table, you must use the alias when referring to the table: DELETE t1 FROM test AS t1, test2 WHERE ..." so using an alias is fine. Commented Feb 25, 2015 at 7:26
53

Or the same thing, with a slightly different (IMO friendlier) syntax:

DELETE FROM posts 
USING posts, projects 
WHERE projects.project_id = posts.project_id AND projects.client_id = :client_id;

BTW, with mysql using joins is almost always a way faster than subqueries...

3
  • What does the USING mean? Commented Mar 30, 2015 at 0:59
  • 1
    Good explanation of USING: stackoverflow.com/questions/11366006/mysql-on-vs-using
    – bigtex777
    Commented Apr 8, 2015 at 18:08
  • 14
    @bigtex777: Please note that keyword USING in SELECT statements has little to do with the same keyword in a DELETE statement. In SELECTs it specifies the list of columns to join on, while in DELETEs it's a list of all tables in a join
    – ivanhoe
    Commented Apr 16, 2015 at 1:29
30

I'm more used to the subquery solution to this, but I have not tried it in MySQL:

DELETE  FROM posts
WHERE   project_id IN (
            SELECT  project_id
            FROM    projects
            WHERE   client_id = :client_id
        );
12
  • 90
    You should really avoid using the IN keyword in SQL (even though it's usually easier to understand for beginners) and use JOIN instead (when possible), as subqueries usually make things a lot slower.
    – user276648
    Commented Oct 28, 2011 at 2:05
  • 14
    This tends to crash the DB when there are a huge number of rows returned by the sub query. It is also immensely slow.
    – Raj
    Commented Feb 23, 2012 at 15:38
  • 3
    @yukondude Indeed "IN" is a lot easier to understand than "JOIN" at 1st, and that's why people who are not really familiar with SQL will end up writing "IN" everywhere, while they could use "JOIN" which performs better (or a whooole lot better, depending on the query). I remember several years ago, almost all my SQL queries would be rewritten by someone who actually knew how to write good queries. That's why I added the comment to avoid "IN", so that people would know that if possible, they should avoid using it.
    – user276648
    Commented May 24, 2012 at 9:58
  • 12
    The very reason I came to this page is because the query I wrote with an IN statement was dog slow. Definitely avoid the accepted answer here.
    – MikeKulls
    Commented Jun 14, 2013 at 2:15
  • 7
    As old as this question is, it is important to know WHY you should use JOIN instead of IN. When that where condition runs on a row, it is going to run that query inside IN. That means, if there are 100 rows that needs to be checked against that WHERE, that subquery is going to be run 100 times. Whereas a JOIN will only run ONCE. So, as your db gets bigger and bigger, that query is going to take longer and longer to finish. @markus just because something is not critical does not mean you should write bad code. Writing it a little better will save you a lot of time and headache in the future. :)
    – RisingSun
    Commented Mar 7, 2015 at 0:29
19

Single Table Delete:

In order to delete entries from posts table:

DELETE ps 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

In order to delete entries from projects table:

DELETE pj 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

In order to delete entries from clients table:

DELETE C
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id;

Multiple Tables Delete:

In order to delete entries from multiple tables out of the joined results you need to specify the table names after DELETE as comma separated list:

Suppose you want to delete entries from all the three tables (posts,projects,clients) for a particular client :

DELETE C,pj,ps 
FROM clients C 
INNER JOIN projects pj ON C.client_id = pj.client_id
INNER JOIN posts ps ON pj.project_id = ps.project_id
WHERE C.client_id = :client_id
12

MySQL DELETE records with JOIN

You generally use INNER JOIN in the SELECT statement to select records from a table that have corresponding records in other tables. We can also use the INNER JOIN clause with the DELETE statement to delete records from a table and also the corresponding records in other tables e.g., to delete records from both T1 and T2 tables that meet a particular condition, you use the following statement:

DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition

Notice that you put table names T1 and T2 between DELETE and FROM. If you omit the T1 table, the DELETE statement only deletes records in the T2 table, and if you omit the T2 table, only records in the T1 table are deleted.

The join condition T1.key = T2.key specifies the corresponding records in the T2 table that need be deleted.

The condition in the WHERE clause specifies which records in the T1 and T2 that need to be deleted.

7

Try like below:

DELETE posts.*,projects.* 
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
0
4

Another method of deleting using a sub select that is better than using IN would be WHERE EXISTS

DELETE  FROM posts
WHERE   EXISTS ( SELECT  1 
                 FROM    projects
                 WHERE   projects.client_id = posts.client_id);

One reason to use this instead of the join is that a DELETE with JOIN forbids the use of LIMIT. If you wish to delete in blocks so as not to produce full table locks, you can add LIMIT use this DELETE WHERE EXISTS method.

4
  • 1
    Can this query be written with "aliases"? It isn't very clear from the syntax how the posts within EXISTS() is the same posts that the rows are deleted from. (IMHO anyway)
    – MattBianco
    Commented Oct 3, 2014 at 14:18
  • I hear you, but aliases aren't allowed in the table to delete from. The "posts" in the sub query has to be the full table name, which means that if you wanted to re-use that table in your sub-select From clause, you'd have to alias it there.
    – Jim Clouse
    Commented Oct 3, 2014 at 15:12
  • 1
    This works: DELETE p FROM posts p WHERE EXISTS ( SELECT 1 FROM projects WHERE projects.client_id = p.client_id);
    – MattBianco
    Commented Oct 6, 2014 at 6:40
  • In my case, exists/in() query was ~1000+ times slower. So sure, you can use limit with it, BUT, its pointless, if it takes you 1000 times longer to execute. Commented Dec 29, 2020 at 7:31
4
mysql> INSERT INTO tb1 VALUES(1,1),(2,2),(3,3),(6,60),(7,70),(8,80);

mysql> INSERT INTO tb2 VALUES(1,1),(2,2),(3,3),(4,40),(5,50),(9,90);

DELETE records FROM one table :

mysql> DELETE tb1 FROM tb1,tb2 WHERE tb1.id= tb2.id;

DELETE RECORDS FROM both tables:

mysql> DELETE tb2,tb1 FROM tb2 JOIN tb1 USING(id);
2

One solution is to use subquery

DELETE FROM posts WHERE post_id in (SELECT post_id FROM posts p
INNER JOIN projects prj ON p.project_id = prj.project_id 
INNER JOIN clients c on prj.client_id = c.client_id WHERE c.client_id = :client_id 
);

The subquery returns the ID that need to be deleted; all three tables are connected using joins and only those records are deleted that meets the filter condition (in yours case i.e. client_id in the where clause).

1

If join does not work for you you may try this solution. It is for deleting orphan records from t1 when not using foreign keys + specific where condition. I.e. it deletes records from table1, that have empty field "code" and that do not have records in table2, matching by field "name".

delete table1 from table1 t1 
    where  t1.code = '' 
    and 0=(select count(t2.name) from table2 t2 where t2.name=t1.name);
0

Try this,

DELETE posts.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
-3

-- Note that you can not use an alias over the table where you need delete

DELETE tbl_pagos_activos_usuario
FROM tbl_pagos_activos_usuario, tbl_usuarios b, tbl_facturas c
Where tbl_pagos_activos_usuario.usuario=b.cedula
and tbl_pagos_activos_usuario.cod=c.cod
and tbl_pagos_activos_usuario.rif=c.identificador
and tbl_pagos_activos_usuario.usuario=c.pay_for
and tbl_pagos_activos_usuario.nconfppto=c.nconfppto
and NOT ISNULL(tbl_pagos_activos_usuario.nconfppto)
and c.estatus=50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.