MySQL ABS() Function
MySQL ABS() Function: Removing Negative Signs from Numbers
The ABS() function returns the absolute (non-negative) value of any numeric expression in MySQL. If you pass -45.50, it returns 45.50. Positive numbers and zero stay unchanged.
Developers use ABS() when calculating price gaps, inventory variances, or invoice discrepancies where only the magnitude matters. It keeps the original numeric type when possible, returning integers for integer inputs and decimals for decimal inputs.
Syntax
ABS(number)
number: Any numeric literal, column, or expression. Non-numeric strings are implicitly cast to numbers before evaluation.
Practical Example
Suppose the demo_products table tracks expected stock counts against physical warehouse counts. You want to find items with an absolute stock discrepancy of at least 5 units, regardless of whether items are missing or overstocked.
SELECT
product_id,
product_name,
expected_qty,
actual_qty,
ABS(actual_qty - expected_qty) AS stock_variance
FROM demo_products
WHERE ABS(actual_qty - expected_qty) >= 5
ORDER BY stock_variance DESC;
| product_id | product_name | expected_qty | actual_qty | stock_variance |
|---|---|---|---|---|
| 104 | USB-C Hub | 120 | 108 | 12 |
| 119 | Wireless Mouse | 85 | 93 | 8 |
| 102 | Mechanical Keyboard | 60 | 55 | 5 |
Notice how row 104 had a negative difference (108 - 120 = -12), yet ABS() turned it into 12 for clean sorting.
Common Mistakes & NULL Behavior
- NULL inputs: Passing
NULLtoABS(NULL)returnsNULL. Wrap nullable columns withCOALESCE(col, 0)if you need0instead. - Minimum BIGINT overflow: On 64-bit signed integers,
ABS(-9223372036854775808)throws an out-of-range error because+9223372036854775808exceedsBIGINTmax (9223372036854775807). Cast the column toDECIMAL(20, 0)first when handling extreme values. - Unindexed WHERE filters: Calling
ABS(col)inside aWHEREclause prevents MySQL from using a standard index oncol. Use a range condition likecol >= 5 OR col <= -5on large tables.
Frequently Asked Questions
Does MySQL ABS() change decimal precision?
No. ABS() preserves the scale and precision of DECIMAL columns. For example, ABS(-19.95) returns 19.95 as an exact decimal value.
What happens if I pass a string to ABS()?
MySQL converts the string to a floating-point number first. Passing ABS('-42abc') yields 42, while a string with no leading digits like ABS('abc') evaluates to 0.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.