1. Database Basics & Querying
Filtering, Pattern Matching & NULL Safety
Write cleaner filters with IN, BETWEEN, LIKE, and DISTINCT, avoid the classic '= NULL' bug using IS NULL, and create dynamic labels with CASE WHEN.
- Simplify multi-value and range filters with IN, BETWEEN, and LIKE
- Handle missing NULL values accurately using IS NULL and COALESCE
- Create conditional labels dynamically inside queries with CASE WHEN
Once you know SELECT and WHERE, a handful of everyday keywords make your queries shorter, safer, and far more expressive.
Cleaner Filters: IN and BETWEEN
Instead of repeating OR five times:
-- Messy: WHERE category = 'Python' OR category = 'SQL' OR category = 'Git'
-- Clean:
SELECT title, category
FROM courses
WHERE category IN ('Python', 'SQL', 'Git');For numeric or date ranges (inclusive on both ends):
SELECT title, price
FROM books
WHERE price BETWEEN 200 AND 500;Searching Text with LIKE
Use % as a wildcard meaning "zero or more characters":
-- Courses containing 'Data' anywhere in the title
SELECT title
FROM courses
WHERE title LIKE '%Data%';'Py%'→ starts with"Py"'%SQL'→ ends with"SQL"'%API%'→ contains"API"anywhere
(In PostgreSQL, use ILIKE for case-insensitive matching!)
Removing Duplicates with DISTINCT
SELECT DISTINCT category
FROM courses;The NULL Trap (IS NULL vs = NULL)
In SQL, NULL does not mean zero or empty string—it means "unknown / missing value."
Because an unknown value cannot equal another unknown value, WHERE phone = NULL always returns zero rows!
-- WRONG (returns nothing):
SELECT name FROM students WHERE phone = NULL;
-- RIGHT:
SELECT name FROM students WHERE phone IS NULL;
-- Find students who DO have a phone number:
SELECT name FROM students WHERE phone IS NOT NULL;Always use IS NULL and IS NOT NULL. And use COALESCE(phone, 'Not Provided') to substitute a friendly default when displaying results.
Dynamic Labels with CASE WHEN
CASE WHEN works just like if / elif / else inside a SQL query:
SELECT
title,
estimated_hours,
CASE
WHEN estimated_hours <= 3 THEN 'Weekend Quick Course'
WHEN estimated_hours <= 7 THEN 'Medium Track'
ELSE 'Deep Dive'
END AS pacing_label
FROM courses;Try It Yourself: Live SQL CASE WHEN & COALESCE
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
You want to find all orders where shipped_at is still missing. Which WHERE condition is correct?
What does WHERE name LIKE 'A%' match?