// math reference

SQL SIGN function

Returns -1, 0 or 1 depending on the input's sign. Applied to a difference, it says behind, level or ahead.

Catégorie
Math
Returns
-1, 0 or 1, in the input's type on SQL Server and PostgreSQL
In this category
9 of 82

Syntaxe

SIGN(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 SIGN(-19.5) AS direction;  -- -1

Any engine

SELECT region, SIGN(actual - target) AS direction, COUNT(*) AS reps
FROM quotas
GROUP BY region, SIGN(actual - target);

Bon à savoir

  • The value is always -1, 0 or 1, but the type can follow the input: SIGN(-19.5) is -1.0 (decimal) on SQL Server and a numeric on PostgreSQL, and an integer on MySQL and SQLite.
  • SIGN of NULL is NULL, not 0.
  • SIGN is a core function in SQLite, available even in builds without the math functions.
  • SUM(SIGN(actual - target)) is rows ahead minus rows behind. To count rows ahead, use SUM(CASE WHEN actual > target THEN 1 ELSE 0 END).

Questions about SIGN

What does SIGN(0) return?

0. SIGN returns -1, 0 or 1, and only returns NULL when the input is NULL.

How do SIGN and ABS relate?

ABS keeps the magnitude and SIGN keeps the direction, and multiplying them gives the original number back: SIGN(x) * ABS(x) = x.

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.