Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL newline character

How to use newline character in PostgreSQL?

This is an incorrect script from my experiment:

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

I want the sql editor display this result from my script above:

test line 1 test line 2 

But unfortunately I just get this result from my script when I run it in sql editor:

test line 1 test line 2 
like image 274
Alimin Avatar asked Mar 16 '16 07:03

Alimin


People also ask

How do I add a new line character in PostgreSQL?

To use "escape sequences" in a string literal you need to use an "extended" constant. You can specify the escape character by prefixing the letter E: UPDATE posts SET body = E'First Line\nSecond line.

What is CHR 10 in Postgres?

The PostgreSQL chr function is used to return the corresponding character against the given code within the argument. Syntax: chr(number) PostgreSQL Version: 9.3.

What are special characters in PostgreSQL?

Special character symbols are characters with a pre-defined syntactic meaning in PostgreSQL. They are typically disallowed from being used in identifier names for this reason, though as mentioned in the section on quoted identifiers, this restriction can usually be worked around with quotes if need be.

How do you identify a new line character?

There are lots ways to check this. I use Notepad++ as my text editor for this because it is easy to use and is widely used by developers. Open any text file and click on the pilcrow (¶) button. Notepad++ will show all of the characters with newline characters in either the CR and LF format.


1 Answers

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:

E'test line 1\ntest line 2'

like image 141
a_horse_with_no_name Avatar answered Sep 21 '22 23:09

a_horse_with_no_name