null Blogs
Written by Kiprosh, team of passionate and disciplined craftsmen turning your ideas into reality.
Kiprosh is now part of LawLytics
Written by Kiprosh, team of passionate and disciplined craftsmen turning your ideas into reality.
In the previous article, we went through How NOT IN works with NULL values. We also learned how we can overcome this restriction. In this article, we will look at alternative ways to handle NULL values with SQL functions. So basically when we use != or NOT IN in query, it ignores the records with NULL values for fields. User.where("state != ?", 'active') SELECT * FROM users WHERE state != 'active' OR User.where("state NOT IN (?)", ['active']) SELECT * FROM users WHERE state NOT IN ('active') The above queries will consider records with state having a NOT NULL value,
Recently I faced one scenario with NULL value with NOT IN, I have added the details here about what I learnt. suppose we have two table Category and Product Category id | name -------- 1 | Category 1 2 | Category 2 3 | Category 3 4 | Category 4 Product id | name | category_id ----------------------------- 1 | Product 1 | 1 2 | Product 2 | 2 3 | Product 3 | 2 4 | Product 4 | 3 5 | Product 5 | 4 6 | Product 6 | NULL Scenario :- *I just want to retrieve all the Products excluding Category 1 and Category 3 so I wrote following query :- Product.joins(:category)