Home > Database > Mysql Tutorial > How to Efficiently Delete Rows from One SQL Table Based on IDs in Another?

How to Efficiently Delete Rows from One SQL Table Based on IDs in Another?

Patricia Arquette
Release: 2025-01-05 04:17:40
Original
413 people have browsed it

How to Efficiently Delete Rows from One SQL Table Based on IDs in Another?

Deleting Rows Based on Another Table

In SQL, it's not uncommon to encounter the need to delete rows from a table based on their presence in another table. Consider the following scenario:

DB Query:

I can't seem to ever remember this query!

DB Query Goal:

I want to delete all rows in Table1 whose IDs are the same as in Table2. This can be expressed as:

DELETE table1 t1
WHERE t1.ID = t2.ID
Copy after login

While the subquery approach is valid, we'll explore how to achieve this using a JOIN for improved performance:

DB Query Solution using JOIN:

DELETE t1 
FROM Table1 t1
JOIN Table2 t2 ON t1.ID = t2.ID;
Copy after login

By leveraging the JOIN, we establish a relationship between the rows in Table1 and Table2 based on their ID column. Rows in Table1 that share ID values with rows in Table2 will be identified and eligible for deletion.

Note:

  • Using aliases in the DELETE statement is recommended.
  • Prevent accidental deletions by highlighting the entire query before running it to avoid deleting the entire table instead of specific rows.

The above is the detailed content of How to Efficiently Delete Rows from One SQL Table Based on IDs in Another?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template