SQL Count empty fields

34,927

Solution 1

SELECT count(improve) + count(timeframe) + count(impact) + count(criteria) FROM data 

Solution 2

Something like this may get you going in the right direction

SELECT 
SUM(CASE WHEN improve IS NULL THEN 0 ELSE 1 END +
CASE WHEN timeframe IS NULL THEN  0 ELSE 1 END +
CASE WHEN criteria IS NULL THEN  0 ELSE 1 END +
CASE WHEN impact IS NULL THEN  0 ELSE 1 END)
from
data 
Share:
34,927
Tom
Author by

Tom

Updated on November 19, 2020

Comments

  • Tom
    Tom over 3 years

    I'm not sure if this is possible or if it is, how to do it -

    I have the following data in a database -

    id     |    improve |   timeframe |  criteria |  impact
    -------+------------+-------------+-----------+--------- 
    1      |            |    Test     |   Test    |    Test
    2      |    Test    |             |   Test    |   
    3      |            |    Test     |           |    
    -------+------------+-------------+-----------+--------- 
    

    Ignoring the id column, how can I determine the number of fields out of the remaining 12 that are not null using an SQL query?

    I have started with -

    SELECT improve, timeframe, impact, criteria 
    FROM data 
    WHERE improve IS NOT NULL 
      AND timeframe IS NOT NULL 
      AND impact IS NOT NULL 
      AND criteria IS NOT NULL;
    

    This only returns the number of rows, ie. 3.

    Any ideas?

    Thanks.