52

I'm selecting from a table with long text columns. I'd like to wrap long lines to a maximum line length.

From:

SELECT * FROM test;
test_id |                                  text
--------+-----------------------------------------------------------------------
      1 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lorem

To:

test_id |              text
--------+-----------------------------
      1 | Lorem ipsum dolor sit amet,+
        | consectetur adipiscing elit+
        | . Mauris lorem
jkj
  • 856
  • 1
  • 6
  • 8

3 Answers3

51

If you're using the psql command line tool, issue this command first:

\pset format wrapped

It should then wrap long lines to your terminal window like so:

test_id |              text
--------+-----------------------------
      1 | Lorem ipsum dolor sit amet,.
        |.consectetur adipiscing elit.
        |.. Mauris lorem

You can also set the number of columns to wrap to with

\pset columns 100

and you can change the dots to ellipses with

\pset linestyle unicode

More info: http://www.postgresql.org/docs/current/static/app-psql.html

randers
  • 107
  • 3
linesarefuzzy
  • 626
  • 6
  • 4
13

My answer won't directly answer your question because I don't think psql itself can specifically do this. But, \x will turn on expanded output, which will place your values like this:

-[ RECORD 1 ]------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
id         | 1
longstring | This is a long string of text that will be quite long and most likely be very annoying to read if you are viewing results with more than at most a few columns of data. Words words words words words words lorem ipsum.

You can also configure your pager to not wrap lines.

To switch to normal display, just issue the command \x again. Explanation:

\x [on|off|auto] toggle expanded output (currently off)
András Váczi
  • 31,778
  • 13
  • 102
  • 151
Derek Arnold
  • 1,166
  • 6
  • 4
3

With the Regexp_Replace function, we can control the exact width of each column separately.  In your example, 27 seems to be the desired column width; so we

SELECT Regexp_Replace('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris lorem'
, '(.{27})' , E'\\1\n' , 'g');

, obtaining

       regexp_replace        
-----------------------------
 Lorem ipsum dolor sit amet,+
  consectetur adipiscing eli+
 t. Mauris lorem

How it works:    We tell Regexp_Replace to replace a block of 27 consecutive characters (.{27}), with itself (\1) plus a newline (\n); and the global flag (g) says to do that for all such 27-character blocks.
Vainstein K
  • 196
  • 3