How to Use ABS() Function in PostgreSQL

PostgreSQL offers a built-in mathematical function named ABS() that takes a number or expression as an argument and retrieves an absolute value of the specified number. The absolute value of a number indicates how far it is away from zero. It is a non-negative(always positive) value because it doesn’t signify the direction.

This post will explain the following topics through practical examples:

  • How to Use ABS() Function in Postgres?
  • What is the ABS() Function, and How Does it Work on Positive Values?
  • How Does the ABS() Function Work on Negative Values?
  • How Does the ABS() Function Work on Table’s Data?

So, let’s get started!

How to Use ABS() Function in Postgres?

To use the Postgres ABS() function, follow the below syntax:

ABS(numeric_expression);

The syntax illustrates the below-listed points:

  • The ABS() function accepts only one argument, i.e., a numeric expression.
  • The data type of the retrieved value depends on the data type of the value passed to the ABS() function.
  • In the case of negative numbers, the ABS() function will return the negation of that number.

Let’s implement it practically.

What is the ABS() Function and How Does it Work on Positive Values?

Let’s pass a positive numeric value to the ABS() function and see how it works:

SELECT ABS(1001.5225);
img

Since the passed value was non-negative, therefore the ABS() function retrieved that value as it is.

How Does the ABS() Function Work on Negative Values?

In this example, we will pass a negative numeric value to the ABS() function:

SELECT ABS(-1001.5225);
img

This time we passed a negative value to the ABS() function. Consequently, the ABS() function retrieved the negation of that number.

How Does the ABS() Function Work on Table’s Data?

For profound understanding, we create a table named abs_example containing an original_val column. The original_val column will accept numeric values:

CREATE TABLE abs_example(
original_val NUMERIC
);
img

Let’s insert some positive as well as negative values into the abs_example table:

INSERT INTO abs_example(original_val)
VALUES (550),
(-210), 
(72.12),
(-87.93),
(-0.0);
img

Let’s utilize the ABS() function on the abs_example table to see how the ABS() function works on the table’s data:

SELECT original_val, ABS(original_val) AS absolute_value
FROM abs_example;
img

The output verifies the working of the ABS() function.

Conclusion

PostgreSQL provides an inbuilt mathematical function named ABS() to get an absolute value. It takes a number or expression as an argument and retrieves an absolute value of the specified number. The absolute numeric value represents how far it is away from zero. It is a non-negative(always positive) value because it doesn’t signify the direction. Through practical examples, this article explained the working of the ABS() function.