Set difference: students not in the club

Use the difference operation to find what one relation has and the other does not.

What to build

A query that computes π name ( Student ) − ClubMember.

Requirements

  • Use EXCEPT.
  • Return each name once.
  • Sort the names alphabetically.

Tables

Each test fills these tables with its own rows, then runs your SQL:

CREATE TABLE Student (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL
);
CREATE TABLE ClubMember (
  name TEXT NOT NULL
);

Output

One column, name, in alphabetical order. Your result is compared with the expected one, column names included, so name each column exactly as asked (use AS).

Constraints

Club members need not be students, and two students may share a name.

Example

When a test starts with:

INSERT INTO Student VALUES (1, 'Rahim', 'CSE'), (2, 'Karim', 'EEE'), (3, 'Nadia', 'CSE');
INSERT INTO ClubMember VALUES ('Nadia'), ('Imran');

your SQL should print:

name
-----
Karim
Rahim
(2 rows)

Why it works

EXCEPT keeps the rows of the first result that do not appear in the second, and like the algebra it removes repeats.

Examples

Example 1 · Input
CREATE TABLE Student (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL
);
CREATE TABLE ClubMember (
  name TEXT NOT NULL
);
INSERT INTO Student VALUES (1, 'Rahim', 'CSE'), (2, 'Karim', 'EEE'), (3, 'Nadia', 'CSE');
INSERT INTO ClubMember VALUES ('Nadia'), ('Imran');
Expected output
name
-----
Karim
Rahim
(2 rows)

Example 2 · Input
CREATE TABLE Student (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL
);
CREATE TABLE ClubMember (
  name TEXT NOT NULL
);
INSERT INTO Student VALUES (1, 'A', 'CSE');
INSERT INTO ClubMember VALUES ('A');
Expected output
name
----
(0 rows)

Each test makes its own tables, runs your SQL on them, and compares what your queries return. Changes never carry over from one test to the next.

Hints

Hint 1

π name (Student) − ClubMember is `SELECT name FROM Student EXCEPT SELECT name FROM ClubMember`.

Hint 2

An ORDER BY written at the very end sorts the whole result.

Solution

Show one correct solution (try it yourself first)
SELECT name FROM Student
EXCEPT
SELECT name FROM ClubMember
ORDER BY name;

Lesson: Relational algebra →