如何打印 postgres table 输出以便区分空字符串和 null
How to print postgres table output so it can distinguish between empty string and null
有没有办法配置 psql 或在查询时传入一些参数,为 null 和空字符串打印出不同的值?目前两者都显示为空。
例如,我有一个 table 内容如下:
adventure=# select * from account
adventure-# ;
user_id | username | password | email | created_on | last_login
---------+----------+----------+-------+----------------------------+----------------------------
1 | | | | 2020-04-07 10:30:08.836098 | 2020-04-07 10:30:08.836098
(1 row)
有了这个,我无法判断用户名是空字符串还是 null。在这种情况下,用户名是空的,但密码是空字符串。
我试过使用\x on
,但还是一样。
当然,我可以进行一些合并,但如果我需要对每一列都进行合并,那就有点太多了。
您可以使用 coalesce()
将 NULL
值替换为其他值:
select coalesce(username, '<null user>') as username,
coalesce(password, '<null password>') as password
或者,如果您想为空字符串包含第三个值,请使用 case
:
select (case when username is null then '<null user>'
when username = '' then '<empty user>'
else username
end)
当然,如果密码是 <null password>'
那么它看起来像 NULL
值。
或者,您可以将值括在引号中:
select '"' || username || '"' as username
||
运算符returnsNULL
如果值为NULL
.
在 psql
中,您可以使用配置选项 null
来实现,可以使用 \pset
进行更改
postgres=# \pset null '<null>'
Null display is "<null>".
postgres=# select null as c1, '' as c2;
c1 | c2
--------+----
<null> |
如果您想要永久使用该选项,可以将 \pset
命令放入 .psqlrc
有没有办法配置 psql 或在查询时传入一些参数,为 null 和空字符串打印出不同的值?目前两者都显示为空。
例如,我有一个 table 内容如下:
adventure=# select * from account
adventure-# ;
user_id | username | password | email | created_on | last_login
---------+----------+----------+-------+----------------------------+----------------------------
1 | | | | 2020-04-07 10:30:08.836098 | 2020-04-07 10:30:08.836098
(1 row)
有了这个,我无法判断用户名是空字符串还是 null。在这种情况下,用户名是空的,但密码是空字符串。
我试过使用\x on
,但还是一样。
当然,我可以进行一些合并,但如果我需要对每一列都进行合并,那就有点太多了。
您可以使用 coalesce()
将 NULL
值替换为其他值:
select coalesce(username, '<null user>') as username,
coalesce(password, '<null password>') as password
或者,如果您想为空字符串包含第三个值,请使用 case
:
select (case when username is null then '<null user>'
when username = '' then '<empty user>'
else username
end)
当然,如果密码是 <null password>'
那么它看起来像 NULL
值。
或者,您可以将值括在引号中:
select '"' || username || '"' as username
||
运算符returnsNULL
如果值为NULL
.
在 psql
中,您可以使用配置选项 null
来实现,可以使用 \pset
postgres=# \pset null '<null>'
Null display is "<null>".
postgres=# select null as c1, '' as c2;
c1 | c2
--------+----
<null> |
如果您想要永久使用该选项,可以将 \pset
命令放入 .psqlrc