SQL
Selecting records with SQL
A database table stores records in rows and fields in columns. SQL uses SELECT to choose fields to show, FROM to name the table, and WHERE to keep only rows matching a condition. For the students table below, SELECT name, score FROM students WHERE year = 10 returns only the Year 10 students' names and scores:
| name | year | score |
|---|---|---|
| Ada | 10 | 81 |
| Ben | 11 | 68 |
| Cy | 10 | 74 |
| name | score |
|---|---|
| Ada | 81 |
| Cy | 74 |
SELECT * would show every field. The WHERE condition filters records; it does not change the stored table. SQL keywords are commonly written in capitals, but they are not case-sensitive.
Key terms
Conditions with AND and OR
A WHERE condition can compare a field with a value using =, !=, <, <=, > or >=. AND and OR join two conditions:
SELECT name FROM students WHERE year = 10 AND score > 75returns only Ada: she is in Year 10 and scored over 75. Cy is in Year 10 but scored 74.SELECT name FROM students WHERE year = 11 OR score > 80returns Ada (score 81) and Ben (Year 11).
With AND, a record must meet both conditions. With OR, it must meet at least one.
Common mistake
Text values go in quotation marks, numbers don't: WHERE name = 'Ada', but WHERE year = 10.
Key terms
Reading a query step by step
To work out what a query returns, read it in this order:
- FROM: find the table.
- WHERE: go down the table one record at a time, keeping only those that meet the condition.
- SELECT: from the records kept, show only the fields listed, in the order they are listed.
Then write the result as a small table, with the field names as its headings. If no record meets the condition, the query returns no records: that's a valid answer, not an error.
Exam tip
When you write a query, check each part: the fields after SELECT, the table after FROM, and a condition after WHERE that uses the field names exactly as they appear in the table.