Insert line break in postgresql when updating text field

alexyes picture alexyes · Oct 29, 2014 · Viewed 63k times · Source

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.

Answer

Mike Sherrill 'Cat Recall' picture Mike Sherrill 'Cat Recall' · Oct 29, 2014

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;