Databases & SQL

Lesson 3 of 7

Lesson 3 — SQL Basics: SELECT, WHERE, ORDER BY

Ask a database questions in its own language and get exactly the rows you want.

🟢 Beginner 80 XP

Learn it

SQL (Structured Query Language) is how you talk to a relational database.

SELECT chooses columns, FROM chooses the table, WHERE filters rows, ORDER BY sorts and LIMIT caps the result.

SQL is declarative: you say what you want, not how to fetch it. The query planner works out the how.

Use single quotes for text, % as a wildcard with LIKE, and IS NULL (never = NULL) to test for missing values.

Key terms

SQL
Structured Query Language, the standard language for relational databases.
DDL / DML
Data Definition Language (structure) vs Data Manipulation Language (data).
Predicate
The condition in a WHERE clause that each row must satisfy.
NULL
Unknown/missing — compared with IS NULL, not = NULL.
Parameterised query
A query with placeholders for user input; blocks SQL injection.

Build a query one clause at a time

  1. 1FROM: SELECT * FROM student; — every row, every column.
  2. 2SELECT: SELECT name, year_group FROM student; — fewer columns, less data moved.
  3. 3WHERE: … WHERE year_group = 10 AND house = 'Ash';
  4. 4ORDER BY: … ORDER BY name ASC;
  5. 5LIMIT: … LIMIT 10; — top ten only, great while testing.

A realistic query

sqlSELECT name,
       year_group,
       house
FROM   student
WHERE  year_group >= 10
  AND  house IN ('Ash', 'Birch')
  AND  left_school_on IS NULL
ORDER BY year_group DESC, name ASC
LIMIT 20;

Filter first, sort second, limit last. IS NULL finds students who have not left — using = NULL would silently return nothing.

Try it

Complete the query that finds active Year 11 students, newest first.

SELECT name FROM student
WHERE year_group = 11
  AND left_school_on ______
ORDER BY joined_on DESC;

Challenge

Write SQL for a shop's `orders` table (id, customer_id, total, status, placed_at) that returns the 5 largest completed orders placed this year, showing only id, customer_id and total.

Pick whichever way suits you — every mode earns the same bonus XP.

Write at least 40 more characters to submit.

Mark your own work

Guided walkthrough — 0/3 clues revealed

  1. Clue 1 locked — reveal it only if you get stuck.
  2. Clue 2 locked — reveal it only if you get stuck.
  3. Clue 3 locked — reveal it only if you get stuck.

Each clue costs 4 XP (never below 20 XP). You'd earn 40 XP right now.

Quiz time

Question 1 of 4Score 0

Which clause filters rows before grouping?