How to Round Up a Number to the Nearest Integer in SQL
Database:
Operators:
Table of Contents
Problem:
You want to round up a number to the nearest integer in SQL.
Example:
Our database has a table named rent with data in the following columns: id
, city
, area
, and bikes_for_rent
.
id | city | area | bikes_for_rent |
---|---|---|---|
1 | Los Angeles | 1302.15 | 1000 |
2 | Phoenix | 1340.69 | 500 |
3 | Fargo | 126.44 | 101 |
Let’s show each city’s name along with the ratio of its area to the number of bikes for rent. This ratio should be an integer.
Solution:
SELECT city, CEILING(area/bikes_for_rent) AS ratio FROM rent; |
The query returns each city with the ratio as an integer of rounded up the area per one bike.
id | city | ratio |
---|---|---|
1 | Los Angeles | 2 |
2 | Phoenix | 3 |
3 | Fargo | 2 |
Discussion:
Like its counterpart floor, ceiling is a mathematical operation that takes a number and rounds it up to the nearest integer. For example, the ceiling of 5 is 5, and so is the ceiling of 4.1.
SQL uses the CEILING
function to perform this computation. It takes a single argument: the column whose values you’d like to round up to the nearest integer.
In our example, we’d like to calculate how many square meters (rounded up to the nearest integer) there are per one bike. In our example, we used CEILING
like so: CEILING(area/bikes_for_rent)
). This returns an integer result, not a float.