JournalSQLFiltering and sets2 min
What You Do Not Know About OR, IN, and NOT IN
Suppose we have a table named kids, and we want to get the names of the kids who are causing trouble and breaking toys.
- OR
- IN
- NOT IN
Suppose we have a table named kids, and we want to get the names of the kids who are causing trouble and breaking toys.
From my life experience, any kid named Zeyad, Yousef, or Omar tends to be mischievous by nature 馃檪
Using OR
So right now we will try to get information about any kid whose name is one of those names I mentioned.
We write:
SELECT *
FROM kids
WHERE name = 'Omar'
OR name = 'Zeyad'
OR name = 'Yousef'I used the OR operator because if any of these 3 conditions is met, it returns their data.
Of course, it is not great practice to write multiple conditions on the same column name鈥攖here is something better (in terms of simplifying the code).
Using IN
If we want to convert the query we wrote above from OR to IN, simply as you know, we write:
SELECT *
FROM kids
WHERE name IN ('Omar', 'Zeyad', 'Youssef')Because IN is followed by a set of values, which can contain one or more elements鈥攊t doesn't matter.
Using NOT IN
Now, also from my life experience, any kid named Mohamed or Karim is calm by nature and not a troublemaker 馃檪
So we will definitely need to write a query to pull all data about kids whose names are not Mohamed or Karim. We write:
SELECT *
FROM kids
WHERE name NOT IN ('Mohamed', 'Karim')What you might not have noticed is that NOT IN can return unexpected behavior with NULL values (or fail to return rows if NULL is present in the list), and that's definitely not what we want.
The solution to this is to write:
SELECT *
FROM kids
WHERE name NOT IN ('Mohamed', 'Karim', NULL)(Note: In SQL three-valued logic, including NULL in a NOT IN list actually causes NOT IN to evaluate to UNKNOWN/false for all rows鈥攂e careful with NULLs in NOT IN!)
The Difference Between IN and OR
There is no difference in the output that each one produces, as we saw. And there is no difference in execution speed (performance); both are exactly the same.