Oracle study notes: nvl, nvl2, nullif, decode function

A, nvl function

Function: Returns the two expressions from a non-NULL value.

grammar:

select nvl(expression1, expression2)
-- 如果 expression1 计算结果为 null,则返回 expression2
-- 任意一种数据类型
-- 如果 expression1、expression2 都为null则返回null

select nvl(null, 1) from dual;
-- 1

Return Value Type: character, date, time-of-date, numeric, money, logical, or a null value.

Both expressions must be the same data type.

Two, nvl2 function

grammar:

select nvl2(expression1, expression2, expression3)
-- expression1 不为null则返回 expression2
-- expression1 为null则返回 expression3

Different types expression2 and expression3 case, data type cast expression2.

select nvl2(expr, 1, 0) from dual;

Three, nullif function

grammar:

select nullif(100, 200)
-- 100

Description: equal returns null, returns ranging from expression1.

Four, decode function

SQL statements are no logical determination (branch statements), decode function can accomplish similar functions.

grammar:

select decode(条件, 值1, 返回值1, 值2, 返回值2..., 值n, 返回值n, 缺省值);
/*
IF 条件 = 值1 THEN
    RETURN(返回值1)
ELSIF 条件 = 值2 THEN
    RETURN(返回值2)
    ......
ELSIF 条件 = 值n THEN
    RETURN(返回值n)
ELSE
    RETURN(缺省值)
END IF
*/

Application : binding lpadcomplement function, so that the value of the primary key can be automatically incremented by 1 and 0s.

select lpad(decode(count(id), 0, 1, max(to_number(id)+1)), 14, '0') as col from dual;

Application : gender statistics.

select decode(sex, '男', 1, 0), decode(sex, '女', 1, 0) from table_name;

Application : order by characters of a particular sort.

select * from table_name
order by decode(subject_name, '语文', 1, '数学', 2, '英语', 3);

Guess you like

Origin www.cnblogs.com/hider/p/12466170.html