Insert line break in postgresql when updating text field

PostgresqlCharSql Update

Postgresql Problem Overview


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.

Postgresql Solutions


Solution 1 - Postgresql

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;

Solution 2 - Postgresql

Use a literal newline (if standard_conforming_strings = on, i.e. you're on a recent PostgreSQL):

UPDATE public.table 
SET long_text = 'First Line
Second line.' 
WHERE id = 19;

or you can use an escape:

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

Solution 3 - Postgresql

In my version of postgres, \n didnt work for line break and i used \r\n instead, like this:

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

Solution 4 - Postgresql

PostgreSQL:

varchar + varchar = ERROR. \ r and \ n is not anywhere that works, for greater compatibility use:

Corret:

UPDATE public.table SET 
   long_text = concat('First Line',CHR(13),CHR(10),'Second line.')
WHERE id = 19;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexyesView Question on Stackoverflow
Solution 1 - PostgresqlMike Sherrill 'Cat Recall'View Answer on Stackoverflow
Solution 2 - PostgresqlCraig RingerView Answer on Stackoverflow
Solution 3 - PostgresqlMaryam HomayouniView Answer on Stackoverflow
Solution 4 - PostgresqlFranco Michel Almeida CaixetaView Answer on Stackoverflow