Careeroza
Numeric Functions
Common Numeric Functions
| Function | Description | Example → Result |
|---|---|---|
ROUND(n, d) | round to d decimals | ROUND(9.987, 2) → 9.99 |
CEILING(n) / CEIL(n) | smallest integer ≥ n | CEIL(4.1) → 5 |
FLOOR(n) | largest integer ≤ n | FLOOR(4.9) → 4 |
ABS(n) | absolute value | ABS(-7) → 7 |
MOD(a, b) / a % b | remainder | MOD(10, 3) → 1 |
POWER(a, b) | a to the power b | POWER(2, 10) → 1024 |
SQRT(n) | square root | SQRT(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
| ProductName | Price | SalePrice | WholePart | DistanceFrom10 |
|---|---|---|---|---|
| Basmati Rice 5kg | 12.5 | 11.25 | 12 | 2.5 |
| Green Tea 100 bags | 6.75 | 6.08 | 6 | 3.25 |
| Olive Oil 1L | 9.99 | 8.99 | 9 | 0.01 |
| Dark Chocolate | 3.49 | 3.14 | 3 | 6.51 |
| Espresso Beans 1kg | 18 | 16.2 | 18 | 8 |
| Almonds 500g | 8.25 | 7.42 | 8 | 1.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
| Number | Half | Short |
|---|---|---|
| 50 | 3.5 | 72 |
| 50 | 3.5 | 58 |