Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL Count function and distinct missing NULL values

According to MSDN, the TSQL COUNT(*) function includes any NULL values in the result unless DISTINCT is also used (source: http://msdn.microsoft.com/en-us/library/ms175997.aspx)

However, in my query NULL values are being ignored. To test this, I created a small table and filled it with some data:

CREATE TABLE tbl (colA varchar(1), colB varchar(10))
INSERT tbl VALUES
('Y', 'test1'),
('Y', 'test2'),
(null, 'test3'),
(null, 'test4'),
('N', 'test5')

I then ran the following 2 queries on it:

SELECT count(*) FROM tbl
WHERE colA <> 'N'

and

SELECT DISTINCT colA FROM tbl
WHERE colA <> 'N'

Both results ignore the NULL values. I get 2 and 'Y' as the results respectively. I'm at a loss to why this is happening. Could someone please clue me in?

Results simulated in SQL Fiddle: http://sqlfiddle.com/#!3/8f00b/9

like image 480
Fahd Avatar asked Jul 28 '26 13:07

Fahd


2 Answers

Nulls are weird.

null <> 'N' evaluates to false.
null = 'N' also evaluates to false.

You need to handle null explicitly:

SELECT count(*) FROM tbl
WHERE (colA <> 'N') or (colA is null)
like image 150
Blorgbeard Avatar answered Jul 31 '26 06:07

Blorgbeard


declare @tbl as Table (colA varchar(1), colB varchar(10)) 
insert @tbl values 
  ('Y', 'test1'), ('Y', 'test2'), (null, 'test3'), (null, 'test4'), ('N', 'test5')
select * from @tbl

select
  count(*) as 'Rows', -- All rows.
  count(colA) as [colA Values], -- Rows where   colA   is not NULL.
  count(colB) as [colB Values],  -- Rows where   colB   is not NULL.
  count(distinct colA) as [Distinct colA], -- Number of distinct values in   colA .
  count(distinct colB) as [Distinct colB], -- Number of distinct values in   colB .
  -- NULL never equals anything, including another NULL.
  case when 42 = NULL then 'Yes' else 'Unknown' end as [Answer Is NULL?],
  case when NULL = NULL then 'Yes' else 'Unknown' end as [NULL = NULL],
  -- Use   is NULL   to explicitly check for   NULL .
  case when NULL is NULL then 'Yes' else 'Unknown' end as [NULL is NULL]
  from @tbl
like image 35
HABO Avatar answered Jul 31 '26 06:07

HABO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!