SQL on the E-Learning database: reviewing AI-written queries for ratings, lesson progress and the schema
Why a course dashboard reports 37 chapters for a 4-chapter course and 112% completion: fan-out when joining down to child tables, a numerator and denominator that disagree, a redundant course_id. How to review AI-written SQL and schema on the E-Learning database.
On this page
1. The problem
An AI-written dashboard for an online learning platform: the "SQL basics" course has 4 chapters and 37 lessons, but the "chapters" column says 37. The completion table shows 40 students at 112%. No query raised an error.
2. Key idea
Every join down to a child table repeats each parent row once per child row. Rule: aggregate at the level you're counting first, then join up. Before writing, ask: what is one result row, and how many times does each JOIN multiply rows.
| Tool | Use when | Don't use when |
|---|---|---|
COUNT(DISTINCT ch.id) |
counting parents after one join down | you need SUM/AVG on a parent column |
| A CTE per level | rates, totals, multi-level joins | one table, no joins |
HAVING COUNT(uc.rating) >= 10 |
ranking by average rating | the product already chose a weighted average |
| Composite foreign key | a redundant column must match the source path | you can drop the redundant column |
3. In SQL
Completion rate done right: two CTEs with the same filters, then LEFT JOIN onto enrollments (runs on MySQL 8.4 and PostgreSQL).
WITH course_size AS ( -- denominator: ACTIVE lessons per course
SELECT ch.course_id, COUNT(*) AS total
FROM chapter ch JOIN lesson l ON l.chapter_id = ch.id
WHERE ch.status = 'ACTIVE' AND l.status = 'ACTIVE'
GROUP BY ch.course_id
), done AS ( -- numerator: same filters
SELECT ucl.user_id, ucl.course_id, COUNT(*) AS done
FROM user_course_lesson ucl
JOIN lesson l ON l.id = ucl.lesson_id AND l.status = 'ACTIVE'
JOIN chapter ch ON ch.id = l.chapter_id AND ch.status = 'ACTIVE'
AND ch.course_id = ucl.course_id -- blocks drifted course_id
WHERE ucl.status = 'DONE'
GROUP BY ucl.user_id, ucl.course_id
)
SELECT uc.user_id, uc.course_id,
ROUND(100.0 * COALESCE(d.done, 0) / NULLIF(cs.total, 0), 2) AS percent_done
FROM user_course uc
LEFT JOIN course_size cs ON cs.course_id = uc.course_id
LEFT JOIN done d ON d.user_id = uc.user_id AND d.course_id = uc.course_id;Other languages: JPA, Prisma and Django ORM counting through collections fan out too; read the generated SQL in the log.
4. Working with AI
Hand to AI: a first draft from the task and DDL, sample data with edge cases (empty course, hidden lessons, progress recorded under the wrong course).
Check yourself in AI-written code:
- After joining down to a child table,
COUNTon the parent usesDISTINCT, or it's pre-aggregated in a CTE. - Rates: numerator and denominator share the
statusfilters, useNULLIF(…, 0)and100.0; sample data yields no row above 100%. - Joins to
user_course_lessonuse all three key columns:user_id,course_id,lesson_id. - MySQL 8.4 DDL declares foreign keys at table level; verify with
SHOW CREATE TABLE.
5. Exercises
Exercise 1: Review "completion rate in one query, no CTE"
The AI says "shorter than the CTE version, same result". A student who finished 2/10 lessons shows 100%; one who hasn't started shows NULL instead of 0. Find the bug, give the smallest data that proves it, fix it.
SELECT uc.user_id, uc.course_id,
ROUND(100.0 * SUM(ucl.status = 'DONE') / COUNT(l.id), 2) AS percent_done
FROM user_course uc
JOIN chapter ch ON ch.course_id = uc.course_id AND ch.status = 'ACTIVE'
JOIN lesson l ON l.chapter_id = ch.id AND l.status = 'ACTIVE'
LEFT JOIN user_course_lesson ucl
ON ucl.user_id = uc.user_id AND ucl.course_id = uc.course_id
GROUP BY uc.user_id, uc.course_id;Solution 1
- Bug: the
ONlacksucl.lesson_id = l.id. Each lesson pairs with every progress row of the enrollment. - Proof data: one course, 10 ACTIVE lessons; student A has 2 DONE rows. After the join there are 10 × 2 = 20 rows,
SUM= 20,COUNT(l.id)= 20, giving 100.00. Expected 20.00. - NULL case: a student who hasn't started:
ucl.status = 'DONE'is NULL on every row, andSUMof all NULLs is NULL. - Fix: add
AND ucl.lesson_id = l.id AND ucl.status = 'DONE'to theON, compute100.0 * COUNT(ucl.lesson_id) / NULLIF(COUNT(l.id), 0). - Still missing:
JOIN chapteris INNER, so a course with no ACTIVE chapter drops the enrollment. The two-CTE version in section 3 keeps all of them.
Exercise 2: Choose between two account designs
The schema has three tables user, teacher, admin with the same login columns. The AI proposes merging them into one account table with a role. Soon teachers will be able to buy courses. Pick one, give the reason and when the choice flips.
Solution 2
Pick one account table + role: three tables force someone who both learns and teaches to hold two accounts, username is only unique per table, and login has to check three places.
| Three tables | One account + role |
|
|---|---|---|
| Gain | FK course.teacher_id → teacher guarantees the instructor is a teacher |
login, permissions, account locking in one place |
| Cost | duplicated columns, one person can't hold two roles | an FK can't check "must have role TEACHER" |
Cover the cost with a profile table teacher_profile(account_id PK/FK, bio) for course.teacher_id to point at; for multiple roles use account_role. Keep three tables only when the user kinds are truly separate (internal admins signing in through their own SSO).
More review notes: status should be an ENUM/CHECK, rating needs CHECK (rating BETWEEN 1 AND 5), password should be password_hash, and a completed_at column is missing.
Exercise 3: Read an incident
After a legacy data import, 40 students of "SQL basics" sit at 112%. The rate query lacks AND ch.course_id = ucl.course_id. SHOW CREATE TABLE user_course_lesson shows no FOREIGN KEY, although the migration has lesson_id BIGINT NOT NULL REFERENCES lesson(id). Diagnose it, say what to do in 15 minutes, fix the root cause.
Solution 3
- Diagnosis: the import wrote progress for another course's lessons under the SQL course's
course_id. The denominator only counts SQL lessons, the numerator also counts the strays, so it passes 100%. Nothing blocked it because MySQL 8.4 ignores inlineREFERENCES(enforced only from 9.0). - 15 minutes: count drifted rows, add the check condition to the report, stop the import script.
SELECT COUNT(*) AS drifted
FROM user_course_lesson ucl
JOIN lesson l ON l.id = ucl.lesson_id
JOIN chapter ch ON ch.id = l.chapter_id
WHERE ch.course_id <> ucl.course_id;- Root fix: clean the drifted rows, declare
FOREIGN KEY (...)at table level. For the database to block drift itself, addcourse_idtolessonwithUNIQUE (id, course_id)and a composite key(lesson_id, course_id) → lesson(id, course_id). Add a CI step comparinginformation_schema.REFERENTIAL_CONSTRAINTSagainst the expected foreign keys.
Summary
- Every JOIN down to a child table multiplies parent rows; aggregate at the child level first, then join up.
- Rates: same filters on both sides,
NULLIF,100.0; over 100% means a bug. - Ratings can be NULL; ranking by average needs a minimum count.
- A redundant column needs a constraint (composite foreign key) or a check join.
- MySQL 8.4 ignores inline
REFERENCES; verify withSHOW CREATE TABLE.
Further reading: SQL exercises: JOIN and GROUP BY.
Practice interview questions on this topic
- What are DDL, DML, DCL and TCL? How do DELETE, TRUNCATE and DROP differ?
- What is JOIN fan-out that makes SUM/COUNT wrong, and how do you fix it?
- What are the NULL pitfalls in SQL, and why can NOT IN return nothing?
- What is normalization? State 1NF, 2NF and 3NF briefly?
- When do you deliberately denormalize, and how do you keep redundant data correct?
- If Java already validates input, do you still need NOT NULL, CHECK, FK and UNIQUE in the database?
All SQL & Query Tuning questions →All Data Modeling & Scaling questions →
Comments
Community rules