Home > Database > Mysql Tutorial > How to Delete Orphan Rows in SQL Using LEFT JOIN, EXISTS, or NOT IN Subqueries?

How to Delete Orphan Rows in SQL Using LEFT JOIN, EXISTS, or NOT IN Subqueries?

Linda Hamilton
Release: 2025-01-24 22:35:13
Original
562 people have browsed it

How to Delete Orphan Rows in SQL Using LEFT JOIN, EXISTS, or NOT IN Subqueries?

Use SQL to delete rows with no matches

When working with multiple tables in a relational database, it is sometimes necessary to identify and delete rows in one table that do not have corresponding matches in another table. This process is often called "removing orphan entries".

Consider the following scenario:

  • You have two tables, "files" and "blob", where "files.id" can be used to join with "blob.fileid".
  • Your goal is to delete all rows in the "blob" table that do not have a matching "id" value in the "files" table.

To do this, you can use various SQL methods:

Use LEFT JOIN and IS NULL

<code class="language-sql">DELETE b FROM BLOB b
LEFT JOIN FILES f ON f.id = b.fileid
WHERE f.id IS NULL</code>
Copy after login

Use EXISTS subquery

<code class="language-sql">DELETE FROM BLOB
WHERE NOT EXISTS(SELECT NULL
                    FROM FILES f
                   WHERE f.id = fileid)</code>
Copy after login

Use NOT IN subquery

<code class="language-sql">DELETE FROM BLOB
WHERE fileid NOT IN (SELECT f.id
                        FROM FILES f)</code>
Copy after login

NOTE: If possible, it is recommended to perform delete operations within a transaction so that you have the option to roll back the changes if any unexpected issues arise.

The above is the detailed content of How to Delete Orphan Rows in SQL Using LEFT JOIN, EXISTS, or NOT IN Subqueries?. 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