Lesson

MySQL ABS() Function

10 min reading
Free Course

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 NULL to ABS(NULL) returns NULL. Wrap nullable columns with COALESCE(col, 0) if you need 0 instead.
  • Minimum BIGINT overflow: On 64-bit signed integers, ABS(-9223372036854775808) throws an out-of-range error because +9223372036854775808 exceeds BIGINT max (9223372036854775807). Cast the column to DECIMAL(20, 0) first when handling extreme values.
  • Unindexed WHERE filters: Calling ABS(col) inside a WHERE clause prevents MySQL from using a standard index on col. Use a range condition like col >= 5 OR col <= -5 on 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum