3

How can I query rows where the output would be the rows with least null value on the columns?

My data is:

ID         | col1     | col2      | col3      | col4     
-----------+----------+-----------+-----------+-----------
 1         | Null     |Null       | with value| with value
 2         |with value|Null       | with value| with value
 3         |with value|Null       | Null      | Null       

where the result would be:

 ID         | col1     | col2      | col3      | col4     
 -----------+----------+-----------+-----------+-----------
  2         |with value|Null       | with value| with value  

Because id 2 is the record with fewest null values. Any help will be greatly appreciated. Thanks

gdmplt
  • 33
  • 1
  • 4

2 Answers2

3

You can:

  1. Order rows by number of nulls (ascending)
  2. Limit rows to 1 ( LIMIT 1 )

Your code:

SELECT *
FROM your_table
ORDER BY 
    CASE WHEN col1 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col2 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col3 IS NULL THEN 1 ELSE 0 END +
    CASE WHEN col4 IS NULL THEN 1 ELSE 0 END 
LIMIT 1
dani herrera
  • 48,760
  • 8
  • 117
  • 177
0

If you want only one row, then you can do:

select t.*
from t
order by ( (col1 is null)::int + (col2 is null)::int +
           (col3 is null)::int + (col4 is null)::int
         ) asc
fetch first 1 row only;

If you want all such rows, I think I would do:

select t.*
from (select t.*,
             dense_rank() over 
                 (order by (col1 is null)::int + (col2 is null)::int +
                           (col3 is null)::int + (col4 is null)::int
                 ) as null_ranking
      from t
     ) t
where null_ranking = 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786