首页 > 解决方案 > 如何检查一行中的空值?

问题描述

我想要其中至少有一列具有空值的行。我尝试使用如下行表达式:

SELECT *
FROM <table>
WHERE <table> IS NULL

但它不起作用。我的查询不正确还是?

PS我使用的是13.4版

标签: postgresql

解决方案


您可以在 WHERE 子句中引用表别名。该条件where the_table is not null将返回所有列都不为空的行。

相反的(至少一列为空)可以通过否定表达式来实现:

select *
from the_table
where not (the_table is not null);

看起来有点奇怪,但它与the_table is null- 不一样,因为对表(别名)的引用指的是现有行。如果存在一行,则“整行”不能为空。

这个:

with the_table (col1, col2, col3) as (
values 
  (1,null,null),
  (null,2,null), 
  (null,3,4),
  (5,6,7)
  
) 
select *
from the_table 
where not (the_table is not null);

返回:

col1 | col2 | col3
-----+------+-----
   1 |      |     
     |    2 |     
     |    3 |    4

推荐阅读