Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slick way to count NULL and non-NULL rows?

Tags:

sql

postgresql

I have been counting NULL and non-NULL columns with a subselect and some aggregate functions

CREATE TEMPORARY TABLE citizens(name text, country text,profession text,postalcode text);

INSERT INTO citizens VALUES
 ('Fred', 'USA', 'Professor', NULL),
 ('Amy', 'USA', 'Professor', NULL),
 ('Ted', 'USA', 'Professor', 90210),
 ('Barb', 'USA', 'Lawyer', 10248),
 ('Wally', 'USA', 'Lawyer', NULL),
 ('Fred', 'Canada', 'Professor', 'S0H'),
 ('Charles', 'Canada', 'Professor', 'S4L'),
 ('Nancy', 'Canada', 'Lawyer', NULL),
 ('Linda', 'Canada', 'Professor', NULL),
 ('Steph', 'France', 'Lawyer', 75008 ),
 ('Arnold', 'France', 'Lawyer', 75008 ),
 ('Penny', 'France', 'Lawyer', 75008 ),
 ('Harry', 'France', 'Lawyer', NULL);

SELECT country,
    profession,
    MAX(have_postalcode::int*num) AS num_have,
    MAX((1-have_postalcode::int)*num) AS num_not_have
FROM
    (
    SELECT country, profession,
        COUNT(*) AS num,
        (postalcode IS NOT NULL) AS have_postalcode
    FROM citizens
    GROUP BY country, profession, have_postalcode
    ) AS d
GROUP BY country, profession

with the result

USA     Professor   1   2
Canada  Lawyer      0   1
USA     Lawyer      1   1
France  Lawyer      3   1
Canada  Professor   2   1

but it seems like there ought to be a slicker way (for example it pains me that MAX is used just to grab the one nontrivial value). Does anybody have a cool idea?

like image 227
Brian B Avatar asked Oct 11 '12 16:10

Brian B


People also ask

How do you COUNT rows with NULL values?

How to Count SQL NULL values in a column? The COUNT() function is used to obtain the total number of the rows in the result set. When we use this function with the star sign it count all rows from the table regardless of NULL values.

Does COUNT () ignores NULL?

COUNT(expression) returns the number of values in expression, which is a table column name or an expression that evaluates to a column of data. COUNT(expression) does not count NULL values.

Does COUNT (*) include NULL?

The notation COUNT(*) includes NULL values in the total. The notation COUNT( column_name ) only considers rows where the column contains a non- NULL value.

How do I COUNT non NULLs in SQL?

Using SELECT COUNT(*) or SELECT COUNT(1) (which is what I prefer to use) will return the total of all records returned in the result set regardless of NULL values. Using COUNT()will count the number of non-NULL items in the specified column (NULL fields will be ignored).


1 Answers

SELECT country, profession,
        COUNT(postalcode) AS num_have
      , (COUNT(*) - COUNT(postalcode)) AS num_not_have
FROM citizens
GROUP BY country, profession;

http://sqlfiddle.com/#!1/17a9d/15

like image 159
closh Avatar answered Sep 21 '22 12:09

closh