Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using decode to check for negative and positive values

Tags:

sql

Hi is there a way to use decode to check for positive and negative values in sql?

e.g.

select decode(money_return, **<0**, abs(money_return), **>0**, 
money_return*10, money_return) from cash_t;

if the logic is coded in if else statement it will be something like this:

if(money_return<0){money_reutrn = abs(money_return);}
else if(money_return>0){money_reutrn = money_return*10;}
else {money_return = money_return;}
end

Thank you.

like image 410
user1872384 Avatar asked Dec 26 '12 07:12

user1872384


People also ask

How do you check if a value is positive or negative in SQL?

In SQL Server, the T-SQL SIGN() function returns the sign of a number. In other words, it indicates whether or not the value is a positive number, a negative number, or zero. You provide the number as an argument when calling the function.

How do I use decode?

DECODE compares the expression to each search value one by one. If expression is equal to a search, then the corresponding result is returned by the Oracle Database. If a match is not found, then default is returned. If default is omitted, then Oracle returns null.

What is use of decode function in Oracle?

DECODE compares expr to each search value one by one. If expr is equal to a search , then Oracle Database returns the corresponding result . If no match is found, then Oracle returns default . If default is omitted, then Oracle returns null.

How do you write a decode function?

The basic syntax for writing DECODE function in SQL is as follows: DECODE (expression , search_1, result_1[, search_2, result_2], ...,[,search_n,result_n] [, default]); The parameters used in the above mentioned syntax are: expression: expression argument is the value which is to be searched and compared with.


3 Answers

You can use 'sign' with a decode. Sign will return -1 for any negative, 0 for 0, and 1 for any positive:

select decode(sign(money_return), -1, abs(money_return), 
                                   1, money_return*10, 
                                   money_return) 
from cash_t;
like image 105
Damienknight Avatar answered Sep 28 '22 07:09

Damienknight


You need case statement

select CASE 
 WHEN money_return < 0 THEN abs(money_return)
 WHEN money_return > 0 THEN money_return*10
 ELSE money_return END money_return from cash_t;
like image 38
rs. Avatar answered Sep 28 '22 06:09

rs.


Use SIGN(). It returns "0" for 0, "1" for positive and "-1" for negative values.

SELECT
    DECODE(
        SIGN(money_return),
        0,
        money_return,
        1,
        money_return * 10,
        - 1,
        ABS(money_return)
    )
FROM
    CASH_T;
like image 35
Volker Bach Avatar answered Sep 28 '22 05:09

Volker Bach