I have the below query. When type_id is null
I want it to be grouped by the name "unknown".
How can I do it.
I know there is a decode function but I'm not sure how to use it.
select type_id,
name
from test_table
group by decode(type_id,'Unknown'),
name;
how can I do it?
The DECODE function is not specifically for handling null values, but it can be used in a similar way to the NVL function, as shown by the following example.
The DECODE function returns a value that is the same datatype as the first result in the list. If the first result is NULL, then the return value is converted to VARCHAR2. If the first result has a datatype of CHAR, then the return value is converted to VARCHAR2. If no matches are found, the default value is returned.
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.
The NVL function accepts two arguments: the first argument takes the name of the expression to be evaluated; the second argument specifies the value that the function returns when the first argument evaluates to NULL. If the first argument does not evaluate to NULL, the function returns the value of the first argument.
select decode(type_id, null, 'Unknown', type_id), name, count(*)
from
(
select 'asdf' type_id, 'name1' name from dual union all
select 'asdf' type_id, 'name2' name from dual union all
select null type_id, 'name3' name from dual
) test_table
group by type_id,name;
I agree with @sql_mommy that CASE
would probably look better. But I disagree about using TechOnTheNet as your primary source of information. You are usually better off with the official documentation, and the page for DECODE is a good example of why.
DECODE
has some strange behavior: "In a DECODE function, Oracle considers two nulls to be equivalent." That behavior is not mentioned in the TechOnTheNet article.
For null, we have the NVL function. It can be used as follows
select nvl(type_id,'Unknown'),name from test_table group by
type_id,name;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With