SQLite | SQLite Functions | Calculating an Absolute Value (abs Function)
The abs function calculates the absolute value of a number. This article explains how to use the function.
Using the abs Function
Use abs to calculate a number’s absolute value. Its syntax is as follows.
abs(number)
It returns the absolute value of its argument. A positive number is returned unchanged, while a negative number is returned as a positive number.
abs(0.47); /* 0.47 */
abs(-19); /* 19 */
When the argument is NULL, the function returns NULL. When it is a nonnumeric value that cannot be converted to a number, the function returns 0.0.
abs(NULL); /* NULL */
abs('-18.5'); /* 18.5 */
abs('pen'); /* 0.0 */
When a column name is supplied, the function calculates the absolute value of each value stored in that column.
–
Let’s calculate some absolute values. First, create the following table.
create table test (id, data);
Add the following data with INSERT statements.
insert into test values (1, 18);
insert into test values (2, -7.4);
insert into test values (3, NULL);
insert into test values (4, 'Flower');
insert into test values (5, '-16');
sqlite> insert into test values (1, 18);
sqlite> insert into test values (2, -7.4);
sqlite> insert into test values (3, NULL);
sqlite> insert into test values (4, 'Flower');
sqlite> insert into test values (5, '-16');
sqlite>
Use abs to calculate the absolute values of the data stored in the data column.
select id, data, abs(data) from test;
sqlite> .mode column
sqlite> .header on
sqlite>
sqlite> select id, data, abs(data) from test;
id data abs(data)
---------- ---------- ----------
1 18 18
2 -7.4 7.4
3
4 Flower 0.0
5 -16 16.0
The absolute value of each value stored in the column is displayed.