Lesson

MySQL SIGN() Function

10 min reading
Free Course

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 FLOAT or DOUBLE columns like 0.1 + 0.2 - 0.3 can yield 5.55e-17, making SIGN() return 1 instead of 0. Round float differences before calling SIGN(), or store exact amounts as DECIMAL.
  • Expecting boolean true/false: SIGN() returns -1, 0, or 1—three distinct integers, not 0/1 booleans.
  • NULL inputs: Passing NULL to SIGN(NULL) returns NULL.

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.

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