Averages and SQL Functions

What does != mean in SQL?

Learn what != means in SQL: it checks that two values are not equal, like <>. See how NULL values behave with != and how to filter rows before averaging.

On this page
  1. The short answer
  2. Using != in a query
  3. How != treats NULL
  4. Filtering before you average

The short answer

!= means “not equal to.” WHERE score != 0 keeps every row whose score is anything other than 0. The <> operator means the same thing, and MySQL, PostgreSQL, SQL Server, and SQLite all accept both.

Using != in a query

SELECT student_id, subject, score
FROM test_results
WHERE subject != 'math';

This returns every test result except the math results. Writing subject <> 'math' returns the same rows.

How != treats NULL

A comparison with NULL does not come out as true or false. It comes out as unknown, and a WHERE clause keeps only the rows that come out true. So score != 0 drops every row where the score is NULL.

SELECT student_id, score
FROM test_results
WHERE score != 0
   OR score IS NULL;

This version keeps the NULL scores along with every non-zero score. If you want to replace NULL with a number instead of filtering it out, see how to get 0 instead of NULL in SQL, since that is a different job.

Filtering before you average

Some data uses a placeholder such as -1 to mean “no score.” Filtering that value out with != before you average keeps it from skewing the result:

SELECT student_id, AVG(score) AS avg_score
FROM test_results
WHERE score != -1
GROUP BY student_id;

Rows with a NULL score are also left out by the filter, and AVG() would skip them anyway.

Be careful with 0. If 0 is a real score, a filter like score != 0 removes it, and that changes the average.

The complete guide to averages and sql functions

How to Calculate the Average for Each Row in SQL
Read the guide

Keep exploring

Guides from other topics

All topics →