WHERE - filtering rows#
WHERE keeps only the rows that satisfy a condition:
SELECT columns
FROM table
WHERE condition;
Comparison operators#
| Operator | Meaning | Example |
|---|---|---|
= |
equal | status = 'Delivered' |
<> or != |
not equal | status <> 'Cancelled' |
> < >= <= |
greater/less | price >= 5000 |
AND, OR, NOT#
When mixing AND and OR, use brackets. Without them AND is evaluated first:
-- probably NOT what you meant:
WHERE status = 'Cancelled' OR status = 'Returned' AND payment_mode = 'UPI'
-- clear:
WHERE (status = 'Cancelled' OR status = 'Returned') AND payment_mode = 'UPI'
IN - match any value in a list#
BETWEEN - ranges (inclusive)#
LIKE - text patterns#
| Pattern | Matches |
|---|---|
'A%' |
starts with A |
'%Laptop%' |
contains "Laptop" |
'%a' |
ends with a |
'_a%' |
second letter is a (_ = exactly one character) |
(In SQLite and MySQL, LIKE is case-insensitive for English letters; in PostgreSQL use ILIKE for that.)
IS NULL - missing values#
NULL means "no value / unknown". It is not zero or an empty string, and = NULL never matches.
NULL का मतलब है "value मौजूद नहीं / पता नहीं" - यह 0 या खाली text नहीं है।
इसलिए WHERE manager_id = NULL कभी काम नहीं करता (क्योंकि "अज्ञात" की तुलना किसी से नहीं हो सकती)। हमेशा IS NULL या IS NOT NULL लिखें।
ORDER BY - sorting#
ASC(default) = smallest/A first;DESC= largest/Z first.- Sort by several columns: first by category, then by price within each category.
LIMIT - top N#
SELECT name, price FROM products ORDER BY price DESC LIMIT 3; -- 3 most expensive
(SQL Server uses SELECT TOP 3 ...; Oracle uses FETCH FIRST 3 ROWS ONLY.)
DISTINCT - unique values#
DISTINCT applies to the whole row: SELECT DISTINCT city, state returns unique city-state pairs.
Calculated columns and aliases#
You can calculate new columns and name them with AS:
Write 100.0 (not 100) when dividing integers in SQLite/SQL Server - otherwise integer division drops decimals (7 / 2 = 3).
How SQL processes a query#
You write clauses in this order:
SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
But the database executes them in this order:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
That's why an alias created in SELECT can be used in ORDER BY, but not in WHERE (in most databases).
Summary#
WHEREfilters rows with =, <>, >, <, AND, OR, NOT, IN, BETWEEN, LIKE and IS NULL.ORDER BY ... ASC/DESCsorts;LIMITgives top N.DISTINCTreturns unique values.- Create calculated columns and name them with
AS. - Logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.