标簽
PostgreSQL , Oracle , 相容性 , ''空字元 , 隐式NULL轉換
https://github.com/digoal/blog/blob/master/201805/20180517_03.md#%E8%83%8C%E6%99%AF 背景
Oracle 對''有一些特殊的處理,預設會轉成NULL。使得''可以适合任意的資料類型。
然而對于PostgreSQL來說,沒有做這層轉換,是以''并不能輸入給任意類型。
https://github.com/digoal/blog/blob/master/201805/20180517_03.md#oracle Oracle
SQL> create table a(id int, c1 varchar2(10) default '', c2 date default '');
Table created.
SQL> insert into a (id) values(1);
1 row created.
SQL> select * from a where c1 is null;
ID C1 C2
---------- ---------- ---------
1
SQL> select * from a where c2 is null;
ID C1 C2
---------- ---------- ---------
1
然而實際上這樣查詢卻查不到結果,是不是很讓人驚訝:
SQL> select * from a where c1 = '';
no rows selected
default ''就是說預設值為NULL。
ORACLE内部把''轉換成了NULL。(不僅時間類型,字元串ORACLE也會這麼幹,是以語義上很混亂,實際上個人認為是ORACLE的一個不嚴謹的地方)
https://github.com/digoal/blog/blob/master/201805/20180517_03.md#postgresql PostgreSQL
PG不做這個轉換,是以非字元串類型,使用''都會報錯。
postgres=# select ''::timestamp;
ERROR: invalid input syntax for type timestamp: ""
LINE 1: select ''::timestamp;
^
為了相容Oracle,建議使用者改''為直接輸入NULL,語義上也通暢。
postgres=# create table a(id int, c1 varchar(10) default null, c2 timestamp(0) default null);
CREATE TABLE
postgres=# insert into a (id) values (1);
INSERT 0 1
postgres=# select * from a where c1 is null;
id | c1 | c2
----+----+----
1 | |
(1 row)
postgres=# select * from a where c2 is null;
id | c1 | c2
----+----+----
1 | |
(1 row)
postgres=# select * from a where c1 = '';
id | c1 | c2
----+----+----
(0 rows)