InĀ MySQL, the ABS()
function returns the absolute value of a given value.
An absolute value is the distance of a number on the number line from 0 without considering which direction from zero the number lies. Therefore, the absolute value of a number is always a non-negative value (i.e. it’s never negative).
Syntax
The syntax goes like this:
ABS(X)
Where X
is the value for which you’d like the absolute value returned.
Example 1 – Basic Example
Here’s a basic example to demonstrate what ABS()
returns for a given number.
SELECT ABS(7);
Result:
+--------+ | ABS(7) | +--------+ | 7 | +--------+
In this case, our argument is a positive number and so the same number is returned.
Example 2 – Negative Numbers
Here’s what happens if we pass in a negative value.
SELECT ABS(-7);
Result:
+---------+ | ABS(-7) | +---------+ | 7 | +---------+
As you can see, the result is a non-negative value (even though we passed in a negative value). This is the absolute value of the argument.
Example 3 – Expressions
You can return the absolute value of expressions, such as the following:
SELECT ABS(7+3);
Result:
+----------+ | ABS(7+3) | +----------+ | 10 | +----------+
Another example:
SELECT ABS(-7+3);
Result:
+-----------+ | ABS(-7+3) | +-----------+ | 4 | +-----------+
As you can see, this is a different result than we’d get if we simply returned the expression itself (without using the ABS()
function). Here’s what that would return:
SELECT -7+3;
Result:
+------+ | -7+3 | +------+ | -4 | +------+