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 Insert If Not Exists in SQL SERVER?
Next article icon

NOT IN vs NOT EXISTS in PL/SQL

Last Updated : 05 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

PL/SQL is a Procedural Language/Structured Query Language. It allows developers to create robust, modular, and reusable code for implementing data manipulation, and transaction control in databases. Two crucial operators in PL/SQL are NOT IN and NOT EXISTS, which are often used to filter data based on specific conditions in subqueries. Understanding the differences between these two operators is essential for writing efficient queries and avoiding unexpected results.

In this article, we will understand the NOT IN vs NOT EXISTS operator along with the examples and so on.

Setting Up The Environment

Let us start by creating a sample table and inserting some values into it. For this article, we are going to create an employee table that contains information on the manager of each employee. We will later use this manager information to understand NOT IN and NOT EXISTS clauses. The following query creates the specified table and inserts some rows into it.

PL/SQL
CREATE TABLE employees (      employee_id number(10) NOT NULL,     employee_name varchar2(50) NOT NULL,     manager_id number(10) );   INSERT INTO employees (employee_id, employee_name, manager_id) SELECT 1, 'Jack', 2 FROM DUAL UNION ALL SELECT 2, 'Jill', NULL FROM DUAL UNION ALL SELECT 3, 'Jim', NULL FROM DUAL UNION ALL SELECT 4, 'Bill', 3 FROM DUAL UNION ALL SELECT 5, 'Ben', NULL FROM DUAL UNION ALL SELECT 6, 'Alex', 2 FROM DUAL UNION ALL SELECT 7, 'Andrew', 5 FROM DUAL UNION ALL SELECT 8, 'Chris', 5 FROM DUAL; SELECT * FROM employees; 

Output:

employeestable
Table

Using the NOT IN Operator

To improve our understanding of NOT IN and NOT EXISTS clauses, we will try to find out all the employees which are not managers.

Firstly, let use a simple query using NOT IN to find the desired result. The following query selects all the employees which are not managers using a subquery.

Example of NOT IN:

SELECT * FROM employees WHERE employee_id NOT IN  (     SELECT manager_id FROM employees );

However, when we run the above query it doesn't return any values. This would mean that all employees are managers which is not true as we understand by seeing the data. So something must be wrong.

If we run the inner query independently, we will find out that it returns the following data:

Query:

SELECT manager_id FROM employees;

Output:

ManagerID
Manager id

Explanation: As we can see it returns NULL values. Whenever there is NULL values in the inner query, NOT IN fails as it doesn't have the ability to compare to NULL value. Hence, it returns false for every record which results in no data being printed.

Now let's modify the NOT IN query to get the correct output. The following modified query only retrieves the manager_ids which are not NULL.

Query:

SELECT * FROM employees WHERE employee_id NOT IN  (     SELECT manager_id FROM employees      WHERE manager_id IS NOT NULL );

Output:

NOTIN
Employee which are not managers

Explanation: As We can see in the above image, the query now works fine and returns the correct employee data.

Using the NOT EXISTS Operator

Unlike NOT IN, the NOT EXISTS operator does not encounter issues with NULL values. It’s generally more efficient and easier to use when dealing with subqueries, especially if you’re working with larger datasets.

Let's fetch employee records from the "employees" table where an employee does not have any corresponding entries indicating that they are a manager of another employee.

Query:

SELECT * FROM employees e WHERE NOT EXISTS  (     SELECT 1 FROM employees m     where m.manager_id=e.employee_id );

Output:

NOTEXIST
Employee which are not managers

Explanation: As we can see from the above image, we didn't need to specially handle NULL values in the case of NOT EXISTS statement. It automatically gives NOT NULL values in the result.

Key Differences Between NOT IN and NOT EXISTS Operator

The following are some of the differences between NOT IN and NOT EXISTS:

FeatureNOT INNOT EXISTS
NULL HandlingFails if the subquery contains NULL values, potentially leading to unexpected results.Automatically handles NULL values, making it safer to use without additional conditions.
Execution EfficiencyExecutes a full table scan for each record in the main query.Uses indexes more effectively and stops processing once a match is found.
Performance with JoinsGenerally slower for large datasets, especially with multiple conditions.Faster with complex queries due to better optimization with joins and indexing.
Query InterpretationEvaluates all records returned by the subquery, which can be slower.Stops processing as soon as it finds a match, reducing workload and improving performance.
Best Use CasesWhen data does not contain NULL values, and performance is not a priority.Ideal for complex, large datasets where performance and NULL handling are critical.

Conclusion

Overall, After reading whole article both NOT IN and NOT EXISTS are used for solving subquery results in PL/SQL, they have distinct characteristics. NOT EXISTS is typically more efficient, especially for large datasets, due to its ability to terminate processing once a match is found and NOT IN can lead to unexpected results if the subquery contains NULL values We have seen in the above examples that the in NOT EXISTS we don't need to specify to contain NOT NULL value but in NOT IN we have to specify that to contain NOT NULL values.


Next Article
How to Insert If Not Exists in SQL SERVER?

D

dvsingla28
Improve
Article Tags :
  • Geeks Premier League
  • Databases
  • PL/SQL
  • Geeks Premier League 2023
  • PL/SQL Query

Similar Reads

  • NOT IN vs NOT EXISTS in SQL
    Structured Query Language (SQL) is a domain-specific language used in managing and manipulating data in a relational database. In SQL, we use these two operators i.e. NOT IN and NOT EXISTS to filter out and efficiently retrieve our data from a table. Both of these operators are negations of IN and E
    5 min read
  • NOT IN vs NOT EXISTS in PostgreSQL
    PostgreSQL is one of the most advanced general-purpose object-relational database management systems and is open-source. Being an open-source software, its source code is available under the PostgreSQL license, a liberal open-source license. Anyone with the right skills can use, modify, and distribu
    4 min read
  • IN vs EXISTS in SQL
    SQL stands for Structured Query Language. SQL is used for retrieving useful information from a large set of data and it is used for storing the data in the Database, modifying, or manipulating the data from the database. In this article, we are going to discuss IN Operator and EXISTS Operator in SQL
    5 min read
  • How to Insert Row If Not Exists in SQL
    Managing and manipulating data in SQL is essential, especially when it comes to avoiding duplicate entries in a database. Duplicate records can lead to data inconsistencies and errors that disrupt operations and analysis. The "INSERT IF NOT EXISTS" feature in SQL acts as a safeguard, ensuring that o
    6 min read
  • How to Insert If Not Exists in SQL SERVER?
    Adding Data to a table in SQL Server is a key operation. Data can be inserted into tables using many different scenarios like plain data inserted into a table without checking anything or checking if data already exists in the target table and only if the data does not exist then the new data is ins
    7 min read
  • MySQL IN vs. EXISTS
    In MySQL, We have two commonly used clauses in SQL queries that are EXISTS and IN used for querying data efficiently for high-performance applications. EXISTS and IN are the two most important clauses that are used to filter and extract data from the database. Although they both use subqueries in th
    4 min read
  • How to INSERT If Row Does Not Exist in PL/SQL
    The database management system (DBMS) stores, processes, and manipulates data in a database. All data in a database can be stored using the INSERT command or updated using the UPDATE command. These two data manipulation language (DML) commands play a key role in adding and maintaining the data. Some
    7 min read
  • PL/SQL EXISTS Operator
    The EXISTS operator in PL/SQL is a powerful tool used to check the existence of records in a subquery. Unlike traditional comparison operators that evaluate data values, EXISTS focuses on whether a set of conditions returns any rows. It is commonly used to determine the presence or absence of record
    6 min read
  • CROSS APPLY vs INNER JOIN in PL/SQL
    PL/SQL Stands for procedural language extension to SQL. In a procedure, the role of the subprogram is to perform a particular task and it is a unit module of a program. It combined to form larger programs. A subprogram can be involved by another program which is called the calling program. PL/SQL pr
    6 min read
  • PL/SQL SELECT INTO Existing Table
    PL/SQL is a programming language that is used alongside SQL for writing procedural code such as stored procedures, functions, triggers, and packages within the Oracle Database. It was developed by Oracle Corporation and is widely used in database programming. PL/SQL is a programming language that ha
    5 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