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 % 3Here, 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
EasyAvailable tables and columns:
<strong>products</strong>:<strong>id</strong>,<strong>price</strong>,quantity
Create a query that:
- Shows the product ID
- 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 - 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 % divisorCommon uses:
- Check even/odd:
number % 2 = 0(even) ornumber % 2 = 1(odd) - Cycle through values:
number % 12returns 0-11 - Group items:
item_number % 5creates 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns