SP
← SQL
JuniorSQL

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;
  • WHERE keeps only rows for which the condition is TRUE.
  • ASC/DESC applies to the column it follows; the default is ASC. 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 for country = 'LT' OR country = 'LV'; NOT IN (...) means "different from every value".
  • BETWEEN 10 AND 20 includes 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 returned

That 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 JOIN returns only matching pairs. Customers without orders disappear.
  • LEFT JOIN keeps every row of the left table; when there is no match, the right side's columns are NULL.
  • 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.

  • WHERE filters rows before grouping, so it cannot use aggregates.
  • HAVING filters 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 groups

WHERE 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-NULL value 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 hold NULL. 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 INSERT list get their DEFAULT, or NULL. If such a column is NOT NULL without a default, the insert fails. Always write the column list.
  • UPDATE and DELETE without WHERE affect every row. Run a SELECT with the same WHERE first, and do risky changes inside a transaction.
Practise this level
20 questions
Practise →