Numeric Functions

Common Numeric Functions

FunctionDescriptionExample → Result
ROUND(n, d)round to d decimalsROUND(9.987, 2) → 9.99
CEILING(n) / CEIL(n)smallest integer ≥ nCEIL(4.1) → 5
FLOOR(n)largest integer ≤ nFLOOR(4.9) → 4
ABS(n)absolute valueABS(-7) → 7
MOD(a, b) / a % bremainderMOD(10, 3) → 1
POWER(a, b)a to the power bPOWER(2, 10) → 1024
SQRT(n)square rootSQRT(81) → 9

Examples

Example

Apply rounding, casting and ABS to product prices:

SELECT ProductName, Price,
       ROUND(Price * 0.9, 2) AS SalePrice,
       CAST(Price AS INTEGER) AS WholePart,
       ABS(Price - 10) AS DistanceFrom10
FROM Products;

Result: 6 rows

ProductNamePriceSalePriceWholePartDistanceFrom10
Basmati Rice 5kg12.511.25122.5
Green Tea 100 bags6.756.0863.25
Olive Oil 1L9.998.9990.01
Dark Chocolate3.493.1436.51
Espresso Beans 1kg1816.2188
Almonds 500g8.257.4281.75

Note: CEIL, FLOOR, POWER and SQRT are available in MySQL, PostgreSQL, SQL Server and Oracle. SQLite only has them from version 3.35.

CAST: Converting Types

Example

CAST(expr AS type) converts between types; useful to avoid integer division:

SELECT CAST('42' AS INTEGER) + 8 AS Number,
       CAST(7 AS REAL) / 2 AS Half,
       CAST(Salary AS INTEGER) / 1000 || 'k' AS Short
FROM Employees
LIMIT 2;

Result: 2 rows

NumberHalfShort
503.572
503.558