// math reference

SQL ABS function

Returns the magnitude of a number without its sign: ABS(-42) is 42. It is mostly used to measure how far apart two values are, whichever is bigger.

Catégorie
Math
Returns
same type as the input
In this category
4 of 82

Syntaxe

ABS(number)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Oui Supported under this name.
MySQL Oui Supported under this name.
SQLite Oui Supported under this name.
Oracle Oui Supported under this name.

Exemples

Any engine

SELECT ABS(-42) AS magnitude;  -- 42

Any engine

SELECT ABS(actual - forecast) AS miss
FROM projections
ORDER BY miss DESC;

Bon à savoir

  • The most negative integer has no positive counterpart in its type: ABS of an int -2147483648 raises an overflow error on SQL Server and PostgreSQL. MySQL promotes it to BIGINT and returns 2147483648, but errors on the most negative BIGINT; SQLite raises 'integer overflow' there too.
  • ABS(actual - forecast) loses the direction of the miss. Keep the signed difference too when over and under mean different things.
  • It returns the input type: ABS of an int stays an int, of a numeric stays numeric.

Questions about ABS

What does ABS do with a negative number?

Drops the sign: ABS(-5) is 5. For integer types, the single most negative value (such as -2147483648 for int) has no positive counterpart and raises an overflow error on most engines.

Does ABS work on decimals and money types?

Yes, and it preserves the type. ABS of a DECIMAL column stays DECIMAL. No precision surprises.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.