Absolute values and modulo
Core idea
ABS gives the magnitude of a number without its sign. The remainder operator % lets you detect even numbers or assign nonnegative identifiers to repeating groups. MOD is another remainder function, but its supported argument types differ by database.
Minimal example
SQLite 3.46.1 example.
SELECT ABS(-12), ABS(0), -7 % 3, 7.5 % 2, MOD(7.5, 2);Observed rows (JSON notation; null means SQL NULL):
[ [ 12, 0, -1, 1, 1.5 ]]How it works
Use ABS(x), x % y for integer remainder, and MOD(x, y) where supported. With signed integers, -7 % 3 is -1 in both selected engines: the remainder can be negative. SQLite % converts operands to integers before computing the remainder; MOD can retain fractional inputs when the math extension is enabled. PostgreSQL % also accepts numeric operands. For a positive group count n, ((x % n) + n) % n gives a nonnegative group number for ordinary integer values; check intermediate overflow for extreme values.
Practical example
SQLite 3.46.1 example. Load the V22 shop-setup.sql fixture first.
SELECT id, id % 2 AS group_no, ABS(price_cents - 200) AS distance_centsFROM products ORDER BY id;Observed rows (JSON notation; null means SQL NULL):
[ [ 1, 1, 150 ], [ 2, 0, 50 ], [ 3, 1, 2200 ], [ 4, 0, 100 ]]Common mistake and practice
ABS is not a general way to obtain a mathematically nonnegative modulo. It also cannot represent the magnitude of the minimum signed 64-bit integer as a signed 64-bit integer. SQLite reports an integer overflow for that input. Practice: adapt the second query to divide products into three groups numbered 0, 1, 2; predict the group for product 4.