Lessons › SQL › Deep Dive: Text, Date & Number Functions
SQL lesson
MOD operator (%) for modulo arithmetic
The modulo operator returns the remainder after division - so dividing by 3 gives you back only 0, 1, or 2, cycling endlessly no matter how large the numbers get.
Try this lesson free →Example
Splitting Retail Orders into Groups with MOD
SELECT order_id,
revenue,
order_id % 2 AS is_odd,
order_id % 3 AS batch_group
FROM orders| order_id | revenue | is_odd | batch_group |
|---|---|---|---|
| 1001 | 89.99 | 1 | 2 |
| 1002 | 45.5 | 0 | 0 |
| 1003 | 120.0 | 1 | 1 |
| 1004 | 33.75 | 0 | 2 |
| 1005 | 210.4 | 1 | 0 |
Step by step
- AS gives a column a friendlier name in the result.
SELECT order_id, revenue, order_id % 2 AS is_odd, order_id % 3 AS batch_group - FROM tells SQL which table to pull the data from.
SELECT order_id, revenue, order_id % 2 AS is_odd, order_id % 3 AS batch_group FROM orders;
Practice
1. Using orders, write a query to find rows where revenue is even (divisible by 2).
SELECT * FROM orders WHERE revenue % 2 = 02. Using store_sales, write a query to find rows where revenue is even (divisible by 2).
SELECT * FROM store_sales WHERE revenue % 2 = 03. Using products, write a query to find rows where price is even (divisible by 2).
SELECT * FROM products WHERE price % 2 = 04. Using reviews, write a query to find rows where rating is even (divisible by 2).
SELECT * FROM reviews WHERE rating % 2 = 05. Using employees, write a query to find rows where salary is even (divisible by 2).
SELECT * FROM employees WHERE salary % 2 = 0Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →