Numeric equality and hashing without detoasting

From: Andrei Lepikhov <lepihov(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>, Andreas Karlsson <andreas(at)proxel(dot)se>
Cc: David Geier <geidav(dot)pg(at)gmail(dot)com>
Subject: Numeric equality and hashing without detoasting
Date: 2026-11-24 13:47:57
Message-ID: 959ad09c-1d66-4260-9c2a-17b2dff03f14@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

This is the second step of the numeric operations optimisation efforts, started
at [1].

This part is about the idea that the EQ/NEQ operator might avoid unpacking
operations altogether. A more general routine, cmp_numerics(), is used for < and
> operations too and needs unpacking, so the previous thread [1] should help in
this case.

0001 makes numeric_eq() and numeric_ne() decide from the bytes as stored. If two
finite values have the same header word and the same length, one memcmp() gives
the answer. Otherwise the code repeats the tests of cmp_numerics() on the stored
form. Compressed, TOASTed, and non-normalised values with leading or trailing
zero digits, still use cmp_numerics() - but in practice it looks like quite rare
case.

0002 applies the same idea to hash_numeric() and hash_numeric_extended(). They
need only the weight and the digits, so they now read them in place. Hash values
do not change.

Performance gain might be easily identified by the following test:

CREATE TEMP TABLE t (x numeric(12,8));
INSERT INTO t SELECT random() FROM generate_series(1,1E7);
ANALYZE t;

SELECT x FROM t t1 WHERE x = 42.42;

On my Intel Macbook Pro 2019 I see the following numbers:

master ~300 ms, patched ~220 ms.

Other primitives show the following numbers:

WHERE a = b, same scale -39%
WHERE a <> b -31%
WHERE a = b, other scale -30%
k = constant of other scale -27%
k IN (seven constants) -44%
GROUP BY one key -32% (0001 alone: -23%)
GROUP BY ten keys -48% (0001 alone: -37%)

Queries without numeric equality are not affected.

It might seem overcomplicated for these speedup numbers. But it might be an
approach to speed up operations on other types too. So, I'll leave it here and
let the community decide.

The patches have no regression tests yet. I will add them in the next version,
if this idea is useful.

[1] Use local buffer for packed numerics
https://www.postgresql.org/message-id/5f99450c-4b45-4b82-8498-15461411037c@gmail.com

--
regards, Andrei Lepikhov,
pgEdge

Attachment Content-Type Size
v0-0001-Decide-numeric-equality-from-the-stored-form.patch text/plain 11.1 KB
v0-0002-Hash-numerics-from-the-stored-form.patch text/plain 7.0 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Manu 2026-11-24 14:02:58 Re: REINDEX CONCURRENTLY reports lockers_done > lockers_total
Previous Message David Geier 2026-11-24 13:45:59 Re: Use correct collation in pg_trgm