2

How do I set an empty set or null value to a default value like 1?

So far, I have this statement, but in case I get null values i want to handle that:

select case when count(*)=0 
                   then 0 
                 else 1 
                   end OUTPUT 
from TESTTBL 
where timestamp = to_char(sysdate-1, 'yyyymmdd')||'0000';
4
  • Where do you suppose to get null values? Commented Jul 20, 2011 at 22:07
  • well what if i have no values for my timestamp criteria? then count would be always 0 right? i'm just thinking in the case if i have no records. Commented Jul 20, 2011 at 22:11
  • 1
    if there are no records that fit that condition - you'll get empty recordset, not null Commented Jul 20, 2011 at 22:15
  • ok, then for empty set. How can I set an empty set to a value of 1? Commented Jul 20, 2011 at 22:17

3 Answers 3

6

Do you mean to check for Null value and set as some default, if so

select nvl(column_name,'DEFAULT') from TESTBL where timestamp = to_char(sysdate-1,   'yyyymmdd')||'0000';
Sign up to request clarification or add additional context in comments.

Comments

5
SELECT CASE WHEN EXISTS
                   ( SELECT * 
                     FROM TESTTBL 
                     WHERE timestamp = to_char(sysdate-1, 'yyyymmdd') || '0000'
                   )
            THEN 1
            ELSE 0
       END AS OUTPUT
FROM dual                     

EDIT

Added FROM dual as Oracle does not allow SELECT without FROM clause.

2 Comments

@ypercube: +1'd, but I vote for changing from SELECT * to SELECT null and for adding FROM dual in the end
I doubt there is any difference in performance. We could well use SELECT 1/0 : stackoverflow.com/questions/1597442/…
4

Here you go

SELECT DECODE(count(*),0,0,
                      1) OUTPUT
   FROM TESTTBL 
   WHERE TIMESTAMP = TO_CHAR(SYSDATE-1, 'yyyymmdd')||'0000'; 

Use Decode like

SELECT supplier_name,
        decode(supplier_id, 10000,  'Google',
                            10001,  'Microsoft'                                
                           'Sony') result
 FROM suppliers;

equivalent to

IF supplier_id = 10000 THEN
     result := 'Google';

ELSIF supplier_id = 10001 THEN
    result := 'Microsoft';

ELSE
    result := 'Sony';    
END IF;

Or Use coalesce

SELECT coalesce( address1, address2) result
FROM suppliers;

which is equivalent to

IF address1 is not null THEN
     result := address1;

ELSIF address2 is not null THEN
    result := address2;

ELSE
    result := null;

END IF;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.