Popular Searches
Popular Course Categories
Popular Courses

Using EXISTS and NOT EXISTS

Using EXISTS and NOT EXISTS

Subqueries and Common Table Expressions

Using EXISTS and NOT EXISTS in MySQL

Course: MySQL Training

Topic: Using EXISTS and NOT EXISTS

Course Link: MySQL Training Course

Demo Link: Register for a Course Demo


1. Introduction to EXISTS and NOT EXISTS in MySQL

EXISTS and NOT EXISTS are SQL operators used to check whether a subquery returns any rows. They are especially useful when you want to find records that have related records in another table or records that do not have related records.

EXISTS evaluates to true when its subquery returns at least one row. NOT EXISTS evaluates to true when its subquery returns no rows.

For example, suppose a company maintains two tables: departments and employees. You may want to find departments that have employees or identify departments that currently have no employees. EXISTS and NOT EXISTS can solve both problems.

These operators are commonly used with correlated subqueries, where the inner query refers to a column from the outer query.

1.1 Why Are EXISTS and NOT EXISTS Important?

  • They help check whether related records are present.
  • They are useful for finding records with matching relationships.
  • They can identify missing relationships between tables.
  • They help prevent unnecessary duplicate rows that can occur with some JOIN queries.
  • They are useful for data validation, reporting, and database auditing.
  • They can express business rules involving the presence or absence of related records.

2. Learning Objectives

After completing this topic, you should be able to:

  • Understand the meaning of EXISTS and NOT EXISTS.
  • Write EXISTS and NOT EXISTS subqueries in MySQL.
  • Understand how correlated subqueries work.
  • Find records that have matching rows in another table.
  • Find records that have no matching rows in another table.
  • Use EXISTS with WHERE conditions and multiple criteria.
  • Compare EXISTS with IN and JOIN.
  • Use EXISTS and NOT EXISTS for practical database tasks.
  • Identify common errors involving aliases, NULL values, and correlation conditions.
  • Understand performance considerations when using these operators.

3. Understanding EXISTS in MySQL

The EXISTS operator checks whether a subquery returns at least one row. If one or more rows satisfy the subquery's conditions, EXISTS evaluates to true. If the subquery returns no rows, EXISTS evaluates to false.

3.1 Basic Syntax

SELECT column_name
FROM table_name t
WHERE EXISTS (
    SELECT 1
    FROM another_table a
    WHERE a.related_column = t.related_column
);

Explanation:

  • The outer query selects records from the main table.
  • The subquery searches another table for matching records.
  • The condition connects the inner query to the current outer row.
  • EXISTS checks whether at least one matching row is found.
  • The outer query returns rows for which the EXISTS condition is true.

3.2 Why Is SELECT 1 Used?

You will often see SELECT 1 inside an EXISTS subquery. The purpose of EXISTS is to check whether a row exists, not to retrieve the actual value in the SELECT list. Therefore, selecting the constant 1 is a common convention.

The following forms are also valid for an EXISTS subquery:

WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);
WHERE EXISTS (
    SELECT *
    FROM employees e
    WHERE e.department_id = d.department_id
);

Both examples check for matching employee records. The actual selected expression does not determine whether EXISTS is true; the presence of rows does.

4. Understanding NOT EXISTS in MySQL

The NOT EXISTS operator checks whether a subquery returns no rows. If the subquery finds no matching records, NOT EXISTS evaluates to true. If the subquery finds at least one row, NOT EXISTS evaluates to false.

4.1 Basic Syntax

SELECT column_name
FROM table_name t
WHERE NOT EXISTS (
    SELECT 1
    FROM another_table a
    WHERE a.related_column = t.related_column
);

This query returns records from the outer table for which the inner query cannot find a matching row.

4.2 Typical Uses of NOT EXISTS

  • Find customers who have never placed an order.
  • Find departments that have no employees.
  • Find products that have never been sold.
  • Find students who have not enrolled in a course.
  • Find users who have not submitted a payment.
  • Identify parent records without corresponding child records.

5. Preparing Sample Tables for Practice

To understand EXISTS and NOT EXISTS, we will create tables for departments and employees. The examples will use these tables to check whether department-related employee records exist.

5.1 Create the Departments Table

CREATE TABLE departments (
    department_id INT PRIMARY KEY,
    department_name VARCHAR(100) NOT NULL,
    location VARCHAR(100)
);

5.2 Insert Department Records

INSERT INTO departments
    (department_id, department_name, location)
VALUES
    (10, 'Finance', 'Mumbai'),
    (20, 'IT', 'Pune'),
    (30, 'HR', 'Delhi'),
    (40, 'Marketing', 'Bengaluru'),
    (50, 'Research', 'Hyderabad');

5.3 Create the Employees Table

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    salary DECIMAL(10,2),
    department_id INT,
    FOREIGN KEY (department_id)
        REFERENCES departments(department_id)
);

5.4 Insert Employee Records

INSERT INTO employees
    (employee_id, employee_name, salary, department_id)
VALUES
    (1, 'Amit', 60000, 10),
    (2, 'Priya', 75000, 20),
    (3, 'Rahul', 45000, 10),
    (4, 'Sneha', 90000, 20),
    (5, 'Neha', 50000, 30),
    (6, 'Vikas', 65000, 30);

In this sample data, Finance, IT, and HR have employees. Marketing and Research do not have employees. These records will help demonstrate both EXISTS and NOT EXISTS.

6. Using EXISTS to Find Departments That Have Employees

One of the most common uses of EXISTS is checking whether a parent record has at least one related child record.

6.1 SQL Query

SELECT
    d.department_id,
    d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

6.2 Explanation

  1. The outer query reads the departments table using the alias d.
  2. The inner query searches the employees table using the alias e.
  3. The condition e.department_id = d.department_id checks whether an employee belongs to the current department.
  4. EXISTS becomes true if at least one employee matches the department.
  5. The outer query returns only departments that have matching employee records.

Expected result: Finance, IT, and HR are returned because each has at least one employee.

6.3 Important Observation

Even though Finance has two employees and IT has two employees, each department appears only once in the result. EXISTS checks whether a match is present; it does not add one output row for every matching employee.

7. Using NOT EXISTS to Find Departments Without Employees

NOT EXISTS is useful when you want to find records in one table that have no related records in another table.

7.1 SQL Query

SELECT
    d.department_id,
    d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

7.2 Explanation

  1. The outer query examines each department.
  2. The inner query searches for employees assigned to that department.
  3. If one or more employees are found, NOT EXISTS evaluates to false.
  4. If no employees are found, NOT EXISTS evaluates to true.
  5. The outer query returns only departments without employees.

Expected result: Marketing and Research are returned because neither department has an employee record in the sample data.

7.3 Business Use Case

A company may need to review departments that have been created in its database but do not yet have staff assigned to them. NOT EXISTS can identify these departments without requiring the application to run separate queries for every department.

8. Understanding Correlated Subqueries

A correlated subquery refers to a column from the outer query. Its condition depends on the current row being examined by the outer query.

In the following query, the inner query uses d.department_id from the outer query:

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

The expression d.department_id connects the inner query with the current department in the outer query. This is what makes the subquery correlated.

8.1 How a Correlated EXISTS Query Works

  1. The outer query considers a department.
  2. The inner query checks for employee rows matching that department's ID.
  3. If a matching employee exists, the department satisfies the EXISTS condition.
  4. The outer query continues evaluating the remaining departments.

This describes the logical behavior. MySQL's optimizer may transform the query and does not necessarily execute the inner query independently from scratch for every outer row.

8.2 Correlated NOT EXISTS

SELECT d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

This correlated query checks every department for the absence of a matching employee. It returns departments that have no employees.

9. Using EXISTS with Additional Conditions

EXISTS can include additional conditions inside the subquery. This allows you to check whether a particular type of related record exists, rather than checking only for any related record.

9.1 Find Departments That Have Employees Earning More Than 70000

SELECT
    d.department_id,
    d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary > 70000
);

The query returns departments with at least one employee earning more than 70000. In the sample data, IT qualifies because Priya and Sneha earn above this threshold.

9.2 Find Departments That Have Employees Earning Less Than 50000

SELECT
    d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary < 50000
);

The query returns departments that have at least one employee earning less than 50000. Rahul's salary makes Finance qualify.

9.3 Find Departments Without Any Employee Earning More Than 70000

SELECT
    d.department_id,
    d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary > 70000
);

This query returns departments for which no employee satisfies the salary condition. Notice that a department can have employees and still qualify if none of them earns more than 70000.

For the sample data, Finance, HR, Marketing, and Research qualify. IT does not qualify because it has employees earning more than 70000.

10. Using EXISTS with Multiple Conditions

You can combine conditions inside the subquery using AND and OR. The result depends on whether at least one row satisfies all the conditions required by the subquery.

10.1 Use AND

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary >= 60000
      AND e.salary <= 80000
);

This query finds departments with at least one employee earning between 60000 and 80000, including both boundaries.

10.2 Use OR

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND (
          e.salary < 50000
          OR e.salary > 80000
      )
);

This query finds departments with at least one employee earning below 50000 or above 80000.

10.3 Find Departments with Employees in a Salary Range and a Specific Location

SELECT d.department_name
FROM departments d
WHERE d.location = 'Pune'
  AND EXISTS (
      SELECT 1
      FROM employees e
      WHERE e.department_id = d.department_id
        AND e.salary >= 70000
  );

The outer query limits departments to Pune. The EXISTS subquery then checks whether each qualifying department has at least one employee earning 70000 or more.

11. Using NOT EXISTS to Identify Missing Relationships

NOT EXISTS is commonly used for anti-join logic: retrieving rows from one table that have no matching rows in another table.

11.1 Customers Who Have Never Placed an Order

Suppose an online store maintains a customers table and an orders table.

SELECT
    c.customer_id,
    c.customer_name
FROM customers c
WHERE NOT EXISTS (
    SELECT 1
    FROM orders o
    WHERE o.customer_id = c.customer_id
);

This query returns customers who have no order records.

11.2 Products That Have Never Been Sold

SELECT
    p.product_id,
    p.product_name
FROM products p
WHERE NOT EXISTS (
    SELECT 1
    FROM order_items oi
    WHERE oi.product_id = p.product_id
);

This query identifies products that do not appear in any order item. It can help a business identify products that have not generated sales.

11.3 Students Who Have Not Enrolled in Any Course

SELECT
    s.student_id,
    s.student_name
FROM students s
WHERE NOT EXISTS (
    SELECT 1
    FROM enrollments en
    WHERE en.student_id = s.student_id
);

This query returns students without enrollment records. It can be useful for identifying students who need assistance completing registration.

11.4 Employees Who Have No Assigned Department

If the employees table permits a NULL department ID or if department assignments are not enforced by a foreign key, NOT EXISTS can identify employees whose department ID does not match any department.

SELECT
    e.employee_id,
    e.employee_name,
    e.department_id
FROM employees e
WHERE NOT EXISTS (
    SELECT 1
    FROM departments d
    WHERE d.department_id = e.department_id
);

This query identifies employees for whom no matching department record exists. With the sample schema's enforced foreign key, invalid non-NULL department IDs should not be present. If an employee's department ID is NULL, the equality condition does not match a department, so that employee is also returned.

12. EXISTS vs NOT EXISTS

Feature EXISTS NOT EXISTS
Purpose Checks whether matching rows exist. Checks whether matching rows do not exist.
True when The subquery returns at least one row. The subquery returns no rows.
Typical use Find departments with employees. Find departments without employees.
Relationship pattern Positive existence check. Negative existence check or anti-join.
Output behavior Returns qualifying outer rows. Returns outer rows without matching subquery rows.
Effect of multiple matches An outer row is still returned once by the EXISTS condition. An outer row is excluded if any matching row exists.

13. EXISTS vs IN

EXISTS and IN can sometimes solve similar problems, but they express different ideas.

  • IN checks whether a value matches one of the values returned by a list or subquery.
  • EXISTS checks whether the subquery returns at least one row.
  • NOT EXISTS checks for the absence of matching rows.
  • NOT IN can produce unexpected results when the subquery contains NULL values.

13.1 Example Using IN

SELECT department_name
FROM departments
WHERE department_id IN (
    SELECT department_id
    FROM employees
);

This query returns departments whose IDs appear in the employees table.

13.2 Equivalent Existence Check

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

Both queries can return the departments that have employees. EXISTS is especially natural when the requirement is to check for a related row.

13.3 Why NOT EXISTS Can Be Safer Than NOT IN

If a NOT IN subquery returns a NULL value, comparisons can evaluate to UNKNOWN, which may prevent rows from being returned. NOT EXISTS checks for matching rows and is often easier to reason about when identifying missing relationships.

SELECT d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

14. EXISTS vs JOIN

JOIN and EXISTS can both be used to check relationships between tables, but their output behavior differs.

14.1 Using INNER JOIN

SELECT
    d.department_id,
    d.department_name
FROM departments d
INNER JOIN employees e
    ON e.department_id = d.department_id;

This query returns matching department-employee combinations. A department with multiple employees can appear multiple times.

14.2 Using EXISTS

SELECT
    d.department_id,
    d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

This query returns each qualifying department row once because the outer table is filtered by a Boolean existence condition rather than combined with every matching employee row.

Aspect JOIN EXISTS
Primary purpose Combines columns and rows from related tables. Checks whether related rows exist.
Multiple matching child rows May create multiple output rows for one parent. Does not multiply the outer row because of multiple matches.
Retrieving child columns Useful when child-table columns are required. Does not return inner-query columns directly.
Typical use case Show departments alongside employee names. Show departments that have at least one employee.

Neither method is universally faster. Choose the approach that best matches the required output and compare execution plans when performance is important.

15. EXISTS with Aggregate and Date Conditions

EXISTS can be used with more complex filtering conditions, including date ranges and numeric conditions.

15.1 Find Customers Who Have Placed an Order This Year

SELECT
    c.customer_id,
    c.customer_name
FROM customers c
WHERE EXISTS (
    SELECT 1
    FROM orders o
    WHERE o.customer_id = c.customer_id
      AND o.order_date >= '2026-01-01'
      AND o.order_date < '2027-01-01'
);

This query returns customers who have at least one order dated during the 2026 calendar year. The half-open date range includes dates from January 1, 2026, up to but not including January 1, 2027.

15.2 Find Products That Have at Least One Order Item Above a Quantity Threshold

SELECT
    p.product_id,
    p.product_name
FROM products p
WHERE EXISTS (
    SELECT 1
    FROM order_items oi
    WHERE oi.product_id = p.product_id
      AND oi.quantity >= 10
);

This query returns products that appear in at least one order item with a quantity of 10 or more.

15.3 Find Products That Have No Order Items

SELECT
    p.product_id,
    p.product_name
FROM products p
WHERE NOT EXISTS (
    SELECT 1
    FROM order_items oi
    WHERE oi.product_id = p.product_id
);

This is a useful inventory check for products that have never appeared in an order.

16. Common Mistakes and Troubleshooting

16.1 Missing the Correlation Condition

Incorrect query:

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
);

If the employees table contains at least one row, this condition is true for every department. The subquery does not check whether an employee belongs to the current department.

Correct query:

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

16.2 Using the Wrong Table Alias

When a query uses aliases, every column reference must point to the correct table or query scope. Verify aliases such as d for departments and e for employees.

16.3 Assuming EXISTS Returns the Inner Query's Data

EXISTS does not return columns from the inner query. It evaluates to a true or false condition that determines whether an outer row is included. If you need employee names or salaries in the output, use a suitable JOIN or another query structure.

16.4 Forgetting NULL Behavior

EXISTS and NOT EXISTS test whether rows satisfy the subquery conditions. If a comparison uses NULL, the condition may not match. For example, e.department_id = d.department_id does not evaluate to true when either side is NULL.

16.5 Confusing No Matching Rows with No Rows in the Table

NOT EXISTS is evaluated using the subquery conditions for each outer row. A table may contain many records while the subquery still returns no rows for a particular outer record because none satisfies the matching condition.

16.6 Expecting One Result for Every Matching Child Record

EXISTS does not multiply outer rows. If you need one result per employee, use a JOIN or query the employees table directly.

17. Performance Optimization and Best Practices

  • Use correct matching conditions: Correlate the inner and outer queries using the appropriate keys.
  • Index relationship columns: Indexes on columns such as employees.department_id may improve matching and existence checks.
  • Keep subqueries focused: Use only the conditions and tables needed to determine whether a matching row exists.
  • Use SELECT 1: It clearly communicates that the subquery is checking for existence, not retrieving displayed data.
  • Check NULL values: Pay special attention when comparing EXISTS-based logic with NOT IN.
  • Choose based on intent: Use EXISTS for presence checks and NOT EXISTS for missing-match checks.
  • Inspect execution plans: Use EXPLAIN to review how MySQL plans to execute a complex query.
  • Test with realistic data: Query performance can change substantially as tables grow.
  • Avoid unsupported assumptions: MySQL may transform an EXISTS subquery into another execution strategy, so do not assume it always runs once for each outer row.
  • Validate output: Test both matching and non-matching cases to ensure the query returns the intended records.

17.1 Example of EXPLAIN

EXPLAIN
SELECT d.department_id, d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

EXPLAIN provides information about the query execution plan, such as access methods, possible indexes, selected keys, and estimated rows when applicable.

17.2 Create an Index for Department Matching

CREATE INDEX idx_employees_department_id
ON employees(department_id);

Before creating an index, inspect existing indexes and consider the impact on inserts, updates, deletes, and storage. The optimizer may not use an index for every query, so measure performance rather than assuming an improvement.

18. Practical Project: Department and Employee Validation

In this mini-project, use EXISTS and NOT EXISTS to produce reports for a company's department management system.

Task 1: List Departments with Employees

SELECT d.department_id, d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

Task 2: List Departments Without Employees

SELECT d.department_id, d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

Task 3: Find Departments with High-Salary Employees

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary >= 75000
);

Task 4: Find Departments Without High-Salary Employees

SELECT d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary >= 75000
);

Task 5: Find Employees Whose Department Does Not Exist

SELECT e.employee_id, e.employee_name, e.department_id
FROM employees e
WHERE NOT EXISTS (
    SELECT 1
    FROM departments d
    WHERE d.department_id = e.department_id
);

This last query is useful for understanding orphaned records. In the sample schema, the foreign key should prevent invalid non-NULL department IDs, but the query is useful in databases where referential integrity is not enforced.

Project Learning Outcomes

  • Check relationships between parent and child tables.
  • Identify departments with and without employees.
  • Filter related records by salary conditions.
  • Understand correlated subqueries.
  • Use existence checks to validate data relationships.
  • Apply SQL to realistic reporting and auditing tasks.

19. Practice Exercises

Use the sample tables to complete these exercises:

  1. Find all departments that have at least one employee.
  2. Find all departments that do not have any employees.
  3. Find departments with at least one employee earning more than 80000.
  4. Find departments with no employee earning more than 80000.
  5. Find departments with an employee earning less than 50000.
  6. Find departments that do not have an employee earning less than 50000.
  7. Find employees whose department ID does not match any department.
  8. Write a query that finds customers who have never placed an order.
  9. Write a query that finds products that have never appeared in an order item.
  10. Compare an EXISTS query with an equivalent JOIN query and explain the difference in output.

19.1 Sample Solution: Exercise 1

SELECT d.department_id, d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

19.2 Sample Solution: Exercise 2

SELECT d.department_id, d.department_name
FROM departments d
WHERE NOT EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
);

19.3 Sample Solution: Exercise 3

SELECT d.department_name
FROM departments d
WHERE EXISTS (
    SELECT 1
    FROM employees e
    WHERE e.department_id = d.department_id
      AND e.salary > 80000
);

20. Interview Questions and Answers

Q1. What is EXISTS in MySQL?

EXISTS checks whether a subquery returns at least one row. It evaluates to true when a matching row exists.

Q2. What is NOT EXISTS in MySQL?

NOT EXISTS checks whether a subquery returns no rows. It evaluates to true when no matching row is found.

Q3. What is the difference between EXISTS and NOT EXISTS?

EXISTS selects outer rows with matching inner rows, while NOT EXISTS selects outer rows without matching inner rows.

Q4. Why is SELECT 1 commonly used with EXISTS?

EXISTS checks for the presence of rows rather than the values selected by the inner query. SELECT 1 is a simple convention that communicates this intention.

Q5. What is a correlated subquery?

A correlated subquery references one or more columns from the outer query, so its condition depends on the current outer row.

Q6. Can EXISTS return duplicate outer rows?

EXISTS itself does not multiply an outer row because of multiple matching inner rows. Each qualifying row from the outer query is returned according to the outer query's own row set.

Q7. Can EXISTS be used with additional conditions?

Yes. Conditions involving salaries, dates, statuses, categories, and other columns can be added inside the subquery.

Q8. How does NOT EXISTS help find missing records?

It returns outer rows for which no related row satisfies the subquery conditions, such as customers who have never placed an order.

Q9. What is the difference between EXISTS and IN?

IN checks whether a value belongs to a set of values. EXISTS checks whether a subquery returns at least one row. Both can solve some similar problems, but they express different logic.

Q10. Why can NOT EXISTS be preferable to NOT IN?

NOT IN can behave unexpectedly if the subquery returns NULL. NOT EXISTS checks whether a matching row is present and is often more straightforward for missing-record checks.

Q11. Is EXISTS always faster than JOIN?

No. Performance depends on the query structure, indexes, data volume, and MySQL's optimizer. Choose based on the required result and test the execution plan.

Q12. Can EXISTS be used with aggregate functions?

Yes. An EXISTS subquery can include conditions involving aggregate queries, although the best structure depends on whether the task checks for rows or evaluates a summary value.

Q13. What happens if the inner query returns several rows?

EXISTS remains true if at least one row is returned. It does not require the inner query to return only one row.

Q14. How can I optimize EXISTS queries?

Use correct correlation conditions, consider indexes on matching columns, keep the subquery focused, and inspect the execution plan with EXPLAIN.

21. Quick Revision Checklist

  • EXISTS checks whether a subquery returns at least one row.
  • NOT EXISTS checks whether a subquery returns no rows.
  • Both operators are frequently used with correlated subqueries.
  • SELECT 1 is a common expression inside EXISTS.
  • EXISTS can find parent records with related child records.
  • NOT EXISTS can find parent records without related child records.
  • Additional conditions can be placed inside the subquery.
  • EXISTS does not multiply an outer row because of multiple matching inner rows.
  • NOT EXISTS is useful for finding missing relationships.
  • NULL behavior should be considered when comparing NOT EXISTS with NOT IN.
  • Indexes can help matching conditions, but their benefit depends on the execution plan.
  • Use EXPLAIN and test with realistic data when performance matters.

22. Conclusion

EXISTS and NOT EXISTS are important MySQL operators for checking whether related records are present or absent. EXISTS is useful when you need to find records with matching relationships, while NOT EXISTS helps identify missing relationships and records without related entries.

By practicing these operators with departments, employees, customers, orders, and products, you can solve common database reporting and validation problems. Focus on writing correct correlation conditions, understanding NULL behavior, and selecting the query structure that best matches your requirement.

Continue Learning: Explore the MySQL Training Course to build your SQL and database skills.

Course Demo: Register for a Course Demo to learn more about the training program.

Official Reference: MySQL Documentation: EXISTS and NOT EXISTS Subqueries.

whatsapp