SQL ยท Chapter 12 of 42
SQL IN & BETWEEN
IN checks if a value matches any in a list. BETWEEN checks a range (inclusive on both ends).
IN with subquery
IN can accept a SELECT: `WHERE user_id IN (SELECT id FROM active_users)`.
NOT variants
`NOT IN (list)` and `NOT BETWEEN a AND b` invert the check.
Example 1 (sql)
SELECT * FROM users WHERE country IN ('India','USA','UK');Output
matching rowsMatch any of the listed countries.
Example 2 (sql)
SELECT * FROM orders WHERE total BETWEEN 100 AND 500;Output
orders 100..500 inclusiveBETWEEN is inclusive.
Key points
- IN = 'value in this list?'
- BETWEEN a AND b โ inclusive.
- IN can take a subquery.
- NOT IN with NULLs can be surprising.
๐ก Note: `NOT IN` returns NO rows if the list contains a NULL โ a classic pitfall. Use NOT EXISTS instead.
