// math reference

SQL unary minus

Negates a numeric value: -x is 0 - x for numbers, and binds tighter than every binary arithmetic operator.

Category
Math
Returns
same type as the input
In this category
54 of 82

Syntax

-x
+x
-(a * b)

Each block is a separate form. The support table and the examples show which engine takes which.

Engine support

EngineSupportNotes
SQL Server Yes Supported under this name.
PostgreSQL Yes Supported under this name.
MySQL Yes Supported under this name.
SQLite Yes Supported under this name.
Oracle Yes Supported under this name.

Examples

Any engine

SELECT -5 AS neg, -(-5) AS double_neg, +5 AS plus;  -- -5, 5, 5

SQL Server

SELECT -balance AS debit_view
FROM ledger;

PostgreSQL

SELECT -2 ^ 2 AS four, -(2 ^ 2) AS minus_four;  -- 4, -4: unary minus binds first

Good to know

  • Unary minus binds before every binary operator, including PostgreSQL's ^: -x ^ 2 is (-x) ^ 2, so it gives 4 for x = 2. Write -(x ^ 2) for -4.
  • The smallest BIGINT, -9223372036854775808, has no positive counterpart, so negating it or taking ABS raises 'bigint out of range' on PostgreSQL and an arithmetic overflow on SQL Server. SQLite's ABS raises 'integer overflow', while its unary minus quietly returns a float.
  • Double unary minus is legal: SELECT -(-5) returns 5. A unary minus before a column is the usual way to negate a whole expression.

Questions about -

What does unary minus do to a column?

Negates every non-null value: SELECT -balance flips the sign column-wide. NULL stays NULL, because negation of unknown is unknown.

Why does ABS of the smallest bigint overflow?

Two's-complement integers hold one more negative than positive value: ABS(-9223372036854775808) has no representable positive counterpart, so SQL Server, PostgreSQL and SQLite raise an overflow error.

Does unary minus bind before or after multiplication?

Before, on every engine: -2 * 3 is (-2) * 3. It also binds before PostgreSQL's ^, which is why -2 ^ 2 is 4 there.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.