← Back to SQL, page 9

sql-0166 · Easy fresher

How do you test whether a number is even, and what does the % operator return for negative numbers?

Use n % 2 = 0 for even numbers. The result of % takes the sign of the left operand on both SQLite and PostgreSQL, so -7 % 2 is -1, not 1. Test odd numbers with n % 2 <> 0 rather than n % 2 = 1, which misses negative odd values.

Full answer
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, -7 % 2 = 1 AS b_is_one;
abcb_is_one
1-110
sql
SELECT 7 % 2 AS a, -7 % 2 AS b, 7 % -2 AS c, mod(-7, 2) AS mod_fn;
abcmod_fn
1-11-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