How the ABS() function works in Mariadb?
The ABS()
function in MariaDB is a straightforward yet essential mathematical function used to return the absolute value of a number.
The ABS()
function in MariaDB is a straightforward yet essential mathematical function used to return the absolute value of a number, which means it converts any negative number to its positive equivalent.
Syntax
The syntax for the MariaDB ABS()
function is as follows:
ABS(number)
The number
parameter is the numeric value for which you want to find the absolute value. The function returns the absolute value of number
.
Examples
Absolute Value of a Positive Number
To illustrate the use of ABS()
with a positive number:
SELECT ABS(5);
5
The output is 5, as the absolute value of a positive number is the number itself.
Absolute Value of a Negative Number
This example demonstrates the ABS()
function with a negative number:
SELECT ABS(-5);
5
The output is 5, showing how ABS()
converts a negative number to its positive equivalent.
Absolute Value of Zero
Applying ABS()
to zero yields:
SELECT ABS(0);
0
The output is 0, as the absolute value of zero is zero.
Absolute Value in an Arithmetic Expression
Using ABS()
in an arithmetic expression:
SELECT ABS(-5 + 3);
2
The output is 2, which is the absolute value of the result of the expression -5 + 3
.
Absolute Value from a Table Column
If we need to use ABS()
on a table column, we first create a simple table:
DROP TABLE IF EXISTS numbers;
CREATE TABLE numbers (value INT);
INSERT INTO numbers (value) VALUES (-5), (3), (0);
Then, we can apply ABS()
to the column:
SELECT ABS(value) FROM numbers;
5
3
0
This returns the absolute values of the numbers in the value
column.
Related Functions
Here are a few functions related to MariaDB’s ABS()
:
- MariaDB
CEIL()
function is used to round up a number to the nearest integer. - MariaDB
FLOOR()
function rounds down a number to the nearest integer. - MariaDB
ROUND()
function is used to round a number to a specified number of decimal places.
Conclusion
The ABS()
function is a fundamental part of numerical operations in MariaDB, providing a simple way to work with the absolute values of numbers. Its usage is crucial in scenarios where only the magnitude of a number is needed, irrespective of its sign. Whether you’re working with raw numbers or data from tables, ABS()
is an indispensable tool in your SQL toolkit.