Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert line break in postgresql when updating text field

I am trying to update a text field in a table of my postgresql database.

UPDATE public.table SET long_text = 'First Line' + CHAR(10) + 'Second line.' WHERE id = 19; 

My intended result is that the cell will look like this:

 First Line Second line 

The above syntax returns an error.

like image 452
alexyes Avatar asked Oct 29 '14 19:10

alexyes


People also ask

How do I insert a line break 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.

How do I add a new line character in PostgreSQL?

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';

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.

Does update insert in Postgres?

The idea is that when you insert a new row into the table, PostgreSQL will update the row if it already exists, otherwise, it will insert the new row. That is why we call the action is upsert (the combination of update or insert).


1 Answers

You want chr(10) instead of char(10).

Be careful with this, because that might be the wrong newline. The "right" newline depends on the client that consumes it. Macs, Windows, and Linux all use different newlines. A browser will expect <br />.

It might be safest to write your update like this for PostgreSQL 9.1+. But read the docs linked below.

UPDATE public.table  SET long_text = E'First Line\nSecond line.'  WHERE id = 19; 

The default value of 'standard_conforming_strings' is 'on' in 9.1+.

show standard_conforming_strings; 
like image 122
Mike Sherrill 'Cat Recall' Avatar answered Sep 22 '22 07:09

Mike Sherrill 'Cat Recall'