In this lesson: Write filtered SELECT queries confidently.
Reading columns
SELECT * FROM students; -- every column
SELECT name, mark FROM students; -- only these two
Avoid
SELECT * in real applications. Name the columns you need. It is faster, and your code will not break when someone adds a column later.
Filtering with WHERE
SELECT name, mark FROM students
WHERE mark >= 70;
Comparison operators
= equal to
<> or != not equal to
> < greater / less than
>= <= greater / less than or equal
Combining conditions
SELECT * FROM students
WHERE country = 'Rwanda' AND mark >= 70;
SELECT * FROM students
WHERE country = 'Rwanda' OR country = 'Kenya';
-- brackets matter, exactly as in arithmetic
SELECT * FROM students
WHERE (country = 'Rwanda' OR country = 'Kenya')
AND mark >= 70;
Useful WHERE helpers
WHERE country IN ('Rwanda', 'Kenya', 'Uganda')
WHERE mark BETWEEN 70 AND 90 -- inclusive at both ends
WHERE name LIKE 'A%' -- starts with A
WHERE name LIKE '%ine' -- ends with 'ine'
WHERE name LIKE '%li%' -- contains 'li'
WHERE email IS NULL
WHERE email IS NOT NULL
NULL is not a value
NULL means "unknown". Comparing to it with = never matches — not even NULL = NULL:
WHERE email = NULL -- always matches nothing. Wrong.
WHERE email IS NULL -- correct
Aliases
SELECT name AS student_name, mark AS score
FROM students;
Removing duplicates
SELECT DISTINCT country FROM students;
-- Rwanda
-- Kenya