0

How do I get not-null results from a sub query in SELECT statement?

SELECT a, b, c,
       (SELECT d 
        FROM table2
        WHERE ...) as d
FROM table 1
WHERE ...

I want to get results only when all values (a, b, c , d) not Null. It won't be kind of weird/non-efficient to use the same sub-query in main WHERE clause as well but with EXISTS?

SABER
  • 373
  • 6
  • 17
Agenobarb
  • 143
  • 2
  • 10

3 Answers3

3

The easiest way to do this is to put your original query in a subquery, then you can check whether the whole row that the subquery returns is NULL:

SELECT *
FROM (
    SELECT a, b, c,
           (SELECT d 
            FROM table2
            WHERE ...)
    FROM table 1
    WHERE ...
) AS sub
WHERE sub IS NOT NULL

sub being the row of (a,b,c,d) returned by the subquery.

404
  • 8,022
  • 2
  • 27
  • 47
0
SELECT 
 t1.a,
 t1.b,
 t1.c, 
 t2.d
FROM table1 t1
left join table2 as t2 on t2.ID = t1.ID
WHERE t1.a is not null and t1.b is not null and t1.c is not null and t2.d is not null
Vaso Miruashvili
  • 101
  • 1
  • 11
  • While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context. – Robert Columbia Oct 31 '18 at 15:51
0

You can use a subquery:

select a, b, c, d
from (SELECT a, b, c,
             (SELECT d 
              FROM table2
              WHERE ...) as d
      FROM table 1
      WHERE ... and
            a is not null and b is not null and c is not null
     ) x
where d is not null;

In all likelihood, though, you can use JOIN:

SELECT a, b, c, x.d 
FROM table 1 JOIN
      (SELECT d 
        FROM table2
        WHERE ...
     ) x
WHERE ... and
      a is not null and b is not null and c is not null and d is not null;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786