Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to eliminate NULLs in SELECT DISTINCT?

Tags:

sql

sql-server

I am working on a query that is fairly similar the following:

CREATE TABLE #test (a char(1), b char(1))  INSERT INTO #test(a,b) VALUES  ('A',NULL), ('A','B'), ('B',NULL), ('B',NULL)  SELECT DISTINCT a,b FROM #test  DROP TABLE #test 

The result is, unsurprisingly,

a   b ------- A   NULL A   B B   NULL 

The output I would like to see in actuality is:

a   b ------- A   B B   NULL 

That is, if a column has a value in some records but not in others, I want to throw out the row with NULL for that column. However, if a column has a NULL value for all records, I want to preserve that NULL.

What's the simplest/most elegant way to do this in a single query?

I have a feeling that this would be simple if I weren't exhausted on a Friday afternoon.

like image 288
Jim Burnell Avatar asked Apr 20 '12 22:04

Jim Burnell


People also ask

Does distinct get rid of NULLs?

In SQL, the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL statement, your result set will include NULL as a distinct value.

How do I omit NULLs in SQL?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

How does count distinct handle NULLs?

If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL. If every column value is NULL, the COUNT DISTINCT function returns zero (0).


2 Answers

Try this:

select distinct * from test where b is not null or a in (   select a from test   group by a   having max(b) is null) 

You can get the fiddle here.

Note if you can only have one non-null value in b, this can be simplified to:

select a, max(b) from test group by a 
like image 127
Mosty Mostacho Avatar answered Oct 11 '22 10:10

Mosty Mostacho


;WITH CTE     AS     (     SELECT DISTINCT * FROM #test     )     SELECT a,b     FROM CTE             ORDER BY CASE WHEN b IS NULL THEN 9999 ELSE b END ;  
like image 28
Karthika D Avatar answered Oct 11 '22 12:10

Karthika D