Вы находитесь на странице: 1из 3

Home / Oracle Comparison Functions / Oracle DECODE Function

Oracle DECODE Function

Summary: in this tutorial, you will learn how to use the Oracle DECODE() function
to embed if-then-else logic in SQL queries.

Introduction to Oracle DECODE() function


The Oracle DECODE() function allows you to add the procedural if-then-else logic to
the query.

In the following example, the Oracle DECODE() function compares the first argument
(1) with the second argument (1). Because they are equal, the function returns the
second argument which is the string One.

1
2
3
4
SELECT
DECODE(1, 1, 'One')
FROM
dual;
It works like the following if statement

1
2
3
IF 1 = 1 THEN
RETURN 'One';
END IF
The following example is slightly different from the one above. The query returns a
null value because one does not equal two.

1
2
3
4
SELECT
DECODE(1, 2, 'One')
FROM
dual;
If you want to specify a default value when the first argument is not equal to the
second one, you append the default value to the argument list as shown below:

1
2
3
4
SELECT
DECODE(1, 2, 'One','Not one')
FROM
dual;
It works like the following if-then-else statement:

1
2
3
4
5
IF 1 = 2 THEN
RETURN 'One';
ELSE
RETURN 'Not one';
END IF;
What if you want to compare the first argument with a list of arguments? See the
following example:

1
2
3
4
SELECT
DECODE(2, 1, 'One', 2, 'Two')
FROM
dual;
The result is

1
Two
In this example, the function compares the first argument (2) with the second one.
If the first argument equal the second one, the function returns the third argument
(One). Otherwise, it compares the first argument with the fourth argument (2). If
they are equal, the function returns the fifth argument (Two).

It works like the following if-then-elsif statement:

1
2
3
4
5
IF 2 = 1 THEN
RETURN 'One';
ELSIF 2 = 2 THEN
RETURN 'Two';
END IF;
If you want to specify a default value when the function does not find any match,
you do it as follows:

1
2
3
4
SELECT
DECODE(3, 1, 'One', 2, 'Two', 'Not one or two')
FROM
dual;
The query returned:

1
Not one or two
The query works like the following if-then-elsif-else statement:

1
2
3
4
5
6
7
IF 3 = 1 THEN
RETURN 'One';
ELSIF 3 = 2 THEN
RETURN 'Two';
ELSE
RETURN 'Not one or two';
END IF;
Oracle DECODE() functio

Вам также может понравиться