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);sql
SELECT city, COUNT(*) AS n FROM students GROUP BY city ORDER BY city;| city | n |
|---|---|
| NULL | 1 |
| Leeds | 2 |
| Pune | 2 |
Dara has no city and appears as a separate group. SQLite sorts NULL first in ascending order; PostgreSQL sorts it last unless told otherwise.
Reports often relabel the group with COALESCE(city, 'Unknown'). Do that in the SELECT and GROUP BY both, or group by the raw column and relabel only for display.
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);
SELECT city, COUNT(*) AS n FROM students GROUP BY city ORDER BY city;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- GROUP BY puts all NULLs in one group
- The group key shows as NULL
- NULL sort position differs between engines
- Relabel with COALESCE for display
Common mistakes
- Expecting rows with NULL keys to disappear
- Assuming NULL groups sort the same on every engine
Follow-ups
- How do you put the NULL group last on SQLite?
- Does DISTINCT treat NULLs the same way?
Tips
- Mention the sort-order difference