SQL Cookbook Lesson
How to check if not equal in SQL
Learn how to check if not equal in SQL with examples and explanations from SQLPad.
Problem
You need to filter results in a SQL query by checking if a particular column's value is not equal to a specified value.
Sample Data
Consider the following Orders table:
| OrderID | CustomerID | OrderDate | Product |
|---|---|---|---|
| 1 | 3 | 2020-07-14 | Apples |
| 2 | 1 | 2020-07-15 | Bananas |
| 3 | 2 | 2020-07-16 | Grapes |
| 4 | 3 | 2020-07-17 | Oranges |
| 5 | 1 | 2020-07-18 | Apples |
MySQL Solution
Solution
SELECT *
FROM Orders
WHERE CustomerID != 1;
Explanation
This MySQL query will return all records from the Orders table where the CustomerID is not equal to 1. The != operator is used to check if two values are not equal in SQL.
PostgreSQL Solution
Solution
SELECT *
FROM Orders
WHERE CustomerID <> 1;
Explanation
This PostgreSQL query will return all records from the Orders table where the CustomerID is not equal to 1. The <> operator is used to check if two values are not equal in SQL. Although the != operator can also be used in Postgres, the <> operator is more widely supported across different SQL dialects.
In both cases, the result would be:
| OrderID | CustomerID | OrderDate | Product |
|---|---|---|---|
| 1 | 3 | 2020-07-14 | Apples |
| 3 | 2 | 2020-07-16 | Grapes |
| 4 | 3 | 2020-07-17 | Oranges |