SQLite abs() Function

The SQLite abs() function returns the absolute value of an argument.

If the argument is NULL, the ABS function returns NULL.

If you pass an argument with the BLOB or string type to the ABS function, SQLite will try to convert it to a number. If the conversion fails, the abs() function returns 0.

If the argument is an integer with the value -9223372036854775808, the ABS function throws an integer overflow exception because there is no positive 64-bit integer for that value.

Syntax

abs(x)Code language: SQL (Structured Query Language) (sql)

Arguments

x
x is a number or an expression that can be evaluated to a number.

Return Type

abs function returns the data type of the argument

Examples

The following statement uses the abs() function to calculate the absolute value of -1000:

SELECT abs(-1000) result;
result
------
1000Code language: Shell Session (shell)

The following example illustrates how to calculate the value of a string that can be converted into a number:

SELECT abs('2000') result;Code language: SQL (Structured Query Language) (sql)
result
-------
2000Code language: Shell Session (shell)

The same for the following example:

SELECT abs('3000abs') resultCode language: SQL (Structured Query Language) (sql)
result
------
3000.0Code language: Shell Session (shell)

However, the following statement returns 0 because the function cannot convert the string into a number.

SELECT abs('sqlite4000')result;Code language: SQL (Structured Query Language) (sql)
ABS('sqlite4000')
-----------------
0.0Code language: Shell Session (shell)

The following example illustrates how to use an expression with the abs() function.

SELECT abs(10-200) result;Code language: SQL (Structured Query Language) (sql)
result
-------
190Code language: Shell Session (shell)

If you execute the following statement, you will get an error message:

SELECT abs(-9223372036854775808);Code language: SQL (Structured Query Language) (sql)

Error:

Error while executing SQL query on database 'sampledb': integer overflowCode language: Shell Session (shell)
Was this tutorial helpful ?