CleverSphere

SQL subqueries

A subquery returns values the outer query goes on working with.

Rules

  • IN (SELECT …) for lists
  • NOT IN finds what is missing
  • Comparing with a single value: = (SELECT AVG …)

Your turn

Three problems on this topic. You can run the query first.

  1. 1 · Subqueries
  2. 2
  3. 3

List the names of all students without a grade entry.

students

idnamemajorsemestercity
1GretaLaw1Zürich
2EvaComputing7Berlin
3JonasComputing8Bern
4ClaraChemistry2Wien
5AnnaComputing2Basel
6HannahBusiness4Basel
7FelixLaw1Bern

grades

student_idcourse_idgrade
123
644
231
142
412.7
243
532.3
211.7
312.3
722.7
+ More tables: courses

courses

idtitlecreditslecturer
1Calculus3Meier
2Databases3Meier
3Statistics4Meier
4Marketing4Weber

SQL

Any equivalent query counts. It is also checked on data you can’t see.

Worked example

List the titles of all courses where a grade of 1 was given.

courses

idtitlecreditslecturer
1Law4Huber
2Statistics5Keller
3Calculus4Keller
4Databases5Weber

grades

student_idcourse_idgrade
612.7
111
123
431
623
212.3
444
512.3
722.3
521.3
642.3
321
+ More tables: students

students

idnamemajorsemestercity
1EvaComputing8Zürich
2LenaLaw7Basel
3GretaLaw1Berlin
4DavidComputing8Bern
5MaxBusiness5Wien
6ClaraBusiness5Wien
7FelixChemistry6Zürich

Worked solution

SELECT title FROM courses WHERE id IN (SELECT course_id FROM grades WHERE grade = 1)

Result on the sample data:

title

Law

Statistics

Calculus

Typical mistake: The subquery returns a list of ids.

Common questions

Can this be done with a JOIN?

Often yes, but subqueries are sometimes easier to read.

Related

More topics