Arithmetic modulo operator %
Last updated: 2026-11-04
Arithmetic modulo operator %
The modulo operator % returns the remainder of integer division and is equivalent to the mod() function. It is handy for "every Nth row" or bucketing by sequence number. Note that PostgreSQL truncates toward zero, so the remainder carries the sign of the dividend: -10 % 3 is -1. A NULL operand yields a NULL result.
| Kind | operator |
|---|---|
| Example Language | SQL |
📝 Syntax
a % b
Precedence: `%` shares a level with `*` and `/` and is left-associative. The sign rule matches division — truncation toward zero, so -10 % 3 is -1 rather than 2. Use `abs()` or add one `b` when you need a non-negative remainder.
⚙️ Parameters
| a | The dividend; if NULL the result is NULL. |
|---|---|
| b | The divisor; if NULL the result is NULL; 0 raises `division by zero`. |
Returns:An integer remainder of the same type as integer division; NULL if either operand is NULL.
▶ 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:
SELECT id, a % b AS remainder, mod(a, b) AS mod_fn FROM t_mod ORDER BY id
id | remainder | mod_fn
---+-----------+-------
1 | 1 | 1
2 | NULL | NULL
3 | -1 | -1
(3 rows)
SELECT a % b IS NULL AS null_is_absent FROM t_mod WHERE id = 2
null_is_absent
--------------
true
(1 row)
📌 Key Points
- NULL propagation: the result is NULL if either operand is NULL.
- The sign follows the dividend: -10 % 3 is -1 and 10 % -3 is 1.
- A zero divisor raises `division by zero`.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow do % and mod() differ?
AThere is none: % is the operator spelling of mod(), both truncating toward zero. For a non-negative remainder use mod(a, b) + b or abs().