SQL NOT Operator

The SQL NOT operator is used to filter records by reversing the result of a condition. When combined with other operators, such as AND, OR, LIKE, or IN, NOT negates the specified condition. This allows you to retrieve records that do not meet a certain criterion.

In this tutorial, we will go through NOT Operator in SQL, its syntax, and how to use this operator in forming conditions in SQL statements, with well detailed examples.

Syntax of SQL NOT Operator

The basic syntax of the SQL NOT operator in a WHERE clause is as follows:

</>
Copy
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

Each part of this syntax has a specific purpose:

  • SELECT: Specifies the columns to retrieve from the table.
  • FROM: Specifies the table from which to retrieve data.
  • WHERE: Introduces the condition used to filter the data.
  • NOT: Reverses the result of the specified condition, returning only rows that do not meet it.

Step-by-Step Examples with MySQL

We’ll go through various examples demonstrating the NOT operator in MySQL. Using MySQL 8.0 with MySQL Workbench, we’ll use a sample students table with fields id, name, age, grade, and locality.

Setup for Examples: Creating the Database and Table

1. Open MySQL Workbench and create a new database:

</>
Copy
CREATE DATABASE school;

2. Select the school database:

</>
Copy
USE school;

3. Create a table named students:

</>
Copy
CREATE TABLE students (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50),
    age INT,
    grade VARCHAR(10),
    locality VARCHAR(50)
);

4. Insert some sample records to use in our examples:

</>
Copy
INSERT INTO students (name, age, grade, locality)
VALUES
('Alice', 14, '8th', 'Northside'),
('Bob', 15, '9th', 'Westend'),
('Charlie', 14, '8th', 'Northside'),
('David', 16, '10th', 'Southend'),
('Eva', 15, '9th', 'Westend');

Examples: Using NOT Operator in Queries

Now, let’s explore different scenarios of using the NOT operator with this table.