Skip to content

MySQL - NOT Operator

The MySQL NOT is a logical operator used to negate a boolean expression. It inverts the truth value of the condition that follows it. If a condition is true, NOT condition becomes false. If a condition is false, NOT condition becomes true. It’s typically used in a WHERE clause to select rows that do not satisfy a specific criterion.

For example, if you want to find all customers who do not live in ‘California’, you can use the NOT operator to exclude that specific state from your results.

For clarity and to avoid issues with operator precedence, it’s a best practice to enclose the condition you are negating in parentheses, like WHERE NOT (condition).

The basic syntax of the NOT operator in a SELECT statement is:

SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

Let’s use a CUSTOMERS table for our examples.

CREATE TABLE CUSTOMERS(
ID INT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(100) NOT NULL,
AGE INT NOT NULL,
ADDRESS VARCHAR(100),
SALARY DECIMAL(10, 2)
);
INSERT INTO CUSTOMERS(NAME, AGE, ADDRESS, SALARY) VALUES
('Ramesh', 32, 'Ahmedabad', 2000.00),
('Khilan', 25, 'Delhi', 1500.00),
('Kaushik', 23, 'Kota', 2000.00),
('Chaitali', 25, 'Mumbai', 6500.00),
('Hardik', 27, 'Bhopal', 8500.00),
('Komal', 22, 'Hyderabad', 4500.00),
('Muffy', 24, 'Indore', 10000.00);

The following query selects all customers whose address is NOT ‘Hyderabad’.

SELECT * FROM CUSTOMERS
WHERE NOT ADDRESS = 'Hyderabad';

Using NOT with Comparison and Logical Operators

Section titled “Using NOT with Comparison and Logical Operators”

The NOT operator is very versatile and is frequently combined with other operators like IN, IS NULL, LIKE, and BETWEEN.

Use NOT IN to exclude rows that match any value in a list.

SELECT * FROM CUSTOMERS
WHERE NAME NOT IN ('Khilan', 'Chaitali', 'Muffy');

Use IS NOT NULL to find rows where a specific column has a value (i.e., is not NULL).

SELECT * FROM CUSTOMERS
WHERE ADDRESS IS NOT NULL;

Use NOT LIKE to exclude rows that match a specific string pattern.

-- Find customers whose name does not start with 'K'
SELECT * FROM CUSTOMERS
WHERE NAME NOT LIKE 'K%';

Use NOT BETWEEN to select rows that fall outside of a specified range.

SELECT * FROM CUSTOMERS
WHERE AGE NOT BETWEEN 25 AND 30;

Using NOT with DML Statements (UPDATE, DELETE)

Section titled “Using NOT with DML Statements (UPDATE, DELETE)”

The NOT operator is equally useful in UPDATE and DELETE statements to target all rows except a certain subset.

The following query updates the salary for all customers whose age is not between 25 and 30.

UPDATE CUSTOMERS
SET SALARY = SALARY * 1.10
WHERE AGE NOT BETWEEN 25 AND 30;

This query deletes all customers who are not from ‘Mumbai’ or ‘Delhi’.

DELETE FROM CUSTOMERS
WHERE ADDRESS NOT IN ('Mumbai', 'Delhi');

This is a critical and common pitfall. If the list in a NOT IN clause contains a NULL value, the entire expression will never evaluate to true. This is because a comparison with NULL (like x <> NULL) results in UNKNOWN, and NOT UNKNOWN is also UNKNOWN. The query will unexpectedly return zero rows.

-- This will ALWAYS return an empty set because of the NULL!
SELECT * FROM CUSTOMERS
WHERE ID NOT IN (1, 2, NULL);

To avoid this, always ensure the subquery or list inside a NOT IN clause does not produce NULL values, or use a NOT EXISTS subquery instead, which handles NULLs correctly.

NOT is a logical operator that negates an entire boolean expression. != (or <>) is a comparison operator that checks for inequality. While NOT col = 'val' is equivalent to col <> 'val', NOT is far more powerful as it can negate complex expressions:

WHERE NOT (AGE > 30 AND ADDRESS = 'Delhi');

Using the NOT Operator in Application Code

Section titled “Using the NOT Operator in Application Code”

When building queries in your application, you can use the NOT operator just as you would in direct SQL. As always, use prepared statements to prevent SQL injection.

PHP (PDO)
Node.js (mysql2)
Java (JDBC)
Python (mysql-connector)
Use a prepared statement to securely pass values to your query.
```php
<?php
// ... (PDO connection setup)
try {
$pdo = new PDO($dsn, $user, $pass, $options);
$sql = "SELECT * FROM CUSTOMERS WHERE ADDRESS IS NOT NULL AND AGE NOT BETWEEN ? AND ?;";
$stmt = $pdo->prepare($sql);
$stmt->execute([25, 30]);
foreach ($stmt->fetchAll() as $row) {
print_r($row);
}
} catch (\PDOException $e) { /* ... error handling ... */ }
?>

Use mysql2/promise for clean, asynchronous code.

const mysql = require('mysql2/promise');
async function getFilteredCustomers(minAge, maxAge) {
let connection;
try {
connection = await mysql.createConnection({ /* ... connection config ... */ });
const sql = 'SELECT * FROM CUSTOMERS WHERE ADDRESS IS NOT NULL AND AGE NOT BETWEEN ? AND ?;';
const [rows] = await connection.execute(sql, [minAge, maxAge]);
console.log(rows);
} catch (error) {
console.error('Query failed:', error);
} finally {
if (connection) await connection.end();
}
}
getFilteredCustomers(25, 30);

Use a PreparedStatement to safely include parameters in your WHERE clause.

import java.sql.*;
public class NotOperatorExample {
public static void main(String[] args) {
String sql = "SELECT * FROM CUSTOMERS WHERE ADDRESS IS NOT NULL AND AGE NOT BETWEEN ? AND ?;";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, 25);
stmt.setInt(2, 30);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.printf("ID: %d, Name: %s, Age: %d%n",
rs.getInt("ID"), rs.getString("NAME"), rs.getInt("AGE"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Pass parameters as a tuple to the cursor’s execute method.

import mysql.connector
config = { /* ... connection config ... */ }
def get_filtered_customers(min_age, max_age):
try:
with mysql.connector.connect(**config) as cnx:
with cnx.cursor(dictionary=True) as cursor:
query = ("SELECT * FROM CUSTOMERS "
"WHERE ADDRESS IS NOT NULL AND AGE NOT BETWEEN %s AND %s")
cursor.execute(query, (min_age, max_age))
for row in cursor.fetchall():
print(row)
except mysql.connector.Error as err:
print(err)
get_filtered_customers(25, 30)