Is there a way to set the max width of a column when displaying query results in psql?

425nesp picture 425nesp · May 16, 2015 · Viewed 7.3k times · Source

The problem I'm having is that I have a table with 10 columns. 1 of those columns is HTML and, as a result, is really long. It's so long that it wraps around several lines and screws up the otherwise useful output. Normally, I've been selecting all of the columns except for that one. However, I'm starting to join with another table and have like 20 columns now.

Is there a way to specify the maximum column width or to truncate a column after a certain number of characters?

I tried \x. It kind of helped... but for the most part everything still looks scrambled.

Answer

Pavel Stehule picture Pavel Stehule · May 16, 2015

you can specify columns width via \pset columns X

postgres=# select 'some longer text some longer text some longer text some longer text some longer text some longer text';
┌───────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                               ?column?                                                │
╞═══════════════════════════════════════════════════════════════════════════════════════════════════════╡
│ some longer text some longer text some longer text some longer text some longer text some longer text │
└───────────────────────────────────────────────────────────────────────────────────────────────────────┘
(1 row)

postgres=# \pset format wrapped 
Output format is wrapped.
postgres=# \pset columns 20
Target width is 20.
postgres=# select 'some longer text some longer text some longer text some longer text some longer text some longer text';
┌──────────────────┐
│     ?column?     │
╞══════════════════╡
│ some longer text…│
│… some longer tex…│
│…t some longer te…│
│…xt some longer t…│
│…ext some longer …│
│…text some longer…│
│… text            │
└──────────────────┘
(1 row)

Be sure, so your pager is well configured - set global variables:

export PAGER=less
export LESS='-iMSx4 -RSFX -e'