MySQL FLOOR() Function
MySQL FLOOR() Function: Rounding Down to Whole Integers
The FLOOR() function returns the largest integer value less than or equal to a given number. Unlike rounding to nearest, FLOOR() always steps downward along the number line.
You will use FLOOR() to group prices into fixed buckets (like $10 intervals), calculate completed age years, or discard fractional cents downward. It preserves exact integer or decimal types when given exact inputs.
Syntax
FLOOR(x)
x: Numeric literal, column, or expression.
Practical Example
Suppose demo_products lists retail prices, and you want to group products into $25 price brackets (0β24, 25β49, 50β74, and so on) using FLOOR(price / 25) * 25.
SELECT
FLOOR(price / 25) * 25 AS price_bucket_start,
COUNT(*) AS product_count
FROM demo_products
WHERE price IS NOT NULL
GROUP BY FLOOR(price / 25) * 25
ORDER BY price_bucket_start;
| price_bucket_start | product_count |
|---|---|
| 0 | 14 |
| 25 | 22 |
| 50 | 9 |
| 75 | 5 |
Any item priced from $25.00 to $49.99 divides by 25 into 1.00..1.99, and FLOOR() pins every one of them cleanly to 1, forming the $25 bucket.
Common Mistakes & NULL Behavior
- Expecting FLOOR() to truncate negatives toward zero:
FLOOR(-3.2)returns-4, NOT-3. Because-4is smaller than-3.2, moving down the number line steps further away from zero. UseTRUNCATE(x, 0)if you want-3. - Floating-point rounding surprises: Expressions like
FLOOR(2.3 * 100)onDOUBLEcolumns might evaluate2.2999999999999998 * 100 = 229.9999, giving229instead of230. Store money inDECIMALcolumns to avoid float drift. - NULL inputs: Passing
NULLtoFLOOR(NULL)returnsNULL.
Frequently Asked Questions
What is the difference between FLOOR(x) and TRUNCATE(x, 0)?
For positive numbers they match (FLOOR(4.9) = 4, TRUNCATE(4.9, 0) = 4). For negative numbers they differ: FLOOR(-4.9) returns -5, while TRUNCATE(-4.9, 0) returns -4.
How do I generate random integers from 1 to 10 with FLOOR()?
Combine FLOOR() with RAND(): SELECT FLOOR(1 + RAND() * 10); returns an integer from 1 through 10 inclusive.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.