PostgreSQL – ABS Function

In PostgreSQL, the ABS() function is used to compute the absolute value of a numeric or interval expression. The absolute value of a number is its magnitude without regard to its sign. If the number is positive or zero, the absolute value remains the same. If the number is negative, the absolute value is its positive counterpart.

The basic syntax of the ABS() function is as follows:

ABS(expression)

where expression is the numeric or interval value for which you want to calculate the absolute value.

Below are some examples of using the ABS() function:

  1. Calculating the absolute value of a positive number:
SELECT ABS(5) AS absolute_value;

This query will return 5 since the absolute value of 5 is 5.

  1. Calculating the absolute value of a negative number:
SELECT ABS(-8) AS absolute_value;

This query will return 8 since the absolute value of -8 is 8.

  1. Calculating the absolute value of a numeric expression:
SELECT ABS(10 - 20) AS absolute_difference;

This query will return 10 since the absolute value of 10 - 20 is 10.

  1. Calculating the absolute value of an interval:
SELECT ABS(INTERVAL '3 days') AS absolute_interval;

This query will return 3 days since the absolute value of 3 days is 3 days.

The ABS() function is commonly used when you want to ensure that a value is treated as positive or when you need to compute differences or distances regardless of their signs.

Keep in mind that the ABS() function only works with numeric and interval types. If you try to use it with non-numeric or non-interval data types, PostgreSQL will raise an error.

Similar Posts