【发布时间】:2016-04-01 04:03:34
【问题描述】:
在正常情况下,将NULL 值与任何其他值进行比较会产生另一个NULL 值。
SELECT NULL = NULL;
返回NULL
如the documentation, 9.23.5. Row Constructor Comparison 中所述,比较任意行时,这(大部分)成立:
SELECT ROW(1, NULL, 'baz text') = ROW(1, NULL, 'baz text');
返回NULL
但是,在比较定义明确的复合类型时,NULL 值被视为相等。
CREATE TYPE test_type AS (
foo INTEGER,
bar BIGINT,
baz TEXT
);
SELECT (1, NULL, 'baz text')::test_type = (1, NULL, 'baz text')::test_type;
返回TRUE
这种行为似乎没有记录(我已经查看并发现没有提及该行为)。
我想使用这种行为来实现一些业务规则,并希望确保这样做是安全的。
- 这是否符合任何 SQL 规范?
- 有可能这会在未来发生变化吗?
【问题讨论】:
-
为了获得稳定的结果,您始终可以使用:
SELECT ROW(1, NULL, 'baz text') IS NOT DISTINCT FROM ROW(1, NULL, 'baz text'); -
@lad2025 - 我熟悉
IS NOT DISTINCT FROM子句;但是,我对与复合类型一起使用时的=运算符感兴趣。 -
这很有趣,我猜它比较的是字符串表示Demo。所以
{ "type": "test_type", "value": "(,,)" }={ "type": "test_type", "value": "(,,)" }=> 是的 -
@lad2025 - 哇...你的第二个测试
(NULL,NULL, NULL)::test_type IS NULL返回TRUE- 我发现SELECT ARRAY[NULL] IS NULL更有趣返回FALSE(与这个问题无关,只是有趣)。 -
这在doc
If the expression is row-valued, then IS NULL is true when the row expression itself is null or when all the row's fields are null, while IS NOT NULL is true when the row expression itself is non-null and all the row's fields are non-null.中有描述