Friday, December 20, 2024

MySQL SIGN() Function

 The SIGN() function in MySQL is used to return the sign of a number. It returns an integer that indicates whether the given number is positive, negative, or zero.

Syntax:

SIGN(number)

Parameters:

  • number: The number whose sign is to be determined. It can be a positive number, negative number, or zero.

Return Values:

  • Returns 1 if the number is positive.
  • Returns -1 if the number is negative.
  • Returns 0 if the number is zero.

Example:

SELECT SIGN(10);   -- Output: 1
SELECT SIGN(-10);  -- Output: -1
SELECT SIGN(0);    -- Output: 0

Usage:

You can use the SIGN() function in various SQL queries, including comparisons or as part of more complex expressions.

Example with a CASE statement:

SELECT 
    number,
    CASE
        WHEN SIGN(number) = 1 THEN 'Positive'
        WHEN SIGN(number) = -1 THEN 'Negative'
        ELSE 'Zero'
    END AS number_sign
FROM numbers;

This query would categorize each number in the numbers table as either "Positive", "Negative", or "Zero" based on its sign.

No comments:

Post a Comment