BeginnerLesson 2 of 15
WHERE – Filtering Rows – SQL
Conditions, operators, LIKE, IN, BETWEEN, and dealing with NULL.
WHERE keeps only rows for which the condition is true. Comparison operators: =, <> (or !=), <, >, <=, >=. You combine several conditions with AND, OR, NOT – always use parentheses when mixing them.
SELECT name, stadt FROM kunden WHERE stadt = 'Berlin';
SELECT * FROM produkte WHERE preis > 20 AND kategorie <> 'Bücher';
SELECT * FROM produkte WHERE (kategorie = 'Möbel' OR kategorie = 'Bücher') AND preis < 100;Handy shorthands: IN for lists, BETWEEN (inclusive of both bounds) for ranges, and LIKE for patterns (% = any number of characters, _ = exactly one).
SELECT * FROM produkte WHERE kategorie IN ('Elektronik', 'Möbel');
SELECT * FROM produkte WHERE preis BETWEEN 25 AND 150; -- 25 and 150 are included
SELECT * FROM kunden WHERE name LIKE 'A%'; -- starts with A
SELECT * FROM kunden WHERE name LIKE '_e%'; -- second letter is eWarningNULL means "unknown", not "empty" or 0. Any comparison with NULL yields neither true nor false, but NULL – and the row is discarded.
WHERE stadt = NULL therefore never returns anything. The correct way: IS NULL or IS NOT NULL.SELECT name FROM kunden WHERE stadt IS NULL; -- Eva
SELECT name FROM kunden WHERE stadt IS NOT NULL; -- all the others
SELECT name FROM kunden WHERE stadt <> 'Berlin'; -- Eva is missing here too!TipDialect: case sensitivity of
LIKE is insensitive in MySQL (default collation) and SQLite (ASCII only), but sensitive in PostgreSQL. PostgreSQL offers ILIKE for case-insensitive search.