PostgreSQL 换行符

如何在 PostgreSQL中使用 newline character

这是我实验中的一个错误脚本:

select 'test line 1'||'\n'||'test line 2';

我想 sql editor显示这个结果从我的脚本以上:

test line 1
test line 2

但不幸的是,当我在 sql 编辑器中运行脚本时,我只得到了这个结果:

test line 1 test line 2
113389 次浏览

The backslash has no special meaning in SQL, so '\n' is a backslash followed by the character n

To use "escape sequences" in a string literal you need to use an "extended" constant:

select 'test line 1'||E'\n'||'test line 2';

Another option is to use the chr() function:

select 'test line 1'||chr(10)||'test line 2';

Or simply put the newline in the string constant:

select 'test line 1
test line 2';

Whether or not this is actually displayed as two lines in your SQL client, depends on your SQL client.


UPDATE: a good answer from @thedayturns, where you can have a simpler query:

select E'test line 1\ntest line 2';

If you want to search if a jsonb contains \n this works

SELECT * FROM table
WHERE column ~ '^.*\\n.*$'