BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

order_idrevenueis_oddbatch_group
100189.9912
100245.500
1003120.011
100433.7502
1005210.410

Step by step

  1. 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
  2. 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

Try each one in your head first, then open the answer.

1. Using orders, write a query to find rows where revenue is even (divisible by 2).
SELECT * FROM orders WHERE revenue % 2 = 0
2. Using store_sales, write a query to find rows where revenue is even (divisible by 2).
SELECT * FROM store_sales WHERE revenue % 2 = 0
3. Using products, write a query to find rows where price is even (divisible by 2).
SELECT * FROM products WHERE price % 2 = 0
4. Using reviews, write a query to find rows where rating is even (divisible by 2).
SELECT * FROM reviews WHERE rating % 2 = 0
5. Using employees, write a query to find rows where salary is even (divisible by 2).
SELECT * FROM employees WHERE salary % 2 = 0

Learn 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 →
About 5–10 minutes · no sign-up needed