SQL Cookbook Lesson
How to round numbers in SQL
Learn how to round numbers in SQL with examples and explanations from SQLPad.
Problem
You have a column in your table that contains decimal numbers. You want to round these numbers to the nearest whole numbers.
Sample Data
Let's consider the following sample data in a table named Products:
| ProductID | Price |
|---|---|
| 1 | 12.49 |
| 2 | 25.89 |
| 3 | 39.26 |
| 4 | 14.99 |
MySQL Solution
SELECT ProductID, ROUND(Price) AS RoundedPrice
FROM Products;
PostgreSQL Solution
SELECT ProductID, ROUND(Price) AS RoundedPrice
FROM Products;
MySQL Explanation
In MySQL, the ROUND() function is used to round a number to the nearest whole number. The ROUND() function takes two arguments: the number to be rounded and the number of decimal places to which the number should be rounded. In this case, we only provide one argument (the number to be rounded) so the function will round to the nearest whole number.
Here, we apply the ROUND() function to the Price column. The SQL statement selects the ProductID and the rounded Price from the Products table. The AS keyword is used to rename the ROUND(Price) column to RoundedPrice in the output.
PostgreSQL Explanation
The ROUND() function in PostgreSQL works the same way as in MySQL. It rounds the Price to the nearest whole number. The result is a list of products with their prices rounded to the nearest whole number. The AS keyword is used to rename the ROUND(Price) column to RoundedPrice in the output.