Sam Luther
Sam Luther

Reputation: 1190

How to deal with subquery returning null

I only want to run the parent select if the subselect is not null. Unsure how to achieve this using sql query :-

SELECT * from schools 
    WHERE `district_id` =
    (SELECT district_id from schools WHERE `school_id` = '0023194')

Upvotes: 0

Views: 1506

Answers (3)

Kunal
Kunal

Reputation: 229

you should run your sql query like ...

SELECT * from schools 
WHERE `district_id` = 
(SELECT district_id from schools 
    WHERE `school_id` = '0023194'
    AND 
    district_id IS NOT NULL) 
AND district_id IS NOT NULL

district_id IS NOT NULL to prevent district_id not null

Upvotes: 1

Safwan Shaikh
Safwan Shaikh

Reputation: 546

You can use IN operator because IN operator allows you to specify multiple values in a WHERE clause.

IN operator is a shorthand for multiple OR conditions. In your condition, = compares only one condition but if you have multiple record of this school_id, = can't evaluate it.

SELECT * from schools WHERE `district_id` in (SELECT district_id from schools WHERE `school_id` = '0023194')

Upvotes: 1

Md. Suman Kabir
Md. Suman Kabir

Reputation: 5453

Seems you just need to use IN like below :

SELECT * from schools 
WHERE `district_id` in
(SELECT district_id from schools WHERE `school_id` = '0023194')

SQL HERE

Upvotes: 2

Related Questions