Choosing columns#
List the columns you want, separated by commas, in the order you want them:
Prefer naming columns over SELECT * in real applications - the query is clearer, faster, and does not break when someone adds a column to the table.
Expressions and aliases#
You can compute new values in SELECT. AS gives a column a readable name (an alias):
|| joins text in SQLite and PostgreSQL. MySQL uses CONCAT(name, ' (', city, ')').
DISTINCT - remove duplicates#
WHERE - filter rows#
WHERE keeps only rows for which the condition is true:
Comparison operators: =, <> or != (not equal), >, <, >=, <=.
WHERE एक छलनी (filter) की तरह है - सिर्फ़ वही rows दिखती हैं जिनके लिए शर्त सच हो। Text values हमेशा single quotes में लिखें: 'Indore'। "बराबर नहीं" के लिए <> या != लिखते हैं।
Combining conditions: AND, OR, NOT#
AND is evaluated before OR. Without the brackets, city = 'Bhopal' OR city = 'Ujjain' AND year = 1 would mean "everyone from Bhopal, plus first-years from Ujjain". Use brackets whenever you mix them.
BETWEEN and IN#
BETWEEN a AND bincludes both ends.IN (...)is a short form of severalORconditions.
LIKE - pattern matching#
| Pattern | Matches |
|---|---|
'A%' |
starts with A |
'%a' |
ends with a |
'%sh%' |
contains "sh" |
'_a%' |
second letter is a |
'____' |
exactly 4 characters |
In SQLite and MySQL, LIKE ignores upper/lower case for English letters by default. In PostgreSQL it is case-sensitive; use ILIKE there for case-insensitive matching.
NULL - missing values#
NULL means "no value / unknown". It is not zero and not an empty string. Any comparison with NULL using = gives "unknown", so such rows are never returned. Use IS NULL and IS NOT NULL:
The last query returns no rows even though three emails are missing - a very common mistake.
The order SQL runs a query#
You write SELECT ... FROM ... WHERE ..., but the database evaluates it as:
FROM- pick the tableWHERE- filter rowsSELECT- choose and compute columns
That is why a column alias defined in SELECT cannot be used in WHERE of the same query.
Summary#
SELECT col1, col2 FROM tablepicks columns;ASrenames; expressions compute new columns.DISTINCTremoves duplicates.WHEREfilters with=,<>,>,AND,OR,NOT,BETWEEN,IN,LIKE.- Use
IS NULL/IS NOT NULLfor missing values - never= NULL.