Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL query rows with least null value on columns

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

like image 360
gdmplt Avatar asked Jul 15 '26 08:07

gdmplt


1 Answers

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
like image 57
dani herrera Avatar answered Jul 17 '26 21:07

dani herrera