Home >Database >Mysql Tutorial >How to Select Non-Matching Rows Between Two SQL Tables?
Non-Matching Rows in SQL Tables: Selecting Disjoint Data
In database management, it is often necessary to retrieve records from one table that do not exist in another. This is referred to as selecting non-matching rows. Consider the scenario where you have two tables, Table1 and Table2, each containing records with FirstName, LastName, and BirthDate columns.
Problem: Identify and display the rows in Table1 that are not present in Table2.
Solution:
The subquery can be structured to select rows from Table1 based on a specific column where the matching row does not exist in Table2.
Modified Query:
SELECT * FROM Table1 WHERE FirstName NOT IN (SELECT FirstName FROM Table2)
In this modified query, we specify the FirstName column for comparison because it is a unique identifier for rows in both tables. The NOT IN clause ensures that only rows from Table1 with FirstName values that do not exist in Table2 are selected.
This query will return all the rows from Table1 that are not in Table2, providing a list of unique records. It should produce the output:
+-----------+----------+------------+ | FirstName | LastName | BirthDate | +-----------+----------+------------+ | Yamila | Diaz | 1972-03-04 | +-----------+----------+------------+
This solution utilizes subquery logic to perform the comparison and effectively select the disjoint records between the two tables.
The above is the detailed content of How to Select Non-Matching Rows Between Two SQL Tables?. For more information, please follow other related articles on the PHP Chinese website!