Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return my records grouped by NULL and NOT NULL?

Tags:

sql

null

group-by

I have a table that has a processed_timestamp column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null.

I want to write a query that returns two rows:

NULL        xx -- count of records with null timestamps NOT NULL    yy -- count of records with non-null timestamps 

Is that possible?

Update: The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.

like image 469
Stewart Johnson Avatar asked Oct 27 '08 10:10

Stewart Johnson


People also ask

Does GROUP BY group NULLs?

All rows with a NULL in the column are treated as if NULL was another value. If a grouping column contains null values, all null values are considered equal, and they are put into a single group. Show activity on this post. Group By groups all the records with NULL values.

How do you handle NULL values in GROUP BY?

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.

How do you return all records if parameter is NULL?

Inside the stored procedure, the parameter value is first tested for Null using the ISNULL function and then checked whether it is Blank (Empty). If the parameter has value then only matching records will be returned, while if the parameter is Null or Blank (Empty) then all records from the table will be returned.


2 Answers

In MySQL you could do something like

SELECT      IF(ISNULL(processed_timestamp), 'NULL', 'NOT NULL') as myfield,      COUNT(*)  FROM mytable  GROUP BY myfield 
like image 192
Stefan Gehrig Avatar answered Oct 12 '22 15:10

Stefan Gehrig


In T-SQL (MS SQL Server), this works:

SELECT   CASE WHEN Field IS NULL THEN 'NULL' ELSE 'NOT NULL' END FieldContent,   COUNT(*) FieldCount FROM   TheTable GROUP BY   CASE WHEN Field IS NULL THEN 'NULL' ELSE 'NOT NULL' END 
like image 40
Tomalak Avatar answered Oct 12 '22 14:10

Tomalak