by wefarrell · 6y ago · 0 comments
SELECT * FROM my_table WHERE my_column NOT IN (5, 6)
SELECT * FROM my_table WHERE my_column NOT IN (5, 6) AND my_column IS NOT NULL
Because "my_column NOT IN (5, 6)" will exclude NULL values.select mumu from kaka where mumu not in (5, 6) or mumu is null.
That will return everything, null included, except for 5 and 6.
But wait, there is more. If, for example, performance is the main issue here above query is quite slow. Even on an indexed table on column mumu, it will still do a full scan of the table before returning. How to improve performance in this case? Well, you use LEFT join on itself. Implementation is left as exercise for reader :D.
QUERY PLAN
---------------------------------------------------------------------
Index Scan using foo_b_idx on foo (cost=0.29..8.30 rows=1 width=8)
Index Cond: (b = 333)
The exact same query plan is generated for a query looking for nulls: QUERY PLAN
---------------------------------------------------------------------
Index Scan using foo_b_idx on foo (cost=0.29..8.30 rows=1 width=8)
Index Cond: (b IS NULL)
(That is, the condition on the scan is the only thing that differs.)(I would heavily suspect that both MSSQL and MySQL have similar behavior here; this is an easy optimization for a query planner.)