School DB Lab
12 worked examples, from SELECT to aggregation

Query & Retrieval Lab

Every example below is a real question a school office would ask, the exact SQL that answers it, and the live result — run straight from database/learning_queries.sql.

نیچے دی گئی ہر مثال اسکول کے دفتری نظام میں اٹھائے جانے والے ایک حقیقی سوال، اس کا جواب دینے والی درست ایس کیو ایل (SQL) کیوری، اور اس کے لائیو نتائج پر مشتمل ہے — جو براہِ راست database/learning_queries.sql سے چلائی گئی ہے۔

Query 1 — Show all students

Question: “Who are all our students?”

Tables: students

Keys used in the JOIN: None — no JOIN needed.

SELECT student_id, admission_no, first_name, last_name, gender, status
FROM students
ORDER BY last_name, first_name;

ORDER BY only changes display order, not which rows come back.

student_idadmission_nofirst_namelast_namegenderstatus
11ADM-2025-011HassanAbbasMaleActive
2ADM-2025-002SaraAhmedFemaleActive
17ADM-2025-017YusufAnwarMaleActive
14ADM-2025-014KhadijaAslamFemaleActive
20ADM-2025-020HiraBasitFemaleActive
15ADM-2025-015BilawalChaudhryMaleActive
7ADM-2025-007UsmanFarooqMaleActive
8ADM-2025-008MahnoorIqbalFemaleActive

20 row(s) total, showing first 8.

Query 2 — Find student by admission number

Question: “Who is ADM-2025-001?”

Tables: students

Keys used in the JOIN: admission_no — a UNIQUE key, so at most one row can match.

SELECT student_id, admission_no, first_name, last_name, date_of_birth
FROM students
WHERE admission_no = 'ADM-2025-001';

Because admission_no is UNIQUE, this WHERE clause can never return more than one row.

student_idadmission_nofirst_namelast_namedate_of_birth
1ADM-2025-001AliKhan2014-03-12

1 row(s) total.

Query 3 — Students in Grade 5, Section A

Question: “Which students are in Grade 5-A this year?”

Tables: students, student_enrollments, classes

Keys used in the JOIN: students.student_id = student_enrollments.student_id
student_enrollments.class_id = classes.class_id

SELECT s.student_id, s.first_name, s.last_name, c.class_name, c.section
FROM students s
INNER JOIN student_enrollments e ON e.student_id = s.student_id
INNER JOIN classes c            ON c.class_id   = e.class_id
WHERE c.class_name = 'Grade 5' AND c.section = 'A' AND c.academic_year = '2025-2026'
ORDER BY s.last_name;

INNER JOIN only returns rows with a match on both sides — a student with no enrollment row would disappear here.

student_idfirst_namelast_nameclass_namesection
2SaraAhmedGrade 5A
1AliKhanGrade 5A
3BilalRazaGrade 5A
5HamzaSheikhGrade 5A
4AyeshaTariqGrade 5A

5 row(s) total.

Query 4 — Every student's parent(s)

Question: “Who are each student's parents/guardians?”

Tables: students, student_parents, parents

Keys used in the JOIN: students.student_id = student_parents.student_id
student_parents.parent_id = parents.parent_id

SELECT s.first_name AS student_first, s.last_name AS student_last,
       p.first_name AS parent_first,  p.last_name AS parent_last,
       sp.relationship_type, sp.is_primary_contact
FROM students s
INNER JOIN student_parents sp ON sp.student_id = s.student_id
INNER JOIN parents p          ON p.parent_id   = sp.parent_id
ORDER BY s.last_name, s.first_name;

This walks through the junction table — there is no parent_id column directly on students, on purpose (it is a Many-to-Many relationship).

student_firststudent_lastparent_firstparent_lastrelationship_typeis_primary_contact
HassanAbbasZafarAbbasFather1
HassanAbbasShaziaZafarMother0
SaraAhmedImranKhanFather0
SaraAhmedNasreenKhanMother1
YusufAnwarNaveedAslamGuardian1
KhadijaAslamTariqMehmoodFather1
HiraBasitNasreenKhanMother1
BilawalChaudhryFarahYousafGuardian1

30 row(s) total, showing first 8.

Query 5 — Teacher + class + subject assignments

Question: “Which teacher teaches which subject to which class?”

Tables: class_subject_teachers, classes, subjects, teachers

Keys used in the JOIN: class_subject_teachers.class_id = classes.class_id
class_subject_teachers.subject_id = subjects.subject_id
class_subject_teachers.teacher_id = teachers.teacher_id

SELECT c.class_name, c.section, sub.subject_name,
       t.first_name AS teacher_first, t.last_name AS teacher_last
FROM class_subject_teachers cst
INNER JOIN classes  c   ON c.class_id   = cst.class_id
INNER JOIN subjects sub ON sub.subject_id = cst.subject_id
INNER JOIN teachers t   ON t.teacher_id = cst.teacher_id
ORDER BY c.class_name, c.section, sub.subject_name;

One assignment row, three JOINs — this is the whole reason the junction table carries three Foreign Keys at once.

class_namesectionsubject_nameteacher_firstteacher_last
Grade 5AArtNadiaSheikh
Grade 5AEnglishBilalHussain
Grade 5AMathematicsSarahAhmed
Grade 5AScienceAyeshaMalik
Grade 5ASocial StudiesOmarFarooq
Grade 5AUrduOmarFarooq
Grade 5BArtNadiaSheikh
Grade 5BEnglishBilalHussain

24 row(s) total, showing first 8.

Query 6 — Daily attendance for one date

Question: “Who was present/absent on 2025-09-03?”

Tables: attendance, students, classes

Keys used in the JOIN: attendance.student_id = students.student_id
attendance.class_id = classes.class_id

SELECT a.attendance_date, s.first_name, s.last_name,
       c.class_name, c.section, a.status
FROM attendance a
INNER JOIN students s ON s.student_id = a.student_id
INNER JOIN classes  c ON c.class_id   = a.class_id
WHERE a.attendance_date = '2025-09-03'
ORDER BY c.class_name, s.last_name;

A straightforward two-way JOIN filtered by a specific date.

attendance_datefirst_namelast_nameclass_namesectionstatus
2025-09-03SaraAhmedGrade 5APresent
2025-09-03AliKhanGrade 5APresent
2025-09-03BilalRazaGrade 5AAbsent
2025-09-03HamzaSheikhGrade 5APresent
2025-09-03AyeshaTariqGrade 5APresent
2025-09-03HassanAbbasGrade 6APresent
2025-09-03KhadijaAslamGrade 6APresent
2025-09-03BilawalChaudhryGrade 6APresent

10 row(s) total, showing first 8.

Query 7 — Absent students

Question: “Who has been marked Absent, and when?”

Tables: attendance, students, classes

Keys used in the JOIN: Same JOIN shape as Query 6.

SELECT a.attendance_date, s.first_name, s.last_name,
       c.class_name, c.section, a.remarks
FROM attendance a
INNER JOIN students s ON s.student_id = a.student_id
INNER JOIN classes  c ON c.class_id   = a.class_id
WHERE a.status = 'Absent'
ORDER BY a.attendance_date;

Same JOIN as Query 6, filtered by status instead of by date — proof that a JOIN's shape and a query's WHERE clause are independent choices.

attendance_datefirst_namelast_nameclass_namesectionremarks
2025-09-02MariamYousafGrade 6ANo reason given
2025-09-03BilalRazaGrade 5ASick leave informed by parent
2025-09-04KhadijaAslamGrade 6AFamily emergency

3 row(s) total.

Query 8 — Exam results with subject names

Question: “How did each student do, per subject, per exam?”

Tables: exam_results, exams, students, subjects

Keys used in the JOIN: exam_results.exam_id = exams.exam_id
exam_results.student_id = students.student_id
exam_results.subject_id = subjects.subject_id

SELECT e.exam_name, s.first_name, s.last_name,
       sub.subject_name, r.marks_obtained, r.grade
FROM exam_results r
INNER JOIN exams    e   ON e.exam_id      = r.exam_id
INNER JOIN students s   ON s.student_id   = r.student_id
INNER JOIN subjects sub ON sub.subject_id = r.subject_id
ORDER BY e.exam_name, s.last_name, sub.subject_name;

Three JOINs turn three raw id columns into readable names.

exam_namefirst_namelast_namesubject_namemarks_obtainedgrade
Mid-Term ExamHassanAbbasEnglish68.00C
Mid-Term ExamHassanAbbasMathematics60.00C
Mid-Term ExamHassanAbbasScience69.00C
Mid-Term ExamSaraAhmedEnglish70.00B
Mid-Term ExamSaraAhmedMathematics72.00B
Mid-Term ExamSaraAhmedScience69.00C
Mid-Term ExamKhadijaAslamEnglish81.00A
Mid-Term ExamKhadijaAslamMathematics89.00A

30 row(s) total, showing first 8.

Query 9 — Unpaid fee invoices

Question: “Which invoices still need to be collected?”

Tables: fee_invoices, students

Keys used in the JOIN: fee_invoices.student_id = students.student_id

SELECT s.first_name, s.last_name, i.invoice_month, i.amount, i.due_date, i.status
FROM fee_invoices i
INNER JOIN students s ON s.student_id = i.student_id
WHERE i.status IN ('Unpaid', 'Overdue')
ORDER BY i.due_date;

A filter on status narrows a simple JOIN down to just the invoices that still need action.

first_namelast_nameinvoice_monthamountdue_datestatus
AmnaRiaz2025-095000.002025-09-10Unpaid
TalhaNadeem2025-095000.002025-09-10Unpaid
HiraBasit2025-095000.002025-09-10Unpaid
OmarSaeed2025-105000.002025-10-10Unpaid
KhadijaAslam2025-105000.002025-10-10Unpaid
BilawalChaudhry2025-105000.002025-10-10Unpaid
SanaRafiq2025-105000.002025-10-10Unpaid
YusufAnwar2025-105000.002025-10-10Unpaid

20 row(s) total, showing first 8.

Query 10 — Total paid by each student

Question: “How much has each student's family paid in total?”

Tables: students, fee_invoices, fee_payments

Keys used in the JOIN: students.student_id = fee_invoices.student_id
fee_invoices.invoice_id = fee_payments.invoice_id

SELECT s.student_id, s.first_name, s.last_name,
       COALESCE(SUM(p.amount_paid), 0) AS total_paid
FROM students s
LEFT JOIN fee_invoices i ON i.student_id  = s.student_id
LEFT JOIN fee_payments p ON p.invoice_id  = i.invoice_id
GROUP BY s.student_id, s.first_name, s.last_name
ORDER BY total_paid DESC;

LEFT JOIN is essential here — a student with an unpaid invoice and no payments yet must still appear, with a total of 0, instead of disappearing from the report.

student_idfirst_namelast_nametotal_paid
2SaraAhmed10000.00
1AliKhan10000.00
3BilalRaza10000.00
11HassanAbbas5000.00
7UsmanFarooq5000.00
8MahnoorIqbal5000.00
6ZainabMalik5000.00
10FatimaNoor5000.00

20 row(s) total, showing first 8.

Query 11 — Count students per class

Question: “How many students are in each class right now?”

Tables: classes, student_enrollments

Keys used in the JOIN: classes.class_id = student_enrollments.class_id

SELECT c.class_name, c.section, COUNT(e.student_id) AS student_count
FROM classes c
LEFT JOIN student_enrollments e
       ON e.class_id = c.class_id AND e.status = 'Active'
GROUP BY c.class_id, c.class_name, c.section
ORDER BY c.class_name, c.section;

LEFT JOIN keeps a class in the results even with 0 enrolled students; COUNT(e.student_id) only counts non-NULL matches, so an empty class correctly shows 0, not 1.

class_namesectionstudent_count
Grade 5A5
Grade 5B5
Grade 6A5
Grade 6B3

4 row(s) total.

Query 12 — Average marks per subject

Question: “Which subject has the highest average score school-wide?”

Tables: exam_results, subjects

Keys used in the JOIN: exam_results.subject_id = subjects.subject_id

SELECT sub.subject_name,
       ROUND(AVG(r.marks_obtained), 2) AS average_marks,
       COUNT(*) AS results_counted
FROM exam_results r
INNER JOIN subjects sub ON sub.subject_id = r.subject_id
GROUP BY sub.subject_id, sub.subject_name
ORDER BY average_marks DESC;

AVG() and COUNT() are aggregate functions — GROUP BY subject collapses many result rows into one summary row per subject.

subject_nameaverage_marksresults_counted
Mathematics81.0010
Science73.3010
English71.1010

3 row(s) total.

Explain this page
How are these queries organised?
They start simple (a single SELECT on one table) and build up to multi-table JOINs and aggregation with GROUP BY. Each example shows the SQL, a plain-English explanation of the key technique, and the actual live result rows from the database.
Why twelve examples?
They cover every major retrieval pattern used in real school reporting: finding a record by a unique key, filtering, sorting, joining across junction tables, calculating aggregates, and counting with LEFT JOIN to include empty groups.
یہ کیوریز کس ترتیب سے ہیں؟
یہ سادہ سے شروع ہوتی ہیں (ایک ٹیبل پر سادہ SELECT) اور بتدریج ملٹی-ٹیبل جوائنز (Multi-table JOINs) اور GROUP BY کے ساتھ اگریگیشن (Aggregation) تک پہنچتی ہیں۔ ہر مثال میں ایس کیو ایل (SQL)، تکنیک کی آسان وضاحت، اور ڈیٹا بیس سے حاصل شدہ لائیو نتائج شامل ہیں۔
بارہ مثالیں کیوں؟
یہ اسکول کی رپورٹنگ میں استعمال ہونے والے تمام اہم ڈیٹا بازیابی (Retrieval) طریقوں کو احاطہ کرتی ہیں: یونیک کی (Unique Key) سے ریکارڈ تلاش کرنا، فلٹر (Filter) کرنا، ترتیب دینا، جنکشن ٹیبلز (Junction Tables) کے پار جوائن (JOIN) کرنا، اگریگیٹ (Aggregate) حساب لگانا، اور خالی گروپوں کو شامل رکھنے کے لیے LEFT JOIN کے ساتھ گنتی کرنا۔