Menu
Coddy logo textTech

The Modulo Operation

Part of the Fundamentals section of Coddy's SQL journey — lesson 25 of 72.

The modulo operator % tells you what's left over after dividing one number by another.

dividend % divisor
  • dividend: The number being divided.
  • divisor: The number that divides the dividend.

For example

10 % 3

Here, 10 is divided by 3. 3 goes into 10 three times, with a remainder of 1. So, result will be 1.

Usually modulo is used for checking if a number is even or odd:

  • If a number is even, dividing it by 2 will leave a remainder of 0.
  • If a number is odd, dividing it by 2 will leave a remainder of 1.

For example find even-numbered rows:

SELECT * FROM table WHERE id % 2 = 0;

Or for cycling through values:

  • number % 12 (returns 0-11)
  • number % 8 (return 0-7)

For example group items into sets of 5:

SELECT item_number % 5 as group_number FROM inventory;
challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>products</strong>: <strong>id</strong>, <strong>price</strong>, quantity

Create a query that:

  1. Shows the product ID
  2. Assigns each product to one of three quality control teams (0, 1, or 2) based on the product ID using the modulo operator, call this column as quality_control
  3. Only includes products where the quantity column contains an odd number (e.g., 1, 3, 5, 7...)

Cheat sheet

The modulo operator % returns the remainder after division:

dividend % divisor

Common uses:

  • Check even/odd: number % 2 = 0 (even) or number % 2 = 1 (odd)
  • Cycle through values: number % 12 returns 0-11
  • Group items: item_number % 5 creates groups 0-4

Examples:

-- Find even-numbered rows
SELECT * FROM table WHERE id % 2 = 0;

-- Group items into sets of 5
SELECT item_number % 5 as group_number FROM inventory;

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals