Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I group by on a field which has NULL values?

I have a table with 2 fields

 x          y
----       ----
 1         null            
 2          5
 3          5
 4         null
 5         null
 6          10
 7          5

And my SQLite query is

select y,count(y)
from mytable
group by y

And the result is

null    0
 5      3
 10     1

It is expected to see null 3.
But the output is null 0.
what does it mean?

like image 411
Siami Avatar asked Oct 13 '12 04:10

Siami


People also ask

Can I GROUP BY NULL values?

ORDER BY and GROUP BY with NULL SQL considers the NULL values as the UNKNOWN values. Therefore, if we use ORDER By and GROUP by clause with NULL value columns, it treats them equally and sorts, group them. For example, in our customer table, we have NULLs in the MilddleName column.

Does GROUP BY ignore NULL values?

Group functions ignore the NULL values in the column. To enforce the group functions ti include the NULL value, use NVL function.

What happens if we have NULL values in grouping attributes?

If a grouping column contains null values, all null values are considered equal, and they are put into a single group.

Which group function will consider NULL value?

Answer: C. NVL is a general function used to provide alternate value to the NULL values. The functions MAX, MIN and AVG can be used as GROUP BY functions.


1 Answers

From Aggregate Functions in SQLite

The count(X) function returns a count of the number of times that X is not NULL in a group. The count(*) function (with no arguments) returns the total number of rows in the group.

So, the COUNT function does not count NULL so use COUNT(*) instead of COUNT(y).

SELECT y, COUNT(*) AS COUNT
FROM mytable
GROUP BY y

Or you can also use COUNT(x) like this one.

SELECT y, COUNT(x) AS COUNT
FROM mytable
GROUP BY y

See this SQLFiddle

like image 68
Himanshu Jansari Avatar answered Sep 28 '22 03:09

Himanshu Jansari