Thursday, December 26, 2024

SQL Server ABS() Function

 The ABS() function in SQL Server returns the absolute value of a given number. The absolute value of a number is its distance from zero, regardless of its sign (positive or negative).

Syntax:

ABS(number)
  • number: The numeric value for which you want to calculate the absolute value. This can be any valid numeric data type (integer, decimal, float, etc.).

Example Usage:

1. Basic Example:

SELECT ABS(-5) AS AbsoluteValue; -- Returns 5
SELECT ABS(3.14) AS AbsoluteValue; -- Returns 3.14
SELECT ABS(0) AS AbsoluteValue; -- Returns 0

2. Using ABS() in a Table Query:

Suppose you have a table named Transactions with a column Amount containing positive and negative numbers.

SELECT Amount, ABS(Amount) AS AbsoluteAmount
FROM Transactions;

Output:

Amount AbsoluteAmount
-200 200
150 150
-50 50

3. Using ABS() in a Calculation:

SELECT ABS(SUM(Balance)) AS TotalAbsoluteBalance
FROM Accounts;

This would calculate the absolute value of the sum of all balances in the Accounts table.

The ABS() function is particularly useful when you need to work with magnitude values while ignoring their signs.

No comments:

Post a Comment