Topic 18 of 52 · Beginner
SELECT, WHERE & Sorting
Filter rows, handle NULLs, sort and limit results.
Concept
SELECT picks columns, WHERE filters rows, ORDER BY sorts and LIMIT caps the number returned.
Useful filters: comparison operators, BETWEEN, IN, LIKE ('A%' starts with A, '_' one char) and IS NULL.
NULL means unknown, so NULL = NULL is not true. Always use IS NULL / IS NOT NULL, and COALESCE to replace NULLs.
Code (SQL · MySQL 8)
SELECT name, city
FROM customers
WHERE city IN ('Hyderabad', 'Chennai')
AND email LIKE '%@mail.com'
AND phone IS NULL
ORDER BY name ASC
LIMIT 10 OFFSET 0;
SELECT name, COALESCE(phone, 'not given') AS phone FROM customers;Remember
- Use IS NULL, never = NULL.
- DISTINCT removes duplicate rows from the result.
- LIMIT n OFFSET m is used for pagination.
Interview questions
Why does WHERE col <> 'x' skip NULL rows?
Comparing NULL to anything gives UNKNOWN, which WHERE treats as false. Add OR col IS NULL to include them.
What is the logical order of a SELECT?
FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT.
Lesson test
Take an 8-question test on “SELECT, WHERE & Sorting” — concepts, output prediction, bug spotting and interview questions.