我是MySQL的新手。
我创建了一个表,其中列“col”的默认值为空。
CREATE TABLE widgets (id serial primary key, col bigint default null);
CREATE TABLE
test=# \d+ widgets;
Table "public.widgets"
Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
--------+---------+-----------+----------+-------------------------------------+---------+--------------+-------------
id | integer | | not null | nextval('widgets_id_seq'::regclass) | plain | |
col | bigint | | | | plain | |
Indexes:
"widgets_pkey" PRIMARY KEY, btree (id)
test=#
但是,在默认列中,没有任何内容可以指示它是空字段。
默认值是否应在架构输出中显示为空?
我也尝试过上面的相同示例,但是使用
default 99
。键入\d+
时默认列中不显示任何内容。在那个例子中,我插入一行,INSERT INTO widgets (id) VALUES (1);
它得到默认值99
,所以我知道正在使用默认值(至少对于整数值)。更新:默认列实际上显示99。我在自动完成中使用了\d+,但查看了错误的表。
使用
default null
,当我SELECT * FROM widgets
时,该列显示为空白。Postgres是否没有显式显示标记为“null”的值?否则,如何区分空文本字段和空值字段?
最佳答案
当没有指定任何内容时,列的默认值总是null
。显然psql
开发人员认为,将null
显示为默认值毫无意义。可能是因为这是标准行为,或者因为null
不是“值”。\d
输出中仅显示非空默认值。
如何区分空文本字段和空值字段?
空字符串''
与null
值不同,您将看到输出中的差异:
postgres=# CREATE TABLE null_test (c1 text default null, c2 text default '');
CREATE TABLE
postgres=# \d null_test
Table "public.null_test"
Column | Type | Collation | Nullable | Default
--------+------+-----------+----------+----------
c1 | text | | |
c2 | text | | | ''::text