Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
How to Find Records From One Table Which Don't Exist in Another SQLite?
Next article icon

How to Select All Records from One Table That Do Not Exist in Another Table in SQL?

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with SQL databases, a common requirement is to find records from one table that do not exist in another table. This can be achieved using various SQL techniques like LEFT JOIN, NOT IN, or NOT EXISTS. In this detailed guide, we will explain how to accomplish this using SQL queries and Laravel's query builder. The article will also include examples, outputs, and optimized queries for improved database performance.

Why Find Records That Don’t Exist in Another Table?

  • Finding records that don’t exist in another table is a critical operation in data analysis and reporting. It helps identify gaps and discrepancies in datasets, ensuring accurate insights and maintaining data integrity.
  • Common use cases include detecting unprocessed orders by comparing an orders table with a processed_orders table, identifying inactive users by analyzing differences between users and active_users tables, or validating relationships between related tables to ensure consistent and reliable data.
  • This operation is essential for maintaining efficient workflows and ensuring robust database management.

SQL Query to Find Records in One Table But Not in Another

When managing relational databases, it is often necessary to identify records that exist in one table but not in another. This guide demonstrates how to achieve this with practical examples, including table creation, data insertion, and queries to fetch unmatched records.

1. Creating Tables

Consider two tables, employee_details and resigned_employees:

CREATE TABLE employee_details(
emp_id VARCHAR(8),
emp_name VARCHAR(20),
emp_designation VARCHAR(20),
emp_age INT);
CREATE TABLE employee_resigned(
emp_id VARCHAR(8),
emp_name VARCHAR(20),
emp_designation VARCHAR(20),
emp_age INT);

2. Inserting data into the Table 

Next, insert records into the employee_details and employee_resigned tables using the following queries.

INSERT INTO employee_details VALUES
('E40001','PRADEEP','H.R',36),
('E40002','ASHOK','MANAGER',28),
('E40003','PAVAN KUMAR','ASST MANAGER',28),
('E40004','SANTHOSH','STORE MANAGER',25),
('E40005','THAMAN','GENERAL MANAGER',26),
('E40006','HARSH',' ANALYST',25),
('E40007','SAMHITH','GENERAL MANAGER',26),
('E40008','SAMEER','SENIOR ANALYST',25),
('E40009','RISABH','BUSINESS ANALYST',26);
INSERT INTO employee_resigned VALUES('E40001','PRADEEP','H.R',36),
('E40004','SANTHOSH','STORE MANAGER',25),
('E40005','THAMAN','GENERAL MANAGER',26);

3. Verifying the inserted data :

To confirm that the data has been inserted correctly, use the following queries:

View Data in employee_details:

SELECT* FROM employee_details;

Output

employee_details
employee_details

View Data in employee_resigned:

SELECT* FROM employee_resigned;

Output

employee_resigned
employee_resigned

Method 1: Using LEFT JOIN with WHERE NULL

The LEFT JOIN technique is one of the most effective ways to find unmatched records between two tables. It retrieves all records from the left table and only matching records from the right table. The WHERE NULL condition then filters out the rows where no match exists in the right table, leaving only unmatched records.

Query:

SELECT e.* 
FROM employee_details e
LEFT JOIN employee_resigned r
ON e.emp_id = r.emp_id
WHERE r.emp_id IS NULL;

Output

emp_idemp_nameemp_designationemp_age
E40002ASHOKMANAGER28
E40003PAVAN KUMARASST MANAGER28
E40006HARSHANALYST25
E40007SAMHITHGENERAL MANAGER26
E40008SAMEERSENIOR ANALYST25
E40009RISABHBUSINESS ANALYST26

Explanation:

The output contains details of employees in employee_details who are not present in employee_resigned. These are the employees who have not resigned.

Method 2: Using NOT EXISTS

The NOT EXISTS clause is a highly efficient method for finding unmatched records, especially when working with large datasets. It checks for the absence of a matching row in the subquery and returns records from the main query that do not satisfy the condition in the subquery.

Query:

SELECT emp_id,emp_name  
FROM employee_details
WHERE NOT EXISTS
(SELECT *
FROM employee_resigned
WHERE employee_details.emp_id = employee_resigned.emp_id);

Output

emp_idemp_name
E40002ASHOK
E40003PAVAN KUMAR
E40006HARSH
E40007SAMHITH
E40008SAMEER
E40009RISABH

Explanation:

The output lists the employee IDs and names of employees who have not resigned. This method efficiently identifies active employees by excluding those found in the employee_resigned table.

Method 3: Using NOT IN

The NOT IN clause is a straightforward way to find unmatched records by filtering rows from one table based on the absence of corresponding values in another table. It is particularly simple to use when dealing with small or moderately sized datasets.

Query:

SELECT *
FROM employee_details
WHERE emp_id NOT IN
(SELECT emp_id
FROM employee_resigned)

Output

emp_idemp_nameemp_designationemp_age
E40002ASHOKMANAGER28
E40003PAVAN KUMARASST MANAGER28
E40006HARSHANALYST25
E40007SAMHITHGENERAL MANAGER26
E40008SAMEERSENIOR ANALYST25
E40009RISABHBUSINESS ANALYST26

Explanation:

The output includes the complete details of employees who have not resigned, such as their ID, name, designation, and age. By using NOT IN, we can quickly identify records that are exclusive to one table, making it a practical choice for straightforward queries.

Conclusion

Finding records in one table that do not exist in another table is a fundamental operation in SQL and Laravel. Use LEFT JOIN, NOT IN, or NOT EXISTS, depending on our specific use case and dataset size. Laravel provides convenient methods to achieve the same using Eloquent ORM or query builder. By applying the techniques and performance tips shared in this guide, we can efficiently handle unmatched records in our database.


Next Article
How to Find Records From One Table Which Don't Exist in Another SQLite?

L

lokeshpotta20
Improve
Article Tags :
  • SQL
  • Databases
  • SQL-Server
  • SQL-Query

Similar Reads

  • How to Select Rows from a Table that are Not in Another Table?
    In MySQL, the ability to select rows from one table that do not exist in another is crucial for comparing and managing data across multiple tables. This article explores the methods to perform such a selection, providing insights into the main concepts, syntax, and practical examples. Understanding
    3 min read
  • How to Find Records From One Table Which Don't Exist in Another SQLite?
    In database management, one of the most common tasks is to compare records either to identify differences or missing records in certain tables. This phase is crucial for data validation, reconciliation, and complete data integrity. On SQLite, a lightweight relational database management system, this
    4 min read
  • SQL Server - Find Records From One Table Which Don't Exist in Another
    When working with databases, it is often necessary to compare data between tables to find records that exist in one table but not in another. In SQL Server, this can be achieved using various methods. In this article, we will explore two common approaches to finding records from one table that don't
    3 min read
  • How to Find Records From One Table Which Don't Exist in Another MySQL
    MySQL is a free and open-source relational database management system written in C and C++ that is extremely popular among developers. Like other relational database management systems, MySQL provides a variety of rich features to create databases and tables, insert data in them, and further manipul
    5 min read
  • How to Select Rows that Don't Exist in Other Table in PostgreSQL?
    In PostgreSQL, there are times when we need to find records in one table that do not exist in another table. This can be useful for various data manipulation tasks and ensuring data integrity. In this article, we will explore different approaches along with examples to achieve this using PostgreSQL.
    5 min read
  • How to Select Rows with no Matching Entry in Another Table in SQLite?
    In database management, selecting rows from one table that does not have matching entries in another table means returning the rows that are present in one table but do not have the same entry in any other table. This scenario often arises in various data validation and analysis processes. In this a
    4 min read
  • How to Append Two Tables and Put the Result in a Table in SQL?
    SQL provides the UNION and UNION ALL operators to combine data from two tables into a new table. These operators are used to merge rows from multiple tables into a single result set. The UNION operator removes duplicate rows from the combined result, while UNION ALL includes all rows, including dupl
    4 min read
  • How to Copy Rows from One Table to Another in SQL?
    In SQL, copying rows from one table to another is a common operation that simplifies data migration and duplication tasks. Whether creating backup tables, transferring data for analysis, or setting up a new schema, the ability to efficiently replicate data across tables is invaluable. This operation
    3 min read
  • How to Update From One Table to Another Based on an ID Match in SQL
    In SQL, updating data between tables is a common operation used to maintain data consistency and accuracy across related datasets. Whether we need to synchronize records, update fields, or correct discrepancies, SQL provides efficient methods to achieve this. In this article, we will explain how to
    4 min read
  • SQL Query to Select all Records From Employee Table Where Name is Not Specified
    In SQL, filtering records based on specific criteria is a fundamental task when working with relational databases. One common scenario is selecting all records from a table while excluding certain values, such as specific names or designations. This article demonstrates how to use SQL queries effect
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences