SQL Standard

SQL Not Equal Operator

This article will discuss comparison operators in SQL, specifically, the NOT EQUAL operator. The NOT Equal operator in SQL allows you to select specific records that match a particular condition.  Comparison operators such as the NOT EQUAL operator are combined with the WHERE clause to select records where the specific condition is true.

SQL Not Equal Operator

In SQL, the NOT EQUAL operator uses the symbol (!=). It is used to compare two values or expressions.  For example:

10 != 10
OR
(10*10) != (100/10)

NOTE: The NOT EQUAL operator uses the (<>) symbol in some database engines. However, the results are similar.

Return Value

The NOT EQUAL operator in SQL returns a Boolean value. It will return FALSE if the left-hand expression is equal to the right-hand term. For example:

10 != 10
// RETURNS FALSE

If the left-hand expression is not equal to the right-hand term, it returns TRUE.

(10*10) != (100/10)
// RETURNS TRUE

Think of it as the negation of the EQUAL TO operator. Therefore, it returns the opposite of what the EQUAL TO operator returns.

NOTE: The NOT EQUAL operator will return 1 to represent true and 0 to represent false in some database engines. PostgreSQL, for example, will return ‘f’ for false and ‘t’ for true.

Example 1

Suppose we have a sample table as shown below:

We can use the NOT EQUAL operator to exclude all the results where the category is equal to DEV-OPS1

We can run a query as shown:

SELECT * FROM employees
WHERE category != ('DEV-OPS1');

This should remove all the rows where the category is equal to ‘DEV-OPS1’. An example output is as illustrated below:

Note that the DEV-OPS1 records are missing.

Example 2

You can also combine multiple conditions using the AND or OR operators. An example is as shown:

SELECT * FROM employees
WHERE category != ('DEV-OPS1') AND active != TRUE;

In this case, the query above will exclude all the records where the category is equal to ‘DEV-OPS1,’ and the status is TRUE.

The resulting table is as shown:

Conclusion

Via this article, you explored and learned how to use comparison operators using the NOT EQUAL operator as an example. Comparison operators allow you to optimize your database results by searching for specific conditions.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list