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 GROUP BY 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 ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL Null

Example Table

We will use the following table named employees for our examples:


    CREATE TABLE employees (
        employee_id INT PRIMARY KEY,
        employee_name VARCHAR(50),
        department VARCHAR(50),
        manager_id INT
    );

    INSERT INTO employees (employee_id, employee_name, department, manager_id) VALUES
    (1, 'Alice Johnson', 'HR', NULL),
    (2, 'Bob Smith', 'IT', 1),
    (3, 'Charlie Brown', 'Finance', NULL),
    (4, 'Diana Prince', 'IT', 2),
    (5, 'Eve Davis', 'Marketing', 3);
    

Employees Table

employee_id employee_name department manager_id
1 Alice Johnson HR NULL
2 Bob Smith IT 1
3 Charlie Brown Finance NULL
4 Diana Prince IT 2
5 Eve Davis Marketing 3

Using SQL NULL Operator

SQL NULL is used to represent missing or unknown data. The IS NULL and IS NOT NULL operators are used to test for NULL values.

Example: Find Employees with No Manager

To find employees who do not have a manager, use the following query:


    SELECT employee_name, department
    FROM employees
    WHERE manager_id IS NULL;
    

Result:

employee_name Alice Johnson
department HR
employee_name Charlie Brown
department Finance

Example: Find Employees with a Manager

To find employees who have a manager, use the following query:


    SELECT employee_name, department
    FROM employees
    WHERE manager_id IS NOT NULL;
    

Result:

employee_name Bob Smith
department IT
employee_name Diana Prince
department IT
employee_name Eve Davis
department Marketing