SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL EXISTS Tutorial

Example Tables

We will use the following tables named employees and departments for our examples:


    CREATE TABLE departments (
        department_id INT PRIMARY KEY,
        department_name VARCHAR(50)
    );

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

    INSERT INTO departments (department_id, department_name) VALUES
    (1, 'HR'),
    (2, 'Finance'),
    (3, 'IT');

    INSERT INTO employees (employee_id, employee_name, department_id, salary) VALUES
    (1, 'John Doe', 1, 50000.00),
    (2, 'Jane Smith', 2, 60000.00),
    (3, 'Sam Brown', 3, 70000.00),
    (4, 'Nancy White', 1, 55000.00),
    (5, 'Mike Green', 2, 65000.00);
    

Departments Table

department_id department_name
1 HR
2 Finance
3 IT

Employees Table

employee_id employee_name department_id salary
1 John Doe 1 50000.00
2 Jane Smith 2 60000.00
3 Sam Brown 3 70000.00
4 Nancy White 1 55000.00
5 Mike Green 2 65000.00

Using SQL EXISTS

The SQL EXISTS operator is used to test for the existence of any record in a subquery. It returns TRUE if the subquery returns one or more records.

Example 1: Check if a Department has Employees

To check if a department has any employees, use the following query:


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

Result:

department_name HR
Finance
IT

Example 2: Check if a Department has No Employees

To check if a department has no employees, use the following query:


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

Result:

department_name (No results, as all departments have employees)