SQL basics: querying, NULL, joins and grouping
SQL describes what data you want, not how to fetch it. A query reads rows from tables, filters them, optionally groups them, and returns a result set. These notes use portable ANSI SQL; anything specific to SQL Server (T-SQL) is called out.
SELECT, WHERE, ORDER BY
SELECT last_name, first_name
FROM employees
WHERE dept = 'IT'
ORDER BY last_name DESC, first_name;WHEREkeeps only rows for which the condition is TRUE.ASC/DESCapplies to the column it follows; the default isASC. Later columns only break ties.- Without
ORDER BY, the order of rows is not guaranteed, however stable it looks. - String literals use single quotes:
'Ona'. In standard SQL double quotes mark an identifier, so"Ona"means "the column named Ona".
Handy filters: LIKE, IN, BETWEEN
LIKE:%matches any number of characters (including none),_matches exactly one.'_an%'matches Hanna and Danas, but not Ana.country IN ('LT', 'LV')is shorthand forcountry = 'LT' OR country = 'LV';NOT IN (...)means "different from every value".BETWEEN 10 AND 20includes both ends:>= 10 AND <= 20. The lower bound comes first.
NULL means "unknown"
NULL is not a value; it marks a missing one. Comparing anything with NULL using =, <>, < and so on gives UNKNOWN, and WHERE drops UNKNOWN rows.
WHERE manager_id = NULL -- never matches anything
WHERE manager_id IS NULL -- correct
WHERE status <> 'paid' -- rows with NULL status are NOT returnedThat last line catches many people: a row with an unknown status is neither "paid" nor "not paid". If you want it, add OR status IS NULL. COALESCE(x, default) replaces NULL with a value you choose.
Arithmetic with NULL gives NULL: 1000 + NULL is NULL.
Aggregates and NULL
Aggregate functions (SUM, AVG, MIN, MAX, COUNT(col)) skip NULL inputs.
| Expression | What it counts |
|---|---|
COUNT(*) |
rows, whatever they contain |
COUNT(dept) |
rows where dept is not NULL |
COUNT(DISTINCT dept) |
distinct non-NULL values |
COUNT never returns NULL; with nothing to count it returns 0. SUM(salary + bonus) skips rows where bonus is NULL (because the sum per row is NULL), while SUM(salary) + SUM(bonus) does not lose the salary of the row whose bonus is NULL, so the two results can differ.
DISTINCT
SELECT DISTINCT city, country removes rows where the whole combination repeats. For DISTINCT and GROUP BY, all NULLs count as one group, so SELECT DISTINCT city returns one NULL row even though NULL = NULL is not TRUE.
Joins
SELECT c.name, COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name;INNER JOINreturns only matching pairs. Customers without orders disappear.LEFT JOINkeeps every row of the left table; when there is no match, the right side's columns areNULL.- Combined with
COUNT(o.id), a customer without orders gets 0.COUNT(*)would give 1, because the left-joined row itself exists.
GROUP BY, WHERE and HAVING
The logical order of a query is: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.
WHEREfilters rows before grouping, so it cannot use aggregates.HAVINGfilters groups after aggregation.
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE amount > 35 -- remove small rows first
GROUP BY customer_id
HAVING SUM(amount) > 100; -- then remove small groupsWHERE COUNT(*) > 2 is an error; it belongs in HAVING.
Keys
- A primary key identifies each row: unique, never
NULL, at most one per table. It may span several columns and need not be numeric. - A foreign key makes every non-
NULLvalue refer to an existing parent row. By default (NO ACTION) you cannot delete a parent row that is still referenced. A nullable foreign key column may holdNULL. SQL Server does not create an index on the foreign key column for you; add one yourself.
INSERT, UPDATE, DELETE
INSERT INTO users (id, email) VALUES (1, 'ona@example.com');
UPDATE products SET price = price * 1.1 WHERE category = 'books';
DELETE FROM orders WHERE id = 42;- Columns missing from the
INSERTlist get theirDEFAULT, orNULL. If such a column isNOT NULLwithout a default, the insert fails. Always write the column list. UPDATEandDELETEwithoutWHEREaffect every row. Run aSELECTwith the sameWHEREfirst, and do risky changes inside a transaction.