ABS & MOD
In this page:
The Absolute Value with ABS
ABS converts any negative number into its positive equivalent while leaving positive numbers unchanged, which is useful for measuring the size of a difference between two values without caring which one is larger.
Example: The Absolute Value with ABS
SELECT ABS(-15) AS positive_value;
The Remainder with MOD
MOD returns the remainder left over after dividing one number by another, the same operation as the % operator in most programming languages — useful for tasks like distributing rows evenly across a fixed number of groups.
Example: The Remainder with MOD
SELECT MOD(17, 5) AS remainder;
Finding Even and Odd Numbers
Checking whether a number is even or odd is a classic use of MOD: dividing by 2 and testing whether the remainder is 0 tells you evenness instantly, without writing a more complex conditional.
Example: Finding Even and Odd Numbers
CREATE TABLE numbers (n INT);
INSERT INTO numbers VALUES (4), (7), (10);
SELECT n, CASE WHEN MOD(n, 2) = 0 THEN 'even' ELSE 'odd' END AS parity FROM numbers;
Using MOD with Decimal Values
MOD isn't limited to whole numbers — it also works on decimal values, dividing the first number by the second and returning the leftover floating-point remainder rather than an error.
Example: Using MOD with Decimal Values
SELECT MOD(10.5, 3) AS decimal_remainder;
Combining ABS and MOD
Combining ABS and MOD together guarantees a positive remainder even when working with negative inputs, since MOD alone can return a negative result if the dividend is negative.
Example: Combining ABS and MOD
SELECT MOD(-7, 3) AS raw_mod, ABS(MOD(-7, 3)) AS positive_mod;
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: