SELECT, filtering and sorting
🏠The everyday picture
Asking the register clerk: "Show me names and phone numbers of customers in Patna who joined this year, newest first, just the first ten."
📘What it really is
SELECT name, phone, joined_on
FROM customers
WHERE city = 'Patna'
AND joined_on >= '2026-01-01'
ORDER BY joined_on DESC
LIMIT 10;
-
SELECTlists the columns;FROMthe table;WHEREfilters rows;ORDER BYsorts (ASCorDESC);LIMITcaps the number of rows (withOFFSETfor pages, Module 47). -
Conditions in
WHERE: - comparisons:
=,<>(not equal),<,>,<=,>=; - combine with
AND,OR,NOT, and brackets to be clear; IN ('Patna', 'Gaya'): one of a list;BETWEEN 100 AND 500: a range, including both ends;LIKE 'As%': text patterns (%means any characters); case rules differ between databases (ILIKEin PostgreSQL ignores case);-
IS NULL/IS NOT NULL(Module 52). -
Aliases rename columns in the result:
SELECT name AS customer_name. SELECT DISTINCT city FROM customers;lists each city once.
🖱️Try it
Write queries for: customers from Patna or Gaya, sorted by name; customers whose name starts with "R"; customers with no email; the five most recently joined customers; the list of distinct cities.
✅Quick check
What's the difference between WHERE and ORDER BY?
Show the answer
WHERE chooses which rows appear; ORDER BY sorts them.
How do you find customers whose email is missing?
Show the answer
WHERE email IS NULL.
