← Back to SQL, page 5

sql-0085 · Medium mid

Two students share the same name. Why does grouping enrolments by student name give wrong totals, and what should you group by?

GROUP BY name merges every row with that name into one group, so two different people become one. Group by the student's key (id), and select the name alongside it, either by also grouping by it or because it depends on the key. Names are labels, not identifiers.

Full answer
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

A second student called Asha joins:

sql
INSERT INTO students VALUES (6, 'Asha', 'Leeds', 2);
INSERT INTO enrolments VALUES (6, 30, 63);
SELECT id, name, city FROM students WHERE name = 'Asha' ORDER BY id;
idnamecity
1AshaPune
6AshaLeeds

Grouping by name:

sql
SELECT s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.name;
namecoursesavg_marks
Asha381.0

The report shows one Asha with three courses and an average of 81. In reality there are two people: one with 88 and 92, the other with 63.

Group by the identifier, and carry the name along:

sql
SELECT s.id, s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.id, s.name
ORDER BY s.id;
idnamecoursesavg_marks
1Asha290.0
6Asha163.0

Adding s.name to GROUP BY is harmless here, because each id has exactly one name. Leaving it out would be an error in PostgreSQL unless the grouping is on the primary key, in which case PostgreSQL accepts the dependent column.

The general rule applies to any report: group by keys, display labels. City names, product names and email addresses all look unique until they are not.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

INSERT INTO students VALUES (6, 'Asha', 'Leeds', 2);
INSERT INTO enrolments VALUES (6, 30, 63);
SELECT id, name, city FROM students WHERE name = 'Asha' ORDER BY id;

SELECT s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.name;

SELECT s.id, s.name, COUNT(*) AS courses, ROUND(AVG(e.marks), 1) AS avg_marks
FROM students s
JOIN enrolments e ON e.student_id = s.id
WHERE s.name = 'Asha'
GROUP BY s.id, s.name
ORDER BY s.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Grouping by a label merges different entities with the same label
  • Group by the key, display the name
  • Adding the name to GROUP BY alongside the key does not change the groups
  • PostgreSQL allows columns that depend on a grouped primary key

Common mistakes

  • Grouping by name, email or title as if they were unique
  • Noticing odd totals and blaming the data instead of the grouping

Follow-ups

  • How would you detect names that belong to more than one id?
  • What makes a good natural key?

Tips

  • Point at the merged average; it is an easy number to check by hand