Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Decode Null Values

Tags:

sql

oracle

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?

like image 819
Arav Avatar asked Mar 15 '12 00:03

Arav


People also ask

Does decode work with NULL?

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.

How do you handle NULL in decode?

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.

How do you decode a value in SQL?

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.

What is NVL command?

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.


2 Answers

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.

like image 134
Jon Heller Avatar answered Oct 16 '22 05:10

Jon Heller


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;
like image 42
Chetter Hummin Avatar answered Oct 16 '22 04:10

Chetter Hummin