SELECT ''::char(5) = ''::char(5) AS eq1
,''::char(5) = ' '::char(5) AS eq2
,''::char(5) = ' '::char(5) AS eq3;
eq1 | eq2 | EQ3
t | t | Ť
使用 char(n) 测试"null or empty string":
SELECT stringexpression
,stringexpression = '' AS simple_test
,(stringexpression = '') IS NOT FALSE AS test1
,(stringexpression <> '') IS NOT TRUE AS test2
,coalesce(stringexpression, '') = '' AS test_coalesce1
,coalesce(stringexpression, ' ') = ' ' AS test_coalesce2
,coalesce(stringexpression, '') = ' ' AS test_coalesce3
FROM (
VALUES
('foo'::char(5))
, ('')
, (NULL)
, (' ') -- not different from '' in char(n)
) sub(stringexpression);
foo | f | f | f | f | f | F | t | t | t | t | t | Ť | | t | t | t | t | Ť | t | t | t | t | t | Ť
用 text 测试"null or empty string"
SELECT stringexpression
,stringexpression = '' AS simple_test
,(stringexpression = '') IS NOT FALSE AS test1
,(stringexpression <> '') IS NOT TRUE AS test2
,coalesce(stringexpression, '') = '' AS test_coalesce1
,coalesce(stringexpression, ' ') = ' ' AS test_coalesce2
,coalesce(stringexpression, '') = ' ' AS test_coalesce3
FROM (
VALUES
('foo'::text)
, ('')
, (NULL)
, (' ') -- different from '' in a sane character type like text
) sub(stringexpression);
如果数据库具有大量记录,那么 null check 可能需要更多时间,您可以通过不同方式使用空检查,例如:1) where columnname is null 2) where not exists() 3) WHERE (case when columnname is null then true end)
6 回答
表达式
stringexpression = ''
产生:TRUE
..适用于''
(或任何仅包含数据类型为char(n)
的空格的字符串)NULL
.. forNULL
FALSE
..还有别的什么所以检查: "stringexpression is either NULL or empty" :
或者相反的方法(可能更容易阅读):
适用于any character type,包括过时的
char(n)
,几乎没用过 .The manual about comparison operators.
Or 使用你已经拥有的表达式,只是没有
trim()
这对于char(n)
(见下文)是没用的,或者它将包括在其他字符类型的测试中仅包含空格的字符串:但顶部的表达式更快 .
断言相反: "stringexpression is neither NULL nor empty" 甚至更简单:
关于char(n)
不要将此数据类型与varchar(n), varchar, text or "char"(带引号)等其他字符类型混淆,后者都是有用的数据类型 . 这是关于过时的数据类型,其用途非常有限:
char(n)
,简称:character(n)
. 此外,char
和character
是char(1)
/character(1)
的缩写(同样的事情) .在
char(n)
中(与其他字符串类型不同!)空字符串与仅包含空格的任何其他字符串没有区别 . 根据类型的定义,所有这些都折叠到char(n)
中的n个空格 . 从逻辑上讲,这也适用于char(n)
:和这些一样多(这对其他字符类型不起作用):
演示
转换为
char(n)
时,空字符串等于任何空格字符串:t | t | Ť
使用
char(n)
测试"null or empty string":foo | f | f | f | f | f | F
| t | t | t | t | t | Ť
| | t | t | t | t | Ť
| t | t | t | t | t | Ť
用
text
测试"null or empty string"foo | f | f | f | f | f | F
| t | t | t | t | f | F
| | t | t | t | t | F
| f | f | f | f | f | F
dbfiddle here
老SQL小提琴
有关:
要检查null和empty:
检查null,空和空格(修剪字符串)
如果可能有空的尾随空格,可能没有更好的解决方案 .
COALESCE
仅适用于像您这样的问题 .我看到人们使用的东西是
stringexpression > ''
. 这可能不是最快的,但恰好是最短的之一 .在MS SQL和PostgreSQL上尝试过它 .
我比较可空字段的优先方法是:NULLIF(nullablefield,:ParameterValue)IS NULL AND NULLIF(:ParameterValue,nullablefield)IS NULL . 这很麻烦但是普遍使用,而Coalesce在某些情况下是不可能的 .
NULLIF的第二个和反向使用是因为如果第一个参数为null,“NULLIF(nullablefield,:ParameterValue)IS NULL”将始终返回“true” .
如果数据库具有大量记录,那么
null check
可能需要更多时间,您可以通过不同方式使用空检查,例如:1)where columnname is null
2)where not exists()
3)WHERE (case when columnname is null then true end)