SQL Server NOT Condition (Operator)

The SQL Server NOT condition or NOT operator is used to negate a condition in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax:

NOT condition   

Parameter explanation

condition: It specifies the condition that you want to negate.

NOT Operator with IN condition

We have a table “Employees”, having the following data:

SQL Not condition 1

Example

Retrieve all employees from the table where the following “NOT” condition is satisfied:

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE name NOT IN ('Mahesh', 'Mohan', 'Chitra');

Output:

SQL Not condition 2

NOT Operator with IS NULL condition

Retrieve all employees from the table “Employees” which follows the IS NOT NULL condition:

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE name IS NOT NULL;

Output:

SQL Not condition 3

NOT Operator with LIKE condition

Retrieve all employees from the table “Employees” which follows the NOT LIKE condition. It will display only names which don?t start with “M”.

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE name NOT LIKE 'M%';

Output:

SQL Not condition 4

NOT Operator with BETWEEN condition

Retrieve all employees from the table “Employees”, which follows the following condition. It will not show the employees between the id 8 to 13.

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE id NOT BETWEEN 8 AND 13;

Output:

SQL Not condition 5

Or:

SELECT *  

FROM [javatpoint].[dbo].[Employees]  

WHERE id < 8  

OR id > 13;

Output:

SQL Not condition 6

NOT Operator with EXISTS condition

You can also combine SQL Server NOT condition with the EXISTS condition.

OR condition:

    SELECT *  
    
    FROM [javatpoint].[dbo].[Employees]  
    
    WHERE NOT EXISTS (SELECT *  
    
                      FROM [javatpoint].[dbo].[Employee2]  
    
                      WHERE Employees.name = Employee2.name  
    
                      OR Employees.salary = Employee2.salary);

    Output:

    SQL Not condition 7

    AND Condition:

    SELECT *  
    
    FROM [javatpoint].[dbo].[Employees]  
    
    WHERE NOT EXISTS (SELECT *  
    
                      FROM [javatpoint].[dbo].[Employee2]  
    
                      WHERE Employees.name = Employee2.name  
    
                      AND Employees.salary = Employee2.salary);

    Output:

    SQL Not condition 8

    This SQL Server NOT example would return all records from the Employees table where there are no records in the Employee2 table for the matching name and salary.


    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *