ABS returns the absolute value of a number, always producing a non-negative result.
Syntax
BIGINT|DOUBLE|DECIMAL ABS(<number>)
Parameters
number: Required. Accepts DOUBLE, BIGINT, or DECIMAL values. STRING values are implicitly converted to DOUBLE before the calculation.
Return value
The return type matches the input type:
| Input type | Return type |
|---|---|
| DOUBLE | DOUBLE |
| BIGINT | BIGINT |
| DECIMAL | DECIMAL |
| STRING | DOUBLE |
| null | null |
If a BIGINT value exceeds the maximum BIGINT range, the result is returned as DOUBLE. Precision may be lost in this case.
Examples
Static values
SELECT ABS(null); -- Returns null
SELECT ABS(-1); -- Returns 1
SELECT ABS(-1.2); -- Returns 1.2
SELECT ABS("-2"); -- Returns 2.0 (STRING implicitly converted to DOUBLE)
SELECT ABS(122320837456298376592387456923748); -- Returns 1.2232083745629837E32
SELECT ABS(id) FROM tbl1; -- Returns the absolute value of the id column. Other built-in functions, except window functions and aggregate functions, are used in a similar way.
Table data
The following example calculates absolute values across multiple column types using the mf_math_fun_t sample table. The query covers BIGINT, DOUBLE, DECIMAL, and STRING inputs in a single statement.
SELECT ABS(bigint_data) AS bigint_new,
ABS(double_data) AS double_new,
ABS(decimal_data) AS decimal_new,
ABS(string_data) AS string_new
FROM mf_math_fun_t;
The following result is returned:
+------------+------------+-------------+------------+
| bigint_new | double_new | decimal_new | string_new |
+------------+------------+-------------+------------+
| 10 | 0.525 | 0.525 | 10.0 |
| NULL | 0.1 | 0.1 | 10.0 |
| 1 | NULL | 20.45 | 30.0 |
| 4 | 0.89 | NULL | 30.0 |
| 50 | 1.0 | 1 | 50.0 |
| 6 | 1.5 | 1.5 | 50.0 |
| 70 | 7.5 | 7.5 | NULL |
| 1 | 10.2 | 10.2 | 1.0 |
| 90 | 2.58 | 2.58 | 0.0 |
| 10 | 5.8 | 5.8 | 90.0 |
+------------+------------+-------------+------------+
Sample data
The following statements create the mf_math_fun_t table and insert sample data used in the table examples above.
CREATE TABLE IF NOT EXISTS mf_math_fun_t(
int_data INT,
bigint_data BIGINT,
double_data DOUBLE,
decimal_data DECIMAL,
float_data FLOAT,
string_data STRING
);
INSERT INTO mf_math_fun_t VALUES
(null, -10, 0.525, 0.525BD, CAST(0.525 AS FLOAT), '10'),
(-20, null, -0.1, -0.1BD, CAST(-0.1 AS FLOAT), '-10'),
(0, -1, null, 20.45BD, CAST(-1 AS FLOAT), '30'),
(-40, 4, 0.89, null, CAST(0.89 AS FLOAT), '-30'),
(5, -50, -1, -1BD, null, '50'),
(-60, 6, 1.5, 1.5BD, CAST(1.5 AS FLOAT), '-50'),
(-1, -70, -7.5, -7.5BD, CAST(-7.5 AS FLOAT), null),
(-80, 1, -10.2, -10.2BD, CAST(-10.2 AS FLOAT), '-1'),
(9, -90, 2.58, 2.58BD, CAST(2.58 AS FLOAT), '0'),
(-100, 10, -5.8, -5.8BD, CAST(-5.8 AS FLOAT), '-90');
Related functions
ABS is a mathematical function. For more information, see Mathematical functions.