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';
Mangesh
  • 3,987
  • 2
  • 31
  • 52
jdamae
  • 3,839
  • 16
  • 58
  • 78

3 Answers3

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';
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.

ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
  • 1
    @ypercube: +1'd, but I vote for changing from `SELECT *` to `SELECT null` and for adding `FROM dual` in the end – zerkms Jul 20 '11 at 22:42
  • 1
    I doubt there is any difference in performance. We could well use `SELECT 1/0` : http://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists/1597487#1597487 – ypercubeᵀᴹ Jul 20 '11 at 22:47
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;
Mangesh
  • 3,987
  • 2
  • 31
  • 52