I wrote before about psql Tips and Tricks.
This is more useful stuff I picked up since then.
Quick links:
Pretty-printing JSON(B) columns
In a query result, JSONB
columns can be hard to read:
the jsonb_pretty function really helps:
Even if a column isn’t strictly JSONB
, you can usually cast, with ::jsonb
, to get what you want:
Using better aggregate functions
Consider this query:
If there are MANY authors, maybe you would want to group by
. Most aggregate functions (sum
, count
, avg
…) would hide the actual pages
values…
There are many options, but let’s start with string_agg
Not bad, but I had to cast the pages column from number to ::text
to make this work. Generally, you might reach for array_agg instead:
There are other exciting aggregate functions out there.
For this section, we’ll keep using the same query, but compare different viewing options.
What a wrapping mess … but this is the default behavior in psql
(i.e. \pset format aligned
)
I recommended, in better defaults, using \x auto
to fix that. It has its own charm:
Another (usually better) option is to use \pset format wrapped
This is ESPECIALLY useful when dealing with multiple wide columns. psql
will try to fit each row to your screen’s width.
It’s not magic though; it’s the HTML-table solution to formatting. Visually, you’ll
know right away when it’s not the right fit.
All together
The good news is that these settings and functions are composable.
\pset format wrapped
jsonb_pretty
array_agg
Knowing what’s possible is most of the work 😄