SQL: Querying Data
Write SELECT queries to retrieve data from databases. Use WHERE to filter, ORDER BY to sort, and LIKE with wildcards to match patterns. Includes worked examples for all boards.
A database with millions of records is useless if you cannot ask it questions. SQL - Structured Query Language - is the language you use to retrieve exactly the data you need, filter out what you do not, and sort the results. Every major website you use runs SQL queries behind the scenes thousands of times per second.
All worked examples below use this table. Get familiar with the structure before we write queries against it.
| StudentID | FirstName | LastName | Age | Year | IsEnrolled | Score |
|---|---|---|---|---|---|---|
| 1001 | Alice | Smith | 15 | 10 | TRUE | 82 |
| 1002 | Bob | Brown | 16 | 11 | TRUE | 67 |
| 1003 | Clara | Davis | 15 | 10 | FALSE | 91 |
| 1004 | Dan | Evans | 16 | 11 | TRUE | 54 |
| 1005 | Eve | Foster | 15 | 10 | TRUE | 78 |
| 1006 | Frank | Green | 17 | 12 | TRUE | 43 |
| 1007 | Grace | Hill | 16 | 11 | FALSE | 88 |
FROM Students
FROM Students
FROM Students
WHERE Score > 75
| FirstName | LastName | Score |
|---|---|---|
| Alice | Smith | 82 |
| Clara | Davis | 91 |
| Eve | Foster | 78 |
| Grace | Hill | 88 |
FROM Students
WHERE Year = 11
AND IsEnrolled = TRUE
| FirstName | LastName |
|---|---|
| Bob | Brown |
| Dan | Evans |
AND requires both conditions to be true. OR requires at least one to be true. When combining AND and OR in one query, use brackets to make the order of evaluation clear - just like BODMAS in maths.
FROM Students
WHERE IsEnrolled = TRUE
ORDER BY Score DESC
| FirstName | LastName | Score |
|---|---|---|
| Alice | Smith | 82 |
| Eve | Foster | 78 |
| Bob | Brown | 67 |
| Dan | Evans | 54 |
| Frank | Green | 43 |
Test yourself - using the Students table above
1. Which SQL clause do you use to filter rows based on a condition?
2. What does WHERE LastName LIKE 'H%' return from the Students table?
3. How would you sort results so that students with the highest scores appear first?
Write a SQL query to return the first name, last name and score of all enrolled Year 10 students, ordered by score from highest to lowest. Use the Students table from this lesson.
FROM Students
WHERE Year = 10 AND IsEnrolled = TRUE
ORDER BY Score DESC
This returns Alice Smith (82), Eve Foster (78). Clara Davis is Year 10 but IsEnrolled = FALSE so she is excluded.
Practice what you have learned
Three levels of worksheet for this lesson. Download, print and complete offline.