[英]SQL Count NULL values is 0 even when there are NULL values
In a particular case I have a database table populated with 1070 items, and at some point in the process I add a column called 'Current_Status' to it. 在特定情况下,我有一个填充有1070个项目的数据库表,在过程中的某个时刻,我向其中添加了一个名为“ Current_Status”的列。 As a result, all items have a new field that is initially NULL .
结果,所有项目都有一个初始为NULL的新字段。
This table is used as a queue, and for each row that is processed, I update the 'Current_Status' field to 'Processed' or 'Non processed'. 该表用作队列,对于已处理的每一行,我将“ Current_Status”字段更新为“已处理”或“未处理”。
In order to see how is the process going, I was counting the remaining items that still had the status NULL using this query: 为了查看流程的进行情况,我使用以下查询对剩余的状态仍然为NULL的项目进行了计数:
SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL
The issue is that after the first 1000 items, the result for that query execution was 0
, even if I checked and using a SELECT * FROM Table_Name
query shown that there where still some rows with status NULL . 问题是,在前1000个项目之后,即使我检查并使用
SELECT * FROM Table_Name
查询也显示出仍有一些状态为NULL的行,但该查询执行的结果为0
。
Any ideas what might be causing this? 任何想法可能是什么原因造成的?
I checked this situation using Azure Data Studio 1.4.5. 我使用Azure Data Studio 1.4.5检查了这种情况。
The reason for that is because you have provided count with a column value which is null
. 这样做的原因是因为您为count提供了一个值为
null
的列值。 Instead, use count(*)
: 而是使用
count(*)
:
SELECT COUNT(*) FROM Table_Name WHERE [Current_Status] IS NULL
Sample data: 样本数据:
current_status
--------------
Processed
Null
Not Processed
Null
And the difference between two queries: 以及两个查询之间的区别:
count(current_status) 计数(当前状态)
SELECT count(current_status) FROM table_name WHERE current_status IS NULL
0
count(*) 计数(*)
SELECT count(*) FROM table_name WHERE current_status IS NULL
2
With 用
SELECT COUNT([Current_Status]) FROM Table_Name WHERE [Current_Status] IS NULL
you say "take all rows where the current_status
is null and count how many of these current_status
are not null". 您说“获取
current_status
为null的所有行,并计算其中有多少current_status
不为null”。 Which is zero of course. 这当然是零。
COUNT(<expression>)
counts non-null occurrences of the expression. COUNT(<expression>)
计算COUNT(<expression>)
非空出现次数。
You want to count rows instead: 您想改为计算行数:
SELECT COUNT(*) FROM table_name WHERE current_status IS NULL;
Or count remains: 或计数仍然存在:
SELECT COUNT(*) - COUNT(current_status) FROM table_name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.