MySQL ABS

The ABS function in MySQL is a mathematical function that stands for “absolute value.” Its primary purpose is to return the absolute value of a numeric expression. The absolute value of a number is its distance from zero on the number line, regardless of its direction. In other words, it gives the positive value of the number.

Syntax

Here is the basic syntax of the ABS function in MySQL:

ABS(number);

number: This is the numeric expression for which you want to calculate the absolute value.

Example

Let’s consider a simple example to illustrate the usage of the ABS function. Assume you have a table named numbers with a column named value:

CREATE TABLE numbers (
    id INT PRIMARY KEY,
    value INT
);

INSERT INTO numbers VALUES 
(1, 10), (2, -5), (3, 7), (4, -12);

Now, if you want to retrieve the absolute values of the value column, you can use the ABS function:

SELECT 
id, value, 
ABS(value) AS absolute_value
FROM numbers;

This query will produce the following result:

+----+-------+----------------+
| id | value | absolute_value |
+----+-------+----------------+
|  1 |    10 |             10 |
|  2 |    -5 |              5 |
|  3 |     7 |              7 |
|  4 |   -12 |             12 |
+----+-------+----------------+

As shown in the result, the ABS function returns the absolute values of the numbers in the value column.

In summary, the ABS function in MySQL is a useful tool for obtaining the absolute value of a numeric expression, which can be particularly handy when working with numerical data in various database applications.