NumbersSQL standard

ABS

Returns the absolute value of a number — its value without the sign.

Syntax

ABS(<number>)

A negative number becomes positive, while positive numbers and zero stay as they are: ABS(-7) gives 7. Most often it's used to measure a distance or difference when the direction doesn't matter: how far a value is from a target, how far a forecast is from reality.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

The absolute value of a number
SELECT ABS(-7) AS negative,
ABS(7) AS positive,
ABS(-2.5) AS fraction;
negativepositivefraction
772.5
How far a salary is from 1300
SELECT name, salary,
ABS(salary - 1300) AS distance_from_1300
FROM employees;
namesalarydistance_from_1300
Emma1200100
Liam1000300
Olivia135050
Noah950350
Sophia1200100
The salary closest to 1300
SELECT name, salary
FROM employees
ORDER BY ABS(salary - 1300)
LIMIT 1;
namesalary
Olivia1350

Watch out

When sorting by a difference, remember equal distances: any of them could end up “closest”. Add a second field to ORDER BY.

The absolute value removes the sign, so you can no longer tell whether the value is bigger or smaller. If the direction matters, look at the difference itself or at SIGN.

The smallest number of a type has no positive counterpart: ABS((-2147483648)::integer) throws integer out of range.

Related functions

Learn more in the course