| From: | Guillaume Lelarge <guillaume(dot)lelarge(at)dalibo(dot)com> |
|---|---|
| To: | PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org> |
| Subject: | Setting the number of digits after the decimal point with a psql's pset variable |
| Date: | 2026-10-29 20:45:54 |
| Message-ID: | a1db875a-15dc-4a8a-a1b3-1f32b020b70a@dalibo.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hello,
Each time I execute a query to get some ratio or percentage, I end up
with a lot of usually useless digits after the decimal point. For example:
postgres=> select datname,
100.*blks_hit/(blks_read+blks_hit) as hit_ratio
from pg_stat_database
order by 1
limit 5;
datname | hit_ratio
---------+---------------------
b1 | 70.0758884178573298
b2 | 97.3346067025525265
b3 | 97.8544316239962496
b4 | 31.8874531850956484
b5 | 43.0444853056359762
(5 rows)
I would rather get only two digits (or one, or even less) after the
decimal point. I know I can do that easily by wrapping the second column
with a call to round(). Easily because this query is simple. But
sometimes, the query is much bigger, the number of columns which need a
call to round() is high enough to make me stop doing it or get pissed
because it gets quickly error prone. I need something quicker and
easier. Something like a pset variable which would allow me to tell psql
how many digits I want after the decimal point. The patch attached does
that. It adds a pset variable called n_decimals, which defaults to all,
meaning no changes in psql's behaviour. A user can set it to any
positive number to get that number of digits after the decimal point. An
example:
postgres=> \pset n_decimals 2
Number of decimals is "2".
postgres=> \g
datname | hit_ratio
---------+-----------
b1 | 70.10
b2 | 97.33
b3 | 97.85
b4 | 31.89
b5 | 43.05
(5 rows)
postgres=> \pset n_decimals 0
Number of decimals is "0".
postgres=> \g
datname | hit_ratio
---------+-----------
b1 | 70
b2 | 97
b3 | 97
b4 | 31
b5 | 43
(5 rows)
postgres=> \pset n_decimals
Number of decimals is "0".
postgres=> \pset n_decimals all
Number of decimals is "all".
postgres=> \g
datname | hit_ratio
---------+---------------------
b1 | 70.1052134669652421
b2 | 97.3396221743544034
b3 | 97.8583698372493909
b4 | 31.8998905599223468
b5 | 43.0615702842088872
(5 rows)
Any comments welcome :)
Thank you.
Regards.
--
Guillaume Lelarge
Consultant
https://dalibo.com
| Attachment | Content-Type | Size |
|---|---|---|
| 0001-Add-new-n_decimals-pset-variable.patch | text/x-patch | 9.1 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Greg Burd | 2026-10-29 20:46:03 | Re: Expanding HOT updates for expression and partial indexes |
| Previous Message | surya poondla | 2026-10-29 20:44:42 | Re: Return INT_MAX or INT_MIN from strtoint() on overflow |