Full answer
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, -7 % 2 = 1 AS b_is_one;| a | b | c | b_is_one |
|---|---|---|---|
| 1 | -1 | 1 | 0 |
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, mod(-7, 2) AS mod_fn;| a | b | c | mod_fn |
|---|---|---|---|
| 1 | -1 | 1 | -1 |
Both engines truncate integer division toward zero, and % is defined to match: a = (a / b) * b + a % b. With a = -7 and b = 2, a / b is -3, so the remainder must be -1.
Checks written as n % 2 = 1 therefore treat -7 as even. n % 2 <> 0 works for both signs. The same sign rule matters for bucketing by id % 10 when ids can be negative, for example when an import uses negative ids for temporary rows.
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, -7 % 2 = 1 AS b_is_one;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- n % 2 = 0 tests for even numbers
- % takes the sign of the left operand
- -7 % 2 is -1 on SQLite and PostgreSQL
- Use n % 2 <> 0 for odd numbers
Common mistakes
- Writing n % 2 = 1 and missing negative odd numbers
- Assuming modulo always returns a non-negative value
Follow-ups
- How would you return every third row by id?
- How would you compute a positive remainder for negative numbers?
Tips
- Connect the sign rule to truncating division