views:

175

answers:

6

I want to know how can i find all the values that are NULL in the MySQL database for example I'm trying to display all the users who don't have an average yet.

Here is the MySQL code.

SELECT COUNT(average) as num
FROM users
WHERE user_id = '$user_id'
AND average IS_NULL
A: 

SELECT COUNT(average) as num FROM users WHERE user_id = '$user_id' AND average IS NULL

BojanG
`COUNT(NULL)` is always 0 (average IS NULL, so COUNT(average) == 0). It should be `count(*)` or `count(1)`
a1ex07
+3  A: 
SELECT
    COUNT(*) as num
FROM
    users
WHERE
    user_id = '$user_id' AND
    average IS NULL
Hammerite
+1  A: 

I may be missing something mysql specific but this would work in sql server

SELECT COUNT(*) as num
FROM users
WHERE user_id = '$user_id'
AND average IS NULL
BioBuckyBall
+1  A: 

Also, you can:

Select Count(*) - Count(Average) as NullAverages
From Users
Where user_id = '$user_id' 
Charles Bretana
I don't think that works in MySql
dplass
+1  A: 

you're on the right track. Remove '_' from 'IS_NULL' and change 'COUNT(average)' to 'COUNT(1)' and you will have it.

For more information on working with NULL in MYSQL see http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

And for working with IS NULL specifically see

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_is-null

Jacob
A: 

A more generic version (that doesn't depend on the where clause and hence limits your overall results):

SELECT 
    SUM(CASE WHEN average IS NULL THEN 1 ELSE 0 END) As null_num, 
    SUM(CASE WHEN average IS NOT NULL THEN 1 ELSE 0 END) AS not_null_num
FROM users

It's not better then the specific queries presented by other answers here, but it can be used in situations where using a limiting where clause is impractical (due to other information being needed)...

ircmaxell