SQL: practising SELECT and WHERE
SELECT picks columns, WHERE the matching rows. Your query runs directly on sample data.
Rules
- SELECT columns FROM table
- WHERE filters rows
- Text in single quotes
- DISTINCT removes duplicates
Your turn
Three problems on this topic. You can run the query first.
- 1 · SELECT & WHERE
- 2
- 3
List the names of all students from Wien.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Greta | Business | 8 | Berlin |
| 2 | David | Business | 8 | Wien |
| 3 | Anna | Law | 5 | Berlin |
| 4 | Max | Law | 8 | Berlin |
| 5 | Nora | Business | 4 | Bern |
| 6 | Eva | Law | 2 | Basel |
| 7 | Jonas | Chemistry | 5 | Wien |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Statistics | 5 | Meier |
| 2 | Calculus | 6 | Weber |
| 3 | Law | 3 | Keller |
| 4 | Databases | 3 | Weber |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 2 | 1.7 |
| 2 | 2 | 2.3 |
| 2 | 4 | 3.3 |
| 6 | 1 | 2.7 |
| 5 | 4 | 1.7 |
| 4 | 1 | 2 |
| 6 | 2 | 2.7 |
| 7 | 3 | 4 |
| 1 | 4 | 2.3 |
| 7 | 4 | 2 |
| 6 | 4 | 4 |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
List the name and city of all Computing students not from Wien.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | David | Computing | 7 | Basel |
| 2 | Jonas | Chemistry | 7 | Basel |
| 3 | Clara | Chemistry | 6 | Wien |
| 4 | Greta | Business | 2 | Bern |
| 5 | Felix | Chemistry | 8 | Bern |
| 6 | Ben | Chemistry | 7 | Bern |
| 7 | Nora | Computing | 7 | Wien |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 3 | Weber |
| 2 | Marketing | 3 | Keller |
| 3 | Statistics | 5 | Keller |
| 4 | Law | 6 | Meier |
grades
| student_id | course_id | grade |
|---|---|---|
| 5 | 1 | 3.3 |
| 7 | 2 | 4 |
| 3 | 1 | 3 |
| 2 | 4 | 1 |
| 6 | 2 | 1.7 |
| 2 | 2 | 1.7 |
| 1 | 3 | 3.3 |
| 6 | 4 | 2.3 |
| 5 | 2 | 1.7 |
| 3 | 4 | 3 |
| 2 | 3 | 1 |
| 4 | 1 | 2.7 |
| 1 | 2 | 3.7 |
Worked solution
SELECT name, city FROM students WHERE major = 'Computing' AND city <> 'Wien'
Result on the sample data:
name | city
David | Basel
Typical mistake: Combine conditions with AND or OR.
Common questions
Must my query look exactly like this?
No. The result counts, not how it is written.
