PostgreSQL是NULL和长度

时间:2014-03-25 02:07:13

标签: sql postgresql null string

我试图从特定列为NULL的表中获取所有记录。但我没有得到任何记录。另一方面,有许多记录,其中长度(字段)确实为0。

select count(*) from article a where length(for_interest) =0;
 count 
-------
     9
(1 row)

select count(*) from article a where for_interest is NULL ;
 count 
-------
     0
(1 row)

有关NULL的事情我没有做对吗?更多信息

select count(*) from article AS a where for_interest is NOT NULL ;
 count 
-------
    15
(1 row)

select count(*) from article ;
 count 
-------
    15
(1 row)

PostgreSQL版本是9.3.2。

添加样本数据,表格描述等(仅为此创建2个记录的新样本表)

test=# \d sample_article 
           Table "public.sample_article"
    Column    |          Type          | Modifiers 
--------------+------------------------+-----------
 id           | integer                | 
 title        | character varying(150) | 
 for_interest | character varying(512) | 

test=# select * from sample_article where length(for_interest)=0;
 id |                              title                              | for_interest 
----+-----------------------------------------------------------------+--------------
  8 | What is the Logic Behind the Most Popular Interview Questions?  | 
(1 row)

test=# select * from sample_article where for_interest IS NOT NULL;
 id |                              title                              | for_interest 
----+-----------------------------------------------------------------+--------------
  7 | Auto Expo 2014: Bike Gallery                                    | Wheels
  8 | What is the Logic Behind the Most Popular Interview Questions?  | 
(2 rows)

test=# select * from sample_article where for_interest IS NULL;
 id | title | for_interest 
----+-------+--------------
(0 rows)

1 个答案:

答案 0 :(得分:5)

Character types可以保留空字符串''一个NULL值。
空字符串的长度为0. NULL值的长度为NULL 大多数函数都会为NULL输入返回NULL

SELECT length('');   --> 0
SELECT length(NULL); --> NULL

SELECT NULL IS NULL; --> TRUE
SELECT '' IS NULL;   --> FALSE