Skip to content
Advertisement

Find IDs and names of students who took CS-101 and did not take CS-319

Can someone help with this homework problem:

Find IDs and names of students who took CS-101 and did not take CS-319.

These are the two tables that I can use for this assignment:

I tried this but was unable to successfully exclude the students who who took “CS-319”

Advertisement

Answer

There are at least three separate ways to solve this problem in SQL.

  1. Set operations ( SELECT then exclude using EXCEPT ).
    • As MySQL doesn’t support EXCEPT we can use NOT IN instead.
  2. Anti-join (LEFT OUTER JOIN).
  3. Join and discriminate on COUNT.

Approach 1: SELECT then exclude using EXCEPT:

Then use this as an inner-query to JOIN on student information:

Approach 1 for MySQL (using NOT IN):

Approach 2: Anti-join:

Approach 3: Join and discriminate on COUNT:

More approaches:

There are other alternatives using WHERE EXISTS, WHERE NOT EXISTS, and so on. One of the problems (or challenges) when using SQL is there are different ways to query the source data to get the exact same results. Have fun!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement