GROUP BY
Definition and example
GROUP BY is the focus of this lesson. GROUP BY puts rows into buckets, then the aggregate runs per bucket. The task asks you to apply that idea in a small example: What does GROUP BY city do. Before you run the code, predict what should happen. Then Inspect the returned columns and rows and compare it with your prediction. If the result differs, change one relevant line and run it again. Testing one change at a time makes the cause of a result easier to understand.
The sample database
CREATE TABLE courses (id INTEGER PRIMARY KEY, title TEXT, monthly_fee INTEGER); CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, city TEXT, course_id INTEGER, joined TEXT); CREATE TABLE fees (id INTEGER PRIMARY KEY, student_id INTEGER, month TEXT, amount INTEGER, paid INTEGER); INSERT INTO courses VALUES (1,'Web Design',9000),(2,'Python',11667),(3,'JavaScript',11667),(4,'AI & Prompt Engineering',15000); INSERT INTO students VALUES (1,'Sara','Faisalabad',2,'2026-01-12'), (2,'Ali','Faisalabad',1,'2026-01-20'), (3,'Hina','Jhumra',2,'2026-02-02'), (4,'Bilal','Faisalabad',4,'2026-02-15'), (5,'Ayesha','Sargodha',3,'2026-03-01'), (6,'Usman','Jhumra',1,'2026-03-11'), (7,'Zainab','Faisalabad',4,'2026-04-05'), (8,'Hamza','Faisalabad',3,'2026-04-19'); INSERT INTO fees VALUES (1,1,'2026-01',11667,1),(2,1,'2026-02',11667,1), (3,2,'2026-01',9000,1),(4,2,'2026-02',9000,0), (5,3,'2026-02',11667,1),(6,3,'2026-03',11667,0), (7,4,'2026-02',15000,1),(8,4,'2026-03',15000,1), (9,5,'2026-03',11667,0), (10,6,'2026-03',9000,1),(11,6,'2026-04',9000,0), (12,7,'2026-04',15000,0), (13,8,'2026-04',11667,1);
Run your code to see the output and the checks.
Submit your code to see results
Write your code in the middle column and press Run code.
Why this works
Checks on this task:
- The query must return the expected rows and values.
The task and step-by-step instructions are written as comments at the top of the editor. Change one relevant line, run it, and compare the result with these checks.
Sign in to use up to 8 optional task skips in this course.
Incorrect attempts before answer: 0 / 3
Track progress
0 passed of 56 tasks
Pass every check or use one of your available skips to open the next task.
Sign in to keep your code and certificates.
Need a hand?
Worked answer
You have made three incorrect attempts. Review this example, close the window, and continue practising.