SQL Server ABS() Function

In SQL Server, the ABS() function is used to return the absolute value of a specified numeric expression. The absolute value is the size of a number with its sign ignored. The ABS() function takes a number as input and returns its absolute value.

Syntax

ABS(number)

number: The numeric expression for which to return the absolute value.

Use Cases

The ABS() function is typically used in the following scenarios:

  • When you need to calculate the size of a number without regard to its sign, the ABS() function can be used to convert the number to a non-negative value.
  • Negative numbers may arise when working with numeric expressions. If you want to ensure that the result is always a positive number, you can use the ABS() function.

Examples

Example 1: Calculating the Absolute Value of a Negative Number

Suppose we have a table containing numerical data, including positive and negative numbers. We want to calculate the absolute value of all negative numbers. The following SQL statement can be used:

SELECT ABS(value) as absolute_value
FROM my_table
WHERE value < 0;

Assuming the table data is as follows:

id value
1 10
2 -5
3 -8
4 15

Running the above SQL statement will return the following result:

absolute_value
5
8

Example 2: Calculating the Distance Between Two Points

Suppose we have a table containing x and y coordinate data, with each row representing the coordinates of a point. We want to calculate the distance between the points. The following SQL statement can be used:

SELECT ABS(SQRT((x1 - x2)^2 + (y1 - y2)^2)) as distance
FROM my_table;

Assuming the table data is as follows:

id x1 y1 x2 y2
1 0 0 3 4
2 1 2 4 6
3 3 4 5 2
4 4 3 0 0

Running the above SQL statement will return the following result:

distance
5
5.385164807134
2.828427124746
5

Conclusion

The ABS() function is a very useful mathematical function for calculating the absolute value of numeric values. It is particularly useful for calculating the absolute value of negative numbers and can be used for numerical calculations such as distance calculations.