82

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.

1
  • 4
    The string concatenation operator in Postgresql is "||", by the way. Commented Jun 6, 2016 at 8:18

5 Answers 5

127

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 using an escape string 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;
Sign up to request clarification or add additional context in comments.

1 Comment

I used CONCAT('Text 1' , chr(13), 'Text 2') and it worked. Thanks!
44

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;

1 Comment

Thanks for this! I needed the escape option; you helped me out tremendously!
8

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;

Comments

6

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;

1 Comment

Is your version of PostgreSQL running on windows?
0

The above solutions are working find but by just entering "Enter" also you can achieve this.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.