Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL counting presence of value (is not null)

Tags:

sql

mysql

I have a table like this:

id  | module_id | answered 
 1       4           3
 2       4           1
 3       4          NULL
 4       5          NULL 
 5       5           1

I need to calculate the number of the rows for each module_id and the number of rows where answered isn't NULL.

so I need the result

module_id  | row_count  |  answered
    4            3            2
    5            2            1

So far I have

SELECT module_id, COUNT(*) as row_count FROM table GROUP BY module_id

but I have no idea how to do the answered column. Any ideas?

like image 478
user1063998 Avatar asked Oct 03 '22 00:10

user1063998


1 Answers

 COUNT(answered)

will count the non-null values in that particular column.

That's why COUNT(*) is a lot faster than COUNT(some-column).

like image 181
O. Jones Avatar answered Oct 12 '22 08:10

O. Jones