Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a select statement return null if no value is returned?

Tags:

sql

oracle

Let's say we have the table "letters" like so:

a | b  
-----  
0 | 0  
0 | 1  
1 | 0  
1 | 1

And the following select statement:

SELECT val1, val2, x.a. val3
  FROM table1, 
       table2, 
       (SELECT a 
          FROM letters 
         WHERE a=b 
           AND a=0) x, 
       table3
 WHERE table1.val1 = table2.val1
   AND table1.val2 = table3.val3

I need the embeded SELECT statement (x) to return:

0  
NULL  
NULL  
NULL 

Instead of what is currently returning which is

0  

Then I want to be able to use that in the big SELECT statement. I hope this makes sense!

like image 878
Crates Avatar asked Aug 07 '15 13:08

Crates


1 Answers

There's a couple of ways you can go about this;

Trivial, using the CASE statement;

SELECT
    CASE 
        WHEN a = b AND a = 0 THEN a
        ELSE NULL
    END
FROM x

Returns:

0
NULL
NULL
NULL

Using a LEFT JOIN:

SELECT  X1.a
FROM    x 
LEFT JOIN   (SELECT a, b FROM x WHERE a = b AND a = 0) AS X1 ON x.a = X1.a AND x.b = X1.b

Returns:

0
NULL
NULL
NULL
like image 195
dash Avatar answered Oct 12 '22 12:10

dash