"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Find Disjoint Records in SQL Using ID Exclusion?

How to Find Disjoint Records in SQL Using ID Exclusion?

Posted on 2025-03-22
Browse:461

How to Find Disjoint Records in SQL Using ID Exclusion?

Finding Disjoint Records with SQL: ID Exclusion

Consider a scenario where you have two tables with primary key bindings and wish to identify the disjoint set of records. Suppose you have two tables, Table1 and Table2, with ID serving as the primary key. Your objective is to retrieve the row from Table1 whose ID is not present in Table2.

To achieve this, you can employ the following SQL query:

SELECT ID, Name 
FROM Table1 
WHERE ID NOT IN (SELECT ID FROM Table2)

This query retrieves the ID and Name from Table1 where the ID is not among the IDs present in Table2. The NOT IN operator compares the ID column of Table1 with the ID column of Table2, excluding any matching IDs.

For instance, in your provided example, where Table1 contains the ID of John (1), Peter (2), and Mary (3), and Table2 has the ID of address2 (1) and address2 (2), the query will return the row for Mary (3) because her ID is not in Table2.

By utilizing this query, you can effectively find disjoint records between tables, allowing you to identify unmatched or missing data.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3