oracle中的NULLs和空字符串(empty string)
CREATE TABLE test ( id NUMERIC ( 3, 0 ) PRIMARY KEY, content VARCHAR ( 255 ) ); INSERT INTO test (id, content) VALUES (1, NULL); INSERT INTO test (id, content) VALUES (2, ''); INSERT INTO test (id, content) VALUES (3, ' '); INSERT INTO test (id, content) VALUES (4, 'x');
這里我們顯式插入了NULL和一個空字符串、一個只有單個空格的字符串。
SELECT id,content,
CASE WHEN content IS NULL THEN 1 ELSE 0 END AS isnull,
CASE WHEN content = '' THEN 1 ELSE 0 END AS isempty,
CASE WHEN content = ' ' THEN 1 ELSE 0 END AS blank
FROM
test;
ID CONTENT ISNULL ISEMPTY BLANK
---------- ------------------------------ ---------- ---------- ----------
1 1 0 0
2 1 0 0
3 0 0 1
4 x 0 0 0
SQL>
這里可以看出,插入數據庫后,空字符串被當做NULL處理了。也就是說空字符串(empty string)在數據庫中是不能存儲的。
而只有單個空格的字符串是不會被轉成NULL的。因為它並不是空字符串(empty string)
postgresql中的NULLs和空字符串(empty string)
使用相同的表結構
postgres@=#SELECT id,content, postgres-# CASE WHEN content IS NULL THEN 1 ELSE 0 END AS isnull, postgres-# CASE WHEN content = '' THEN 1 ELSE 0 END AS isempty, postgres-# CASE WHEN content = ' ' THEN 1 ELSE 0 END AS blank postgres-# FROM postgres-# test; id | content | isnull | isempty | blank ----+---------+--------+---------+------- 1 | | 1 | 0 | 0 2 | | 0 | 1 | 0 3 | | 0 | 0 | 1 4 | x | 0 | 0 | 0 (4 rows)
插入的NULL仍然是NULL,不能和空字符串進行比較;插入的空字符串也沒有被轉化成NULL。
另一個不同是oracle和postgresql中對NULL和非空字符的連接操作
oracle中
SELECT id,content,
content || NULL AS concatnull,
content || 'x' AS concatchar
FROM
test;
ID CONTENT CONCATNULL CONCATCHAR
---------- -------------------- -------------------- --------------------
1 x
2 x
3 x
4 x x xx
oracle將NULL和一個字符連接后,將字符作為結果返回。
postgresql中
postgres@=#SELECT id,content, postgres-# content || NULL AS concatnull, postgres-# content || 'x' AS concatchar postgres-# FROM postgres-# test; id | content | concatnull | concatchar ----+---------+------------+------------ 1 | | | 2 | | | x 3 | | | x 4 | x | | xx
在pg中,NULLs和字符相連接后,NULL出現在任何一個值中都意味着結果是NULL作為輸出值,而不管它連接的是什么。
