SQL: Structured Query LanguageSQL FundamentalsScalar Functions
What is the purpose of the ROUND function?
Question 30 of 30 · Updated
ROUND() rounds a numeric value to a specified number of decimal places. It is useful for displaying ratings, percentages, prices and calculated report values with an appropriate level of precision.
How ROUND works#
In PostgreSQL, ROUND(number) rounds to the nearest whole number. ROUND(number, decimal_places) rounds a NUMERIC value to the specified precision. A negative second argument rounds to the left of the decimal point.
SQLSELECT ROUND(12.345) AS whole_number, ROUND(12.345, 2) AS two_decimals, ROUND(1256.78, -2) AS nearest_hundred, ROUND(-2.5) AS negative_tie, ROUND(NULL::numeric, 2) AS missing;
| Expression | Result | Meaning |
|---|---|---|
| ROUND(12.345) | 12 | Nearest integer value |
| ROUND(12.345, 2) | 12.35 | Two decimal places |
| ROUND(1256.78, -2) | 1300 | Nearest hundred |
| ROUND(-2.5) | -3 | Numeric midpoint rounds away from zero |
| ROUND(NULL::numeric, 2) | NULL | Missing input remains missing |
These results use PostgreSQL's exact NUMERIC arithmetic. Floating-point midpoint behavior and support for negative precision can differ across databases. For PostgreSQL's two-argument form, cast floating-point input to NUMERIC first if required.
Practical example: display product ratings#
A catalog may calculate ratings to several decimal places, but customers only need one decimal place in the product list.
SQLWITH ratings(product, rating) AS ( VALUES ('Pen', 4.376), ('Notebook', 3.824), ('Marker', NULL::numeric) ) SELECT product, rating, ROUND(rating, 1) AS display_rating FROM ratings ORDER BY product;
| product | rating | display_rating |
|---|---|---|
| Marker | NULL | NULL |
| Notebook | 3.824 | 3.8 |
| Pen | 4.376 | 4.4 |
The original rating remains unchanged by SELECT. The rounded column is a numeric result, not a guarantee of how the client formats trailing zeros.
Remember for interviews#
ROUND is different from truncation: it selects the nearest value at the requested precision rather than simply dropping extra digits. Avoid rounding intermediate values unnecessarily because it can change a final total or average. For financial calculations, follow the specified rounding policy.
Validation: Both examples were executed successfully against PostgreSQL using synthetic values. Official Supabase Detection checks documentation was consulted for rounding report metrics. The PostgreSQL manual reference was not live fetched under the offline research exception. Output tables convey the result directly, so no diagram is needed.
References: PostgreSQL mathematical functions and operators · Supabase Detection checks
References
- 1.PostgreSQL — Mathematical Functions and Operatorspostgresql.org
- 2.Supabase — Detection checkssupabase.com
Related questions
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning