mod(y, x) — Remainder of a division
Last updated: 2026-11-04
mod(y, x) — Remainder of a division
mod(y, x) returns the remainder of dividing y by x, with the dividend first and the divisor second, matching the % operator. It is used for shard routing, cyclic bucketing and "every Nth row" logic; note that PostgreSQL keeps the sign of the dividend, while modulo in many languages is always non-negative.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
mod(y numeric, x numeric) → numeric
⚙️ Parameters
| y numeric | The dividend. Type numeric; integer and other numeric types are also accepted. |
|---|---|
| x numeric | The divisor; it must not be 0 or the call raises an error. Type numeric. |
Returns:numeric — the remainder, carrying the sign of the dividend y.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | label | n | shard_bucket | operator_form
----+---------+------+--------------+---------------
1 | shard-a | 1001 | 1 | 1
2 | shard-b | 1002 | 2 | 2
3 | shard-c | 1003 | 3 | 3
(3 rows)
📌 Key Points
- mod(n, 8) is exactly equivalent to n % 8.
- The remainder keeps the sign of the dividend in PostgreSQL: mod(-7, 3) returns -1, not 2.
- A zero divisor raises an error, so guard it with nullif() before dividing.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QWhy does mod(-7, 3) return -1 instead of 2?
APostgreSQL's mod() truncates toward zero and keeps the sign of the dividend, hence -1. For a always-non-negative mathematical modulo use mod(n + 8, 8) or ((n % 8 + 8) % 8).