Fit Psql Output on the Screen
Do you love psql but can't stand how the output wraps and doesn't fit on the screen? Here's a tip for you!
CLI for Querying Postgresl
psql
is a great little tool that comes with the postgres database. It allows you to connect to the database cluster from a cli and run queries.
But let's say you have a small terminal screen or a table with 300 columns. In these cases, getting the query output to show up in a readable format can be a challenge.
With a small screen, you could end up with wrapped mumbo jumbo like this:
$ psql -d test-db
test-db=# \du
List of roles
Role name | Attributes
| Member of
-----------+------------------------------------------------
------------+-----------
postgres | Superuser, Create role, Create DB, Replication,
Bypass RLS | {}
test | Create role, Create DB
| {}
All those "nice" "lines" that show the rows and columns are now mangled by Hurricane Ian.
Expanded display
psql
has this nice option for the display width-challenged developer. It's called "expanded display". Once you turn it on, the columns will be displayed in vertical stacks so that scrolling is easier. Any long values within a column will still wrap when overflowing horizontally.
Observe:
test-db=# \x on
Expanded display is on.
test-db=# \du
List of roles
-[ RECORD 1 ]----------------------------------------------------------
Role name | postgres
Attributes | Superuser, Create role, Create DB, Replication, Bypass RLS
Member of | {}
-[ RECORD 2 ]----------------------------------------------------------
Role name | test
Attributes | Create role, Create DB
Member of | {}
Best of both worlds
But we like columns. When I can get them, they're beautiful. This is for you:
test-db-# \x auto
Expanded display is used automatically.
Now if there's screen space for the horizontal output, it'll be used. Otherwise, vertical stacking will be used.
Your psql
experience has now gotten 100x better.