Pick columns
basicSELECT name, course
FROM students;
List only the columns you need. SELECT * returns all of them.
Select & filter
Filter rows
basicSELECT name
FROM students
WHERE year = 2 AND course = 'Computer Science';
WHERE keeps rows where the condition is true. Combine with AND, OR, NOT.
Select & filter
Sort and limit
basicSELECT name, year
FROM students
ORDER BY year DESC, name ASC
LIMIT 5;
ORDER BY sorts; LIMIT keeps the first rows (SQL Server uses TOP).
Select & filter
Pattern, range and list tests
basicSELECT title
FROM modules
WHERE title LIKE '%Learning%'
AND credits BETWEEN 10 AND 20
AND department IN ('CS', 'Maths');
LIKE matches patterns (% = any text), BETWEEN is inclusive, IN tests membership.
Select & filter
Remove duplicates
basicSELECT DISTINCT course
FROM students;
DISTINCT keeps one copy of each combination of the selected columns.
Select & filter
Handle missing values (NULL)
intermediateSELECT name
FROM students
WHERE course IS NOT NULL;
SELECT COALESCE(course, 'Undeclared') AS course
FROM students;
NULL is not equal to anything, even NULL: use IS NULL / IS NOT NULL. COALESCE returns the first non-NULL value.
Select & filter
Compute a value
intermediateSELECT mark,
CASE
WHEN mark >= 70 THEN 'First'
WHEN mark >= 60 THEN '2:1'
WHEN mark >= 50 THEN '2:2'
WHEN mark >= 40 THEN 'Third'
ELSE 'Fail'
END AS classification
FROM grades;
CASE is SQL’s if / else-if. Conditions are checked top to bottom.
Select & filter
Count, sum, average
basicSELECT COUNT(*) AS marks,
AVG(mark) AS mean_mark,
MIN(mark) AS lowest,
MAX(mark) AS highest
FROM grades;
Aggregates collapse many rows into one. COUNT(*) counts rows; COUNT(col) skips NULLs.
Aggregate
Group by
basicSELECT course, COUNT(*) AS students
FROM students
GROUP BY course;
GROUP BY makes one output row per group. Every non-aggregated selected column must be in GROUP BY.
Aggregate
Filter groups with HAVING
intermediateSELECT module_id, AVG(mark) AS mean_mark
FROM grades
GROUP BY module_id
HAVING AVG(mark) < 50
ORDER BY mean_mark;
WHERE filters rows before grouping; HAVING filters groups after aggregation.
Aggregate
INNER JOIN
basicSELECT s.name, m.title, g.mark
FROM grades g
JOIN students s ON s.id = g.student_id
JOIN modules m ON m.id = g.module_id;
JOIN matches rows on a condition. Rows with no match on either side are dropped.
Joins
LEFT JOIN (keep unmatched rows)
intermediateSELECT s.name, COUNT(e.module_id) AS modules_taken
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
GROUP BY s.id, s.name;
LEFT JOIN keeps every row from the left table, with NULLs where nothing matched. Students with no enrolments show 0.
Joins
Find rows with no match
intermediateSELECT s.name
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE e.student_id IS NULL;
Left join then test the right side for NULL: the "anti-join". Students with no enrolments.
Joins
Self join
advancedSELECT a.name AS student, b.name AS same_course
FROM students a
JOIN students b ON a.course = b.course AND a.id < b.id;
Join a table to itself with two aliases. The a.id < b.id test lists each pair once.
Joins
Subquery in WHERE
intermediateSELECT name
FROM students
WHERE id IN (
SELECT student_id FROM grades WHERE mark >= 70
);
A subquery returns values for the outer query to test. EXISTS is often faster for "is there any match".
Subqueries & CTEs
Compare to an overall average
intermediateSELECT student_id, mark
FROM grades
WHERE mark > (SELECT AVG(mark) FROM grades);
A scalar subquery returns one value, here the average of all marks.
Subqueries & CTEs
Common table expression (WITH)
advancedWITH module_avg AS (
SELECT module_id, AVG(mark) AS mean_mark
FROM grades
GROUP BY module_id
)
SELECT m.title, a.mean_mark
FROM module_avg a
JOIN modules m ON m.id = a.module_id
ORDER BY a.mean_mark DESC;
A CTE names a subquery so the main query reads top to bottom. Great for breaking up complex logic.
Subqueries & CTEs
Recursive CTE
advancedWITH RECURSIVE counter(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;
Starts from a base row and repeatedly adds more until the condition stops it. Used for hierarchies and sequences.
Subqueries & CTEs
Rank within a group
advancedSELECT module_id, student_id, mark,
RANK() OVER (PARTITION BY module_id ORDER BY mark DESC) AS position
FROM grades;
Window functions compute across related rows without collapsing them. PARTITION BY restarts the ranking for each module.
Window functions
Running total and moving average
advancedSELECT student_id, module_id, mark,
SUM(mark) OVER (PARTITION BY student_id ORDER BY module_id) AS running_total,
AVG(mark) OVER (ORDER BY module_id ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS moving_avg
FROM grades;
The frame (ROWS BETWEEN …) says which neighbouring rows each calculation can see.
Window functions
Compare with the previous row
advancedSELECT student_id, module_id, mark,
mark - LAG(mark) OVER (PARTITION BY student_id ORDER BY module_id) AS change
FROM grades;
LAG looks at an earlier row, LEAD at a later one. The first row of each partition gets NULL.
Window functions
Top N per group
advancedSELECT *
FROM (
SELECT module_id, student_id, mark,
ROW_NUMBER() OVER (PARTITION BY module_id ORDER BY mark DESC) AS rn
FROM grades
) t
WHERE rn <= 3;
Number the rows inside each group, then keep the first N. ROW_NUMBER never ties; RANK can.
Window functions
INSERT
basicINSERT INTO students (id, name, year, course)
VALUES (101, 'Grace Hopper', 1, 'Computer Science');
Always list the columns so the statement survives a table change.
Change data
UPDATE
basicUPDATE students
SET year = year + 1
WHERE course = 'Computer Science';
Without WHERE, every row is updated. Run the matching SELECT first to check what you will change.
Change data
DELETE
basicDELETE FROM grades
WHERE mark IS NULL;
Without WHERE, every row is deleted. Prefer a transaction so you can roll back.
Change data
Transactions
intermediateBEGIN;
UPDATE grades SET mark = mark + 5 WHERE module_id = 7;
-- check the result with a SELECT here
COMMIT; -- or ROLLBACK; to undo
A transaction makes several changes succeed or fail together (atomicity).
Change data
CREATE TABLE with constraints
basicCREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
year INTEGER CHECK (year BETWEEN 1 AND 4),
course TEXT
);
PRIMARY KEY identifies a row; NOT NULL and CHECK stop bad data getting in.
Define tables
Foreign key
intermediateCREATE TABLE grades (
student_id INTEGER NOT NULL REFERENCES students(id) ON DELETE CASCADE,
module_id INTEGER NOT NULL REFERENCES modules(id),
mark INTEGER CHECK (mark BETWEEN 0 AND 100),
PRIMARY KEY (student_id, module_id)
);
A foreign key guarantees the referenced row exists. ON DELETE CASCADE removes dependent rows automatically.
Define tables
Index
intermediateCREATE INDEX idx_grades_module ON grades (module_id);
Indexes speed up lookups and joins on a column but slow down writes and use space. Index columns you filter or join on.
Define tables
Change a table
intermediateALTER TABLE students ADD COLUMN email TEXT;
DROP TABLE IF EXISTS old_students;
ALTER changes structure; DROP deletes a table and its data for good.
Define tables