Not Equal in MySQL

The ‘not equal’ operator is a solid way to compare data. This post covers how to use it.

Understanding not equal in MySQL

The 'not equal' operator in MySQL is represented by <> or !=. It's used in a WHERE clause to filter records where the specified column's value is not equal to a given value.

SELECT * FROM table_name WHERE column_name <> value;

Or alternatively:

SELECT * FROM table_name WHERE column_name != value;

Use cases of not equal

Filtering specific records

To exclude records with a specific value, use the 'not equal' operator in the WHERE clause.

SELECT * FROM users WHERE status <> 'inactive';

Combine it with other conditions

'Not equal' can be combined with other conditions using AND or OR.

SELECT * FROM products WHERE price <> 100 AND category = 'electronics';

Use it with NULL values

Remember, NULL values require the IS NOT NULL operator instead of 'not equal'.

SELECT * FROM employees WHERE last_name IS NOT NULL;

How it compares with other operators

Difference from equal operator

While = checks for equality, <> or != checks for inequality.

Interaction with LIKE operator

To find rows that do not match a specific pattern, combine 'not equal' with NOT LIKE.

SELECT * FROM books WHERE title NOT LIKE '%cookbook%';

Some things to be careful of

  • <> and != are functionally identical, but some databases only support one.
  • Using 'not equal' with NULL values requires special attention (see above).
  • Ensure correct data types are compared (helps you avoid unexpected results).

Example

Consider a database of a bookstore. To find all books that are not in the 'Fiction' category and cost more than $20, use:

SELECT * FROM books WHERE category != 'Fiction' AND price > 20;

Basedash

If you’re looking for a solid GUI for your MySQL database, check out Basedash. Basedash uses AI to instantly give you an admin panel on top of your SQL database, so you don’t need to waste time building custom internal tools. You can write and share SQL queries, generate charts, perform CRUD operations and more.

Invite only

We're building the next generation of data visualization.