MySQL SIGN() Function
MySQL SIGN() Function: Detecting Positive, Negative, or Zero Values
The SIGN() function inspects a numeric expression and returns -1 if it is negative, 0 if it is zero, or 1 if it is positive. It provides a clean mathematical shortcut wherever you would otherwise write a three-branch CASE expression.
Financial ledgers, warehouse adjustments, and directional sorting queries use SIGN() to classify credits vs. debits, detect price hikes vs. drops, or group records by direction.
Syntax
SIGN(x)
x: Any numeric literal, column, or expression.
Practical Example
Suppose demo_products compares new_price against old_price. Using SIGN(new_price - old_price) tags every SKU with 1 (increase), 0 (unchanged), or -1 (discount) in a single expression.
SELECT
product_id,
product_name,
old_price,
new_price,
SIGN(new_price - old_price) AS direction_flag
FROM demo_products
WHERE product_id BETWEEN 40 AND 43;
| product_id | product_name | old_price | new_price | direction_flag |
|---|---|---|---|---|
| 40 | Laptop Sleeve | 29.99 | 24.99 | -1 |
| 41 | HDMI Adapter | 14.00 | 14.00 | 0 |
| 42 | Standing Desk | 399.00 | 429.00 | 1 |
| 43 | Webcam Cover | 9.00 | NULL | NULL |
Row 40 dropped in price (-5.00), yielding -1. Row 41 stayed identical, yielding 0. Row 43 has a NULL new price, so SIGN() returns NULL.
Common Mistakes & NULL Behavior
- Floating-point -0.0 or near-zero drift: Subtraction on
FLOATorDOUBLEcolumns like0.1 + 0.2 - 0.3can yield5.55e-17, makingSIGN()return1instead of0. Round float differences before callingSIGN(), or store exact amounts asDECIMAL. - Expecting boolean true/false:
SIGN()returns-1,0, or1—three distinct integers, not0/1booleans. - NULL inputs: Passing
NULLtoSIGN(NULL)returnsNULL.
Frequently Asked Questions
What does SIGN() return for decimal values between 0 and 1?
Any positive value, even 0.0001, returns 1. Likewise, -0.0001 returns -1. Only exact zero returns 0.
Can I use SIGN() inside GROUP BY?
Yes. GROUP BY SIGN(net_profit) is a fast way to summarize profitable (1), break-even (0), and loss-making (-1) accounts in one pass.
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.