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:
PL/SQL INTERSECT Operator
Next article icon

PL/SQL EXISTS Operator

Last Updated : 15 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 records that satisfy specific conditions.

If a subquery returns one or more rows, the EXISTS operator evaluates to TRUE; otherwise, it returns FALSE for other conditions. In this article, we will explain the PL/SQL EXISTS operator in detail with syntax, examples, and outputs to help us understand its usage and performance benefits.

What is the PL/SQL EXISTS Operator?

The primary purpose of the EXISTS operator is to determine whether a subquery returns any rows. Rather than fetching the actual data, EXISTS simply checks whether rows meeting certain conditions are present. If at least one row is returned, EXISTS evaluates to TRUE; if no rows are returned, it evaluates to FALSE.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE EXISTS (subquery);

key terms

  • column_name(s): The columns we want to retrieve from table_name.
  • table_name: The main table from which we want to select the data.
  • subquery: The nested query that is checks for presence of the rows.

Examples of PL/SQL EXISTS Operator

Here,we will explore how to use the EXISTS operator with practical examples. By applying this operator to real-world scenarios, we can see how it helps to check for the existence of certain conditions in subqueries. Each example will demonstrate a different way to use EXISTS in querying data from a relational database.

Employees Table

We will first create an employees table with sample data. This table includes employee details such as their ID, name, salary, and manager ID. This setup allows us to simulate various scenarios, such as identifying managers or comparing employee salaries with their managers.

Query:

CREATE TABLE employees (
emp_id NUMBER(10) PRIMARY KEY, -- Unique employee ID
emp_name VARCHAR2(20), -- Employee name
manager_id NUMBER(10), -- Manager ID (references another employee)
salary NUMBER(10, 2), -- Employee salary with two decimal places
CONSTRAINT fk_manager
FOREIGN KEY (manager_id) -- Foreign key constraint for self-referencing manager ID
REFERENCES employees(emp_id) -- References the emp_id of another employee
);


-- Insert sample employees
INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (1, 'John Smith', NULL, 12000); -- Top-level manager (e.g., CEO)

INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (2, 'Alice Johnson', 1, 9000); -- Alice is managed by John

INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (3, 'Mark Williams', 1, 8500); -- Mark is also managed by John

INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (4, 'Emily Davis', 2, 6000); -- Emily is managed by Alice

INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (5, 'David Harris', 2, 6500); -- David is managed by Alice

INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (6, 'Sarah Wilson', 3, 7500); -- Sarah is managed by Mark

INSERT INTO employees (emp_id, emp_name, manager_id, salary)
VALUES (7, 'James Brown', 3, 7000); -- James is managed by Mark

-- Check the table
SELECT * FROM employees;

Output

EMP_ID

EMP_NAME

MANAGER_ID

SALARY

1

John Smith

NULL

12000

2

Alice Johnson

1

9000

3

Mark Williams

1

8500

4

Emily Davis

2

6000

5

David Harris

2

6500

6

Sarah Wilson

3

7500

7

James Brown

3

7000

Example 1: Find Employees Who Are Managers

Let us consider the above table, we want to retrieve names of the employees who are managers that means who are referenced as the manager_id by other employees in same table.

Query:

SELECT emp_name
FROM employees e1
WHERE EXISTS (SELECT 1
FROM employees e2
WHERE e2.manager_id = e1.emp_id);

Output

EMP_NAME

John Smith

Alice Johnson

Mark Williams

Explanation:

  • The main query retrieves the emp_name from the employees table (aliased as e1).
  • The subquery checks if the emp_id from e1 is referenced as a manager_id in any row of the employees table (aliased as e2).
  • The EXISTS operator evaluates to TRUE if at least one employee in e2 has the current employee from e1 as their manager.
  • The result includes John Smith, Alice Johnson, and Mark Williams, who are referenced as managers by other employees.

Example 2: Find Employees Earning More Than Their Managers:

In this example, we want to find employees who earn more than their managers using the EXISTS operator. We will query the employees table to compare each employee’s salary with their manager’s salary. If an employee's salary exceeds that of their manager, their name will be included in the result.

Query:

SELECT emp_name
FROM employees e1
WHERE EXISTS (SELECT 1
FROM employees e2
WHERE e1.manager_id = e2.emp_id
AND e1.salary > e2.salary);

Output

no rows selected

Explanation:

  • The main query selects emp_name from the employees table (e1).
  • The subquery checks if an employee's manager_id in e1 matches the emp_id of another employee in e2, meaning the employee reports to that manager.
  • It also checks if the employee's salary (e1.salary) is greater than their manager's salary (e2.salary).
  • The EXISTS operator evaluates to TRUE if an employee earns more than their manager, but since no such employees exist in this case, no rows are returned.

Conclusion

In conclusion, the EXISTS operator in the PL/SQL is the versatile and the efficient tool for performing the conditional checks based on presence of the related rows in the subqueries. If is focuses more on whether subquery returns one or more rows, without the comparing specific values.

By Using the EXISTS, we can simplify the queries and optimize the performance, especially when dealing with the large datasets or the complex relationships between the tables. Therefore, understanding and using EXISTS operator effectively can enhance our query-writing skills and overall database performance.


Next Article
PL/SQL INTERSECT Operator
author
jagan716
Improve
Article Tags :
  • Databases
  • PL/SQL

Similar Reads

  • PL/SQL IN Operator
    The PL/SQL IN operator is a powerful tool used in SQL queries to check if a value matches any value in a list or a subquery result. It simplifies querying multiple values and can make your SQL code cleaner and more readable. The IN operator is typically used in the WHERE clause to filter results bas
    6 min read
  • PostgreSQL - EXISTS Operator
    The EXISTS operator in PostgreSQL is a powerful SQL feature used to check the existence of rows in a subquery. It is particularly useful when working with correlated subqueries, where the inner query depends on values from the outer query. The EXISTS operator returns true if the subquery returns at
    4 min read
  • PL/SQL NOT Operator
    PL/SQL, an extension of SQL in Oracle, offers various operators that allow us to perform logical operations on data. One such operator is the NOT operator, which is used to negate a condition, meaning it will return true if the condition is false and vice versa. The NOT operator is commonly used in
    6 min read
  • PL/SQL INTERSECT Operator
    The PL/SQL INTERSECT operator is a powerful SQL set operation that allows us to return only the rows that are common to two or more SELECT queries. Unlike UNION or UNION ALL, which combine the results of different queries, INTERSECT focuses on finding the overlap between them. In this article, We wi
    3 min read
  • PL/SQL IS NULL Operator
    The IS NULL operator is a fundamental tool in PL/SQL used to determine the presence of NULL values in database columns. Understanding how to effectively use the IS NULL operator is crucial for database management, as it allows developers and analysts to identify and handle records with missing or un
    4 min read
  • PL/SQL Operators
    The PL/SQL language offers various operators for data manipulation and logical processing. There are several types of these operators which include arithmetic operators, relational operators, comparison operators, and logical operators. In this guide, we will learn about the various PL/SQL operators
    4 min read
  • PL/SQL AND Operator
    The PL/SQL AND operator is used to combine multiple conditions in a WHERE clause of an SQL query. It allows you to refine your query by ensuring that all specified conditions are met. AND queries which help in filtering data more precisely and can be crucial for retrieving accurate results from a da
    7 min read
  • PL/SQL NOT EQUAL Operator
    In PL/SQL, the NOT EQUAL operator is used to compare two values and determine if they are not equal. If the values are different, the result of the comparison is true; otherwise, it is false. This operator is often used in conditional statements and queries to filter data based on inequality. In thi
    6 min read
  • SQL IN Operator
    The SQL IN operator filters data based on a list of specific values. In general, we can only use one condition in the Where clause, but the IN operator allows us to specify multiple values. In this article, we will learn about the IN operator in SQL by understanding its syntax and examples. IN Opera
    4 min read
  • SQL NOT Operator
    The SQL NOT Operator is a logical operator used to negate or reverse the result of a condition in SQL queries. It is commonly used with the WHERE clause to filter records that do not meet a specified condition, helping you exclude certain values from your results. In this article, we will learn ever
    3 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