How Abs() Works in PostgreSQL

In PostgreSQL, the abs() function returns the absolute value of its argument.

The absolute value means how far the number is away from zero. Therefore, the absolute value of 7 is 7, and the absolute value of -7 is also 7.

Therefore, any negative values passed to abs() are returned as positive values. Positive values and zero are returned unchanged.

Syntax

The syntax is quite simple:

abs(x)

Where x is the argument you provide in order to get the absolute value.

Example

Here’s an example to demonstrate its usage.

SELECT abs(-58);

Result:

58

In this case I provided a negative value (-58) and it returned its positive equivalent (58).

Positive Values

If I pass a positive value, it is returned unchanged.

SELECT abs(58);

Result:

58

Zero

Zero is also returned unchanged.

SELECT abs(0);

Result:

0

Expressions

The abs() function can return the absolute value of expressions such as the following.

SELECT abs(-20 * 5);

Result:

100

Just to be clear, here it is again compared to the actual output of the expression.

SELECT 
  (-20 * 5) AS "Result of Expression",
  abs(-20 * 5) AS "Result of abs(Expression)";

Result:

Result of Expression | Result of abs(Expression)
----------------------+---------------------------
-100 | 100