关于NULL
最近更新时间: 2024-06-12 15:06:00
NULL 的判断:IS NULL ,IS NOT NULL。
注意:
boolean 类型取值 true,false, NULL;
小心NOT IN 集合中带有NULL元素。
postgres=# select * from tbase; id | nickname ----+--------------- 1 | hello TDSQL PG 2 | TDSQL PG好 3 | TDSQL PG好 4 | TDSQL PG default (4 rows) postgres=# select * from tbase where id not in (null); id | nickname ----+---------- (0 rows)
建议对字符串型NULL值处理后,进行 || 操作。
postgres=# select id,nickname from tbase limit 1; id | nickname ----+------------- 1 | hello TDSQL PG (1 row) postgres=# select id,nickname||null from tbase limit 1; id | ?column? ----+---------- 1 | (1 row) postgres=# select id,nickname||coalesce(null,'') from tbase limit 1; id | ?column? ----+------------- 1 | hello TDSQL PG (1 row)
建议使用count(1) 或count(*) 来统计行数,而不建议使用count(col) 来统计行数,因为NULL值不会计入。
注意:
count(多列列名)时,多列列名必须使用括号,例如count( (col1,col2,col3) ); 注意多列的count,即使所有列都为NULL,该行也被计数,所以效果与count(*) 一致;
postgres=# select * from tbase ; id | nickname ----+--------------- 1 | hello TDSQL PG 2 | TDSQL PG好 5 | 3 | TDSQL PG好 4 | TDSQL PG default (5 rows) postgres=# select count(1) from tbase; count ------- 5 (1 row) postgres=# select count(*) from tbase; count ------- 5 (1 row) postgres=# select count(nickname) from tbase; count ------- 4 (1 row) postgres=# select count((id,nickname)) from tbase; count ------- 5 (1 row)
count(distinct col) 计算某列的非NULL不重复数量,NULL不被计数。
注意:
count(distinct (col1,col2,...) ) 计算多列的唯一值时,NULL会被计数,同时NULL与NULL会被认为是相同的;
postgres=# select count(distinct nickname)from tbase; count ------- 3 (1 row) postgres=# select count(distinct(id,nickname)) from tbase; count ------- 5 (1 row)
两个null的对比方法。
postgres=# select null is not distinct from null as TBasenull; TBasenull ----------- t (1 row)