I have a query that should return results that DO NOT match in the subquery. A sub query can return an empty result, so I need to set a default value (say, 0) if the auxiliary query returns an empty set to prevent IN (NULL) , which always returns another NULL.
for example
SELECT * FROM example_table WHERE id NOT IN (subquery_that_selects_ids)
subquery_that_selects_ids can return a set of integers, i.e. (1,2,5,6) or an empty set if the subquery does not find the corresponding results.
COALESCE does not work here, since a sub-query is likely to return more than one result.
Solutions should work in SQLite or postgresql. How can I prevent a subquery from returning an empty set?
Everyone tells me that the request should work as written. And you are all right. The request is built by Rails3 AREL, as I was going to post the full request here. I noticed that AREL put NULL for an empty set when using array conditions.
those. My query on rails looked like this:
Object.where("id NOT IN (?)", Object.where(other_conditions).select(:id))
when Object.where(other_conditions) evaluates to [] ? replaced by NULL
So, I rewrite the request like this:
Object.where("id NOT IN (" + Object.where(other_conditions).select(:id).to_sql + ")")
The problem is resolved.
I do justice to @Michael Buen, but also support anyone who told me that the request will work as it is written, as they are true. Especially thanks to @OMG Ponies and @Ted Elliott!
Sooodesune
source share