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.

Kindfunction
Example LanguageSQL

📝 Syntax

mod(y numeric, x numeric) → numeric

⚙️ Parameters

y numericThe dividend. Type numeric; integer and other numeric types are also accepted.
x numericThe 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

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).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏