PART 2 of 5  •  about 19 class hours

Working with Data

Protect data with keys and constraints, transform it with functions, summarise it with GROUP BY, and combine tables with JOINs.

5

Keys & Constraints

10 examples  •  4 h
6

Built-in Functions

10 examples  •  5 h
7

Aggregation & Grouping

10 examples  •  5 h
8

Joining Tables

10 examples  •  5 h
📊
mysql>
SQL:2023  •  MySQL 9.7 LTS
BrainBit Infotech, Ranchi  |  Complete MySQL Course  |  Keys: ← → navigate   M menu   L SQL Lab   F fullscreen
M5

Keys & Constraints

Good databases refuse bad data. Constraints are rules that MySQL checks on every INSERT and UPDATE - duplicate mobiles, negative marks and orphan orders are stopped before they enter.

  • Why rules belong in the database
  • NOT NULL and DEFAULT
  • PRIMARY KEY and AUTO_INCREMENT
  • UNIQUE
  • CHECK constraints
  • FOREIGN KEY: parent and child tables
  • ON DELETE CASCADE / SET NULL / RESTRICT
  • Composite keys; reading constraint errors
YOU WILL BUILD:
Unique mobile registerAttendance with a composite keyLibrary issue system
🔑
about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M5Where is this used in real work?

Constraints stop bad data at the door

erp.brainbit-teaching.com/admission/new
📝 New admission
Mobile: 9835012345already used by Priya (UNIQUE)
Marks: 105must be 0-100 (CHECK)
Course: 999no such course (FOREIGN KEY)
Name: (empty)required (NOT NULL)
Roll no: auto13 (AUTO_INCREMENT)
🛡️

Last line of defence

Apps check forms, but bugs, Excel imports and other apps can still send bad data. The database checks every write.
🔗

Relationships stay correct

A fee row cannot point to a student who does not exist. Reports never show "unknown student".
🏢

Required in real projects

Banks, hospitals and government systems (e.g. scholarship portals) depend on keys to avoid double payments.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Concept

The six constraints at a glance

❗

NOT NULL

A value must be given. name VARCHAR(50) NOT NULL
📋

DEFAULT

Value used when none is given. status VARCHAR(10) DEFAULT 'Active'
🔑

PRIMARY KEY

Unique + not null. Exactly one per table. Identifies each row.
☝️

UNIQUE

No two rows may share the value (NULLs allowed). Mobile, email, Aadhaar.
✅

CHECK

Any true/false rule: CHECK (marks BETWEEN 0 AND 100). Enforced since MySQL 8.0.16.
🔗

FOREIGN KEY

Value must exist in another table's key. REFERENCES students(student_id)
Name your constraintsCONSTRAINT chk_marks CHECK (...) - then error messages say chk_marks, which is easy to understand.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Concept

PRIMARY KEY and AUTO_INCREMENT

  • The primary key is the row's identity card: unique, never NULL, one per table.
  • AUTO_INCREMENT lets MySQL give the next number. Deleted numbers are not reused - gaps are normal.
  • A duplicate key gives ERROR 1062 Duplicate entry.
Surrogate vs natural keyA surrogate key is a made-up number (student_id). A natural key is real data (Aadhaar, PAN). Most apps use a surrogate PK plus UNIQUE on the natural key.
pk.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Animated explainer

FOREIGN KEY: how parent and child tables stay connected

students (PARENT)
student_idname
1Priya
2Aman
3Sneha
⬅
fees.student_id must exist in students.student_id
fees (CHILD)
fee_idstudent_idamount
114500
222500
3993000
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails
Your choiceON DELETE RESTRICT | CASCADE | SET NULL
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Concept

FOREIGN KEY in SQL

  • The parent column must be a PRIMARY KEY or UNIQUE.
  • Both columns need the same type (INT with INT).
  • Create the parent first, insert parents first, delete children first.
  • Only the InnoDB engine (MySQL's default) enforces foreign keys.
📜 SQL standard vs MySQL
SQL:2023 standardON DELETE CASCADE | SET NULL | SET DEFAULT | RESTRICT | NO ACTION
MySQL 9.7Same, except SET DEFAULT is not supported by InnoDB. RESTRICT = NO ACTION.
fk.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Concept

CHECK and UNIQUE in action

  • UNIQUE stops duplicates in one column (or a group of columns). NULL values do not clash.
  • CHECK (condition) must be true (or unknown) for every row. Before 8.0.16 MySQL ignored CHECK - very old tutorials say "CHECK does not work"; that is no longer true.
  • Errors: 3819 = check violated, 1062 = duplicate.
check.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 1 of 10  •  Easy

Example 1: Roll number as the primary key

● Easy💼 Real project: Exam roll number register
The board gives roll numbers, so they are the natural primary key. A second student with the same roll is refused.
⚠ The error in this example is on purpose.
ex01.sql
REAL RUN
✍ Try it yourself Fix the third INSERT so Rohit gets roll 2611003.
Change only the roll number.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 2 of 10  •  Easy

Example 2: Unique mobile numbers

● Easy💼 Real project: Login by mobile / OTP apps
Apps that log in with OTP need one account per mobile. UNIQUE makes the database enforce it.
⚠ The error in this example is on purpose.
ex02.sql
REAL RUN
✍ Try it yourself Add an email column that is UNIQUE but optional. Insert two users without email - does it fail?
No: UNIQUE allows many NULLs.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 3 of 10  •  Easy

Example 3: NOT NULL name

● Easy💼 Real project: Patient registration
A patient without a name is useless. NOT NULL makes MySQL reject the row (ERROR 1048).
⚠ The error in this example is on purpose.
ex03.sql
REAL RUN
✍ Try it yourself Is an empty string '' accepted for a NOT NULL name? Try it.
Yes - '' is a value, not NULL. Add CHECK (name <> '') to block it.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 4 of 10  •  Easy

Example 4: CHECK marks between 0 and 100

● Easy💼 Real project: Result entry software
Teachers enter marks quickly and make typos like 910 instead of 91. A CHECK stops it immediately.
⚠ The error in this example is on purpose.
ex04.sql
REAL RUN
✍ Try it yourself Why does 910 fail even before the CHECK? Look at the error code.
TINYINT UNSIGNED only holds 0-255, so it is "Out of range" (1264). Try 150 to see the CHECK error 3819.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 5 of 10  •  Easy

Example 5: AUTO_INCREMENT order numbers

● Easy💼 Real project: Online order numbers
Orders often start from a big number so they look professional. AUTO_INCREMENT = 100001 sets the starting value. LAST_INSERT_ID() tells the app the number just created.
ex05.sql
REAL RUN
✍ Try it yourself Insert 3 orders in one statement. What does LAST_INSERT_ID() return now?
It returns the id of the FIRST row of a multi-row insert.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 6 of 10  •  Medium

Example 6: Students and fees with a foreign key

● Medium💼 Real project: Fee module of a school ERP
Every fee row must belong to a real student. The foreign key accepts student 1 and rejects student 50.
⚠ The error in this example is on purpose.
ex06.sql
REAL RUN
✍ Try it yourself Try to DELETE FROM students WHERE student_id = 1; What error do you get and why?
ERROR 1451 - Priya has a receipt, so the parent row is protected.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 7 of 10  •  Medium

Example 7: ON DELETE CASCADE for order items

● Medium💼 Real project: E-commerce order cleanup
Order items have no meaning without their order. With ON DELETE CASCADE, deleting an order deletes its items automatically.
ex07.sql
REAL RUN
✍ Try it yourself Change CASCADE to SET NULL. What happens to the items of order 1 now?
They stay, but their order_id becomes NULL (the column must allow NULL).
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 8 of 10  •  Medium

Example 8: Composite key for attendance

● Medium💼 Real project: Daily attendance app
One student, one record per day. The primary key is the pair (student_id, att_date). Marking the same student twice on one day is refused.
⚠ The error in this example is on purpose.
ex08.sql
REAL RUN
✍ Try it yourself Use an upsert so a teacher can correct today's mark instead of getting an error.
... VALUES (1,'2026-11-25','A') AS n ON DUPLICATE KEY UPDATE status = n.status;
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 9 of 10  •  Hard

Example 9: Library issue system with all constraints

● Hard💼 Real project: District library software
Members, books and issues. Rules: a book copy cannot be issued twice at once, return date must be after issue date, due date defaults to 14 days, and only real members and books can be issued.
⚠ The error in this example is on purpose.
ex09.sql
REAL RUN
✍ Try it yourself Add a rule that the same book cannot have two open issues. (Hint: UNIQUE on a generated column that is NULL when returned.)
Add open_book INT AS (IF(returned_on IS NULL, book_id, NULL)) UNIQUE.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Practice 10 of 10  •  Hard

Example 10: Reading every constraint error

● Hard💼 Real project: Support desk: explaining errors to users
On purpose, each INSERT breaks one rule. Learn the error numbers - you will see them in apps, logs and interviews.
⚠ The error in this example is on purpose.
ex10.sql
REAL RUN
✍ Try it yourself Write the fix for each failing line in the Lab.
Change the value that breaks the rule: new id, a name, an existing dept, a higher salary; delete staff before the dept.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. A column must never repeat but may be empty. Use...
✔ UNIQUE allows NULLs; PRIMARY KEY does not.
Q2. ERROR 1452 means...
✔ The foreign key value does not exist in the parent table.
Q3. Deleting an order should also delete its items. Use...
✔ CASCADE removes the child rows automatically.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M5Module summary

Recap: Keys & Constraints

What you learned in M5

  • ✔Constraints are rules the database checks on every INSERT and UPDATE.
  • ✔PRIMARY KEY = unique + not null; AUTO_INCREMENT numbers it.
  • ✔UNIQUE for mobile/email; NOT NULL for required; DEFAULT for usual values.
  • ✔CHECK (condition) works in MySQL 8.0.16+ and 9.x.
  • ✔FOREIGN KEY keeps child rows linked to real parents; choose CASCADE / SET NULL / RESTRICT.
  • ✔Know the errors: 1062, 1048, 1452, 1451, 3819.
🏆

Module 5 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M6 Built-in Functions: format names, round money, calculate ages and show rupees the Indian way.
Complete MySQL Course  |  Part 2  |  Keys & Constraints
M6

Built-in Functions

MySQL has hundreds of ready-made functions. Learn the ones you will use every week: join and clean text, round money, work with dates and ages, choose values with CASE, and print rupees in lakh-crore style.

  • String functions: CONCAT, UPPER, SUBSTRING, REPLACE, TRIM
  • Number functions: ROUND, CEIL, FLOOR, MOD
  • Date functions: NOW, DATEDIFF, DATE_ADD, DATE_FORMAT
  • Ages with TIMESTAMPDIFF
  • IF, CASE, IFNULL, COALESCE, NULLIF
  • CAST and type conversion
  • FORMAT with en_IN (12,34,567.00)
  • Cleaning messy imported data
YOU WILL BUILD:
Masked mobile numbersLibrary fine calculatorIndian rupee report
🧰
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M6Where is this used in real work?

Functions turn raw data into what users want to read

erp.brainbit-teaching.com/fee-reminders
StudentMobileDueAmountDays late
PRIYA KUMARI98XXXXX34510 Dec 2026, Thu₹ 4,500.000
AMAN RAJ94XXXXX33405 Nov 2026, Thu₹ 12,500.0020
UPPER(name)CONCAT(LEFT(..),'XXXXX',RIGHT(..))DATE_FORMATFORMAT(x,2,'en_IN')DATEDIFF
🔒

Privacy

Mobile and Aadhaar numbers are masked before showing them on screens and receipts.
📅

Dates everywhere

Due dates, ages, late fines, EMI dates, warranty expiry - all date functions.
🧹

Data cleaning

Excel imports have extra spaces, mixed case and blank cells. TRIM, UPPER and NULLIF fix them in one UPDATE.
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Concept

String functions

FunctionResult
CONCAT('Ranchi', '-', '834001')Ranchi-834001
CONCAT_WS(', ', a, b, c)joins with a separator, skips NULLs
UPPER('ranchi') / LOWER()RANCHI / ranchi
CHAR_LENGTH('Priya')5
SUBSTRING('9835012345', 1, 2)98
LEFT(s, 3) / RIGHT(s, 3)first / last 3 chars
REPLACE('Ranchi Jn', 'Jn', 'Junction')Ranchi Junction
TRIM(' Gaya ')'Gaya'
LPAD('7', 3, '0')007
LOCATE('@', email)position of @
strings.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Concept

Number functions

FunctionExampleResult
ROUND(x, d)ROUND(1234.567, 2)1234.57
TRUNCATE(x, d)TRUNCATE(1234.567, 1)1234.5 (cut, no rounding)
CEIL(x) / FLOOR(x)CEIL(4.1) / FLOOR(4.9)5 / 4
MOD(a, b) or a % bMOD(17, 5)2 (remainder)
ABS(x), POW(a,b), SQRT(x)POW(1.01, 12)1.1268...
Where usedCEIL: "how many buses for 130 students at 50 seats?" MOD: even/odd roll numbers, every 3rd customer gets a gift. ROUND: bills and GST.
numbers.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Concept

Date and time functions

  • NOW() date+time, CURDATE() today.
  • DATEDIFF(later, earlier) = days between.
  • DATE_ADD(d, INTERVAL 15 DAY) or d + INTERVAL 1 MONTH.
  • TIMESTAMPDIFF(YEAR, dob, CURDATE()) = completed years (age).
  • DATE_FORMAT(d, '%d-%m-%Y') = Indian style. %D %M %Y = 25th November 2026.
  • DAYNAME(), MONTHNAME(), YEAR(), LAST_DAY().
Lab dateThese runs used the build date 25-11-2026. Your results change with your date.
dates.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Concept

Choosing values: IF, CASE, IFNULL, COALESCE, NULLIF

  • IF(cond, yes, no) - MySQL short form.
  • CASE WHEN ... THEN ... ELSE ... END - standard SQL, many branches. The first true WHEN wins.
  • IFNULL(x, 'N/A') - replace NULL. COALESCE(a, b, c) - first non-NULL of many (standard).
  • NULLIF(a, b) - NULL if a = b. Stops division by zero: x / NULLIF(y, 0).
📜 SQL standard vs MySQL
SQL:2023 standardCASE, COALESCE, NULLIF
MySQL 9.7All three, plus MySQL-only IF() and IFNULL()
case.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Animated explainer

Functions inside functions: read from the inside out

nested functions run inside-out
StepValue
raw' ranchi JN '
TRIM(...)'ranchi JN'
REPLACE(... , ' ', ' ')'ranchi JN'
UPPER(...)'RANCHI JN'
REPLACE(... , 'JN', 'JUNCTION')'RANCHI JUNCTION'
nested.sql
SELECT REPLACE(
         UPPER(
           REPLACE(
             TRIM('  ranchi   JN  '),
           '   ', ' ')
         ),
       'JN', 'JUNCTION') AS station;
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 1 of 10  •  Easy

Example 1: Full name from first and last name

● Easy💼 Real project: Certificates and ID cards
Forms often store first and last names separately. CONCAT joins them; CONCAT_WS adds the separator and quietly skips a missing middle name.
ex01.sql
REAL RUN
✍ Try it yourself Why is the middle column NULL for Anjali? Fix it with IFNULL.
CONCAT with any NULL gives NULL. Use IFNULL(middle_name, '').
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 2 of 10  •  Easy

Example 2: Round off a bill

● Easy💼 Real project: Restaurant and shop billing
Indian bills are usually rounded to the nearest rupee. The round-off amount is printed on the bill.
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show the payable amount rounded UP to the next 10 rupees (like many shops do).
CEIL(total / 10) * 10
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 3 of 10  •  Easy

Example 3: Age from date of birth

● Easy💼 Real project: Age eligibility checks (exams, sports, voting)
TIMESTAMPDIFF(YEAR, dob, date) gives completed years. We use a fixed date (cut-off date of a sports trial) so the answer does not change.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Find students who will be 17 or older on 1 April 2027.
WHERE TIMESTAMPDIFF(YEAR, dob, '2027-04-01') >= 17
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 4 of 10  •  Easy

Example 4: Mask a mobile number

● Easy💼 Real project: Receipts, SMS and public lists
Show only the first 2 and last 3 digits. The real number stays in the table; only the output is masked.
ex04.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Mask emails as pri***@gmail.com (first 3 letters + *** + domain).
CONCAT(LEFT(email,3),'***',SUBSTRING(email, LOCATE('@', email)))
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 5 of 10  •  Easy

Example 5: Upper-case codes and clean PINs

● Easy💼 Real project: Address labels for courier
Courier labels need capital city names, a 2-letter state code and a 6-digit PIN with no spaces.
ex05.sql
REAL RUN
✍ Try it yourself Add a column that joins it all: RANCHI, JH - 834001.
CONCAT(UPPER(TRIM(city)), ', ', UPPER(LEFT(state,2)), ' - ', REPLACE(TRIM(pin),' ',''))
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 6 of 10  •  Medium

Example 6: Grade with CASE

● Medium💼 Real project: Report card generation
CASE checks the conditions top to bottom and stops at the first true one, so the order of WHENs matters. Students who did not take the test (NULL score) get "Absent". (The JOIN line fetches the student name - JOINs are explained in M8.)
ex06.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Move WHEN e.score >= 65 to the top. What goes wrong?
Everyone with 65+ becomes B - the first true WHEN wins.
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 7 of 10  •  Medium

Example 7: Indian rupee format (lakh and crore)

● Medium💼 Real project: Reports for Indian businesses
FORMAT(x, 2, 'en_IN') uses Indian digit grouping: 12,34,567.89 instead of 1,234,567.89. Add the ₹ sign with CONCAT.
ex07.sqlcompany_setup.sql
REAL RUN
✍ Try it yourself Show the total yearly salary bill of the company in Indian format.
SELECT FORMAT(SUM(salary)*12, 0, 'en_IN') FROM employees;
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 8 of 10  •  Medium

Example 8: Library fine by days late

● Medium💼 Real project: Library management software
Fine = Rs 2 per day after the due date, maximum Rs 100. GREATEST(0, ...) avoids negative fines for early returns; LEAST(..., 100) caps it.
ex08.sql
REAL RUN
✍ Try it yourself Change the rule to Rs 5 per day with a Rs 250 cap.
Change * 2 to * 5 and 100 to 250.
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 9 of 10  •  Hard

Example 9: Fee installment due-date reminders

● Hard💼 Real project: SMS reminder system
Each admission pays 3 installments: on admission, after 1 month and after 2 months. We build the SMS text with dates in Indian style and days left from a fixed "today".
ex09.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Add the weekday of the third due date (e.g. Monday) to the SMS text.
Use DAYNAME(admission_date + INTERVAL 2 MONTH) inside CONCAT.
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Practice 10 of 10  •  Hard

Example 10: Clean messy imported data

● Hard💼 Real project: Data migration from Excel / old software
An Excel import arrived with spaces, mixed case, "NA" for missing values and mobiles with +91. One UPDATE cleans every row using nested functions. NULLIF turns "NA" into a real NULL.
ex10.sql
REAL RUN
✍ Try it yourself The name is only capitalised at the start ("Ravi kumar"). How would you capitalise each word? (Hard - think about SUBSTRING_INDEX for first and last word.)
For two words: CONCAT(UPPER(LEFT(w1,1)),LOWER(SUBSTRING(w1,2)),' ',UPPER(LEFT(w2,1)),LOWER(SUBSTRING(w2,2)))
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. CONCAT('Ram', NULL, 'Kumar') returns...
✔ Any NULL inside CONCAT makes the result NULL. CONCAT_WS skips NULLs.
Q2. Days between two dates?
✔ DATEDIFF returns whole days.
Q3. Indian grouping like 12,34,567?
✔ The 'en_IN' locale gives lakh-crore grouping.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 2  |  Built-in Functions
M6Module summary

Recap: Built-in Functions

What you learned in M6

  • ✔Text: CONCAT / CONCAT_WS, UPPER, SUBSTRING, LEFT/RIGHT, REPLACE, TRIM, LPAD.
  • ✔Numbers: ROUND for money, CEIL/FLOOR for counts, MOD for remainders.
  • ✔Dates: CURDATE, DATEDIFF, INTERVAL, TIMESTAMPDIFF, DATE_FORMAT.
  • ✔Logic: CASE (standard), IF, IFNULL, COALESCE, NULLIF.
  • ✔FORMAT(x, 2, 'en_IN') prints lakh/crore style.
  • ✔Nested functions run from the inside out - great for cleaning data.
🏆

Module 6 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M7 Aggregation & Grouping: totals, averages and counts per city, month or category - the heart of every report.
Complete MySQL Course  |  Part 2  |  Built-in Functions
M7

Aggregation & Grouping

Owners and principals do not read 10,000 rows - they want totals. COUNT, SUM, AVG, MIN and MAX with GROUP BY turn raw rows into the numbers that run a business.

  • COUNT(*) vs COUNT(column)
  • SUM, AVG, MIN, MAX
  • GROUP BY: one row per group
  • HAVING vs WHERE
  • The ONLY_FULL_GROUP_BY rule
  • WITH ROLLUP for grand totals
  • GROUP_CONCAT lists
  • Pivot reports with SUM(CASE ...)
YOU WILL BUILD:
Monthly sales reportFee collection summaryShop owner dashboard
📊
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M7Where is this used in real work?

Every dashboard number is an aggregate query

admin.jharkhandbazaar.in/dashboard
11
orders
₹52,350
sales
₹4,759
avg order
8
customers
April 202528,507
May 202523,843
SELECT MONTHNAME(order_date), SUM(qty*price) ... GROUP BY month;
📈

Business reports

Sales per day, per branch, per product. Tally, Zoho and every ERP run GROUP BY behind their reports.
🏫

School and government

Students per class, average marks per subject, beneficiaries per district - all COUNT and AVG with GROUP BY.
📊

Charts

A bar chart is just a GROUP BY result drawn as bars. Power BI and Excel send this SQL for you.
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Concept

The five aggregate functions

  • COUNT(*) counts rows. COUNT(email) counts only non-NULL emails. COUNT(DISTINCT city) counts different cities.
  • SUM(x), AVG(x) - total and average (NULLs are skipped).
  • MIN(x), MAX(x) - smallest and largest. Work on numbers, dates and text.
  • Without GROUP BY, the whole table becomes one group, so you get one row.
NULL trapAVG ignores NULLs. If absent students have NULL score, AVG is the average of those present - which is usually what you want, but know it!
aggregates.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Animated explainer

GROUP BY: rows into buckets, one answer per bucket

students (7 rows)
namecitymarks
PriyaRanchi91
AmanPatna78
SnehaRanchi85
RohitDhanbad64
RahulRanchi72
NehaGaya81
SahilRanchi90
➤
Ranchi: 91, 85, 72, 90
Patna: 78
Dhanbad: 64
Gaya: 81
➤
result: 1 row per city
citystudentsavg_marks
Ranchi484.5
Patna178.0
Dhanbad164.0
Gaya181.0
group.sql
SELECT city, COUNT(*) AS students, ROUND(AVG(marks),1) AS avg_marks
FROM students GROUP BY city;
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Concept

GROUP BY in SQL

  • Write the grouping column(s) in both SELECT and GROUP BY.
  • You can group by several columns: GROUP BY section, gender = one row per section-gender pair.
  • Sort the groups with ORDER BY - often by the aggregate: ORDER BY students DESC.
ONLY_FULL_GROUP_BYMySQL 8+/9 refuses SELECT city, name, COUNT(*) ... GROUP BY city - which name should it show for a city with 4 students? Error 1055. Old MySQL 5.x quietly picked a random name.
groupby.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Concept

WHERE vs HAVING

WHEREHAVING
Filtersrowsgroups
Runsbefore groupingafter grouping
Can use aggregates?❌ No✅ Yes: HAVING COUNT(*) > 3
ExampleWHERE city = 'Ranchi'HAVING AVG(marks) > 80
FROM➤WHERE➤GROUP BY➤HAVING➤SELECT➤ORDER BY➤LIMIT

Full run order of a SELECT. WHERE throws away rows early (fast); HAVING judges whole groups.

having.sql
SELECT city, COUNT(*) AS students
FROM students
WHERE marks >= 60          -- rows first
GROUP BY city
HAVING COUNT(*) >= 2       -- then groups
ORDER BY students DESC;
TipIf a condition does not need an aggregate, put it in WHERE. It is faster because fewer rows are grouped.
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Concept

WITH ROLLUP, GROUPING() and GROUP_CONCAT

  • WITH ROLLUP adds subtotal and grand-total rows. The total row shows NULL in the grouped column.
  • GROUPING(col) is 1 on those total rows - use it to print "TOTAL" instead of NULL.
  • GROUP_CONCAT(name ORDER BY name SEPARATOR ', ') joins the values of each group into one text.
📜 SQL standard vs MySQL
SQL:2023 standardGROUP BY ROLLUP(mode), LISTAGG(name, ', ')
MySQL 9.7GROUP BY mode WITH ROLLUP, GROUP_CONCAT(name SEPARATOR ', ')
rollup.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 1 of 10  •  Easy

Example 1: How many students?

● Easy💼 Real project: Admission office counters
COUNT answers "how many". Add WHERE to count a part of the table.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Count students born in 2009.
WHERE YEAR(dob) = 2009
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 2 of 10  •  Easy

Example 2: Total fees collected

● Easy💼 Real project: Accounts summary
SUM adds money; ROUND keeps it neat. Filter by date range for "this month".
ex02.sqlschool_setup.sql
REAL RUN
✍ Try it yourself What was collected through UPI only?
WHERE mode = 'UPI'
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 3 of 10  •  Easy

Example 3: Average, best and worst score per course

● Easy💼 Real project: Teacher performance review
Grouping enrollments by course gives one row per course. NULL scores (absent) are ignored by AVG, MIN and MAX.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Sort the courses by average score, best first.
ORDER BY avg_score DESC
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 4 of 10  •  Easy

Example 4: Cheapest and costliest product

● Easy💼 Real project: Price range filter on a website
MIN and MAX tell the website what range to show on the price slider - for all products and per category.
ex04.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Also show the total stock value (price × stock) per category.
SUM(price * stock) AS stock_value
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 5 of 10  •  Easy

Example 5: Students per city

● Easy💼 Real project: Transport planning
The bus coordinator needs a count per city, most first. The chart below is drawn from this real result.
ex05.sqlschool_setup.sql
REAL RUN
Chart of the real result
Ranchi4
Bokaro1
Dhanbad1
Dumka1
Gaya1
Hazaribagh1
Jamshedpur1
Khunti1
Patna1
✍ Try it yourself Show only cities with more than one student.
HAVING COUNT(*) > 1 (after GROUP BY).
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 6 of 10  •  Medium

Example 6: Monthly sales report

● Medium💼 Real project: Owner's monthly MIS report
Join orders with their items, skip cancelled orders, and group by month. DATE_FORMAT(order_date, '%Y-%m') makes a sortable month label.
ex06.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Make the same report per payment mode instead of per month.
Replace the month expression with o.payment_mode in SELECT and GROUP BY.
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 7 of 10  •  Medium

Example 7: Popular courses with HAVING

● Medium💼 Real project: Deciding which batches to run
Only courses with at least 3 students get a new batch. WHERE cannot do this (it does not know the counts yet); HAVING can.
⚠ The error in this example is on purpose.
ex07.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Find courses whose average score is above 85.
HAVING AVG(score) > 85
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 8 of 10  •  Medium

Example 8: Category totals with a grand total

● Medium💼 Real project: Stock valuation for the accountant
WITH ROLLUP adds the final "all categories" row - no separate query needed. GROUPING() labels it.
ex08.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Group by category and brand with ROLLUP. How many total rows appear?
You get brand rows, a subtotal per category, and one grand total.
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 9 of 10  •  Hard

Example 9: Pivot: payment modes by month

● Hard💼 Real project: Finance pivot table (like Excel)
Conditional aggregation: SUM(CASE WHEN mode = 'UPI' THEN amount ELSE 0 END) puts each mode in its own column - exactly an Excel pivot table, made by SQL.
ex09.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Make a pivot of students: rows = section, columns = boys and girls.
SUM(gender = 'M') AS boys, SUM(gender = 'F') AS girls (true counts as 1).
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Practice 10 of 10  •  Hard

Example 10: Dashboard numbers for a shop owner

● Hard💼 Real project: Admin dashboard of an online shop
One query fills the 6 tiles of a dashboard. Sub-selects (bracketed SELECTs, M9) each return one number.
ex10.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Add a tile for "UPI share of orders in %".
(SELECT ROUND(100*SUM(payment_mode='UPI')/COUNT(*),1) FROM orders)
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. COUNT(email) counts...
✔ COUNT(column) skips NULLs; COUNT(*) counts every row.
Q2. Filter groups with average marks above 80 using...
✔ Aggregates are allowed in HAVING, not WHERE.
Q3. Which adds a grand-total row?
✔ WITH ROLLUP adds subtotal / total rows.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M7Module summary

Recap: Aggregation & Grouping

What you learned in M7

  • ✔COUNT, SUM, AVG, MIN, MAX summarise many rows into one value.
  • ✔GROUP BY makes one result row per group (city, month, course...).
  • ✔Every SELECT column must be grouped or aggregated (ONLY_FULL_GROUP_BY).
  • ✔WHERE filters rows before grouping; HAVING filters groups after.
  • ✔WITH ROLLUP + GROUPING() for totals; GROUP_CONCAT for lists.
  • ✔SUM(CASE WHEN ...) builds pivot-table reports.
🏆

Module 7 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M8 Joining Tables: combine students with courses, orders with customers, and employees with their managers.
Complete MySQL Course  |  Part 2  |  Aggregation & Grouping
M8

Joining Tables

Real data lives in many tables: students in one, courses in another, fees in a third. JOINs bring them together - the single most important skill for reports and apps.

  • Why data is split into tables
  • INNER JOIN and table aliases
  • LEFT and RIGHT JOIN
  • Finding missing rows (anti-join)
  • Joining 3 or more tables
  • SELF JOIN: employee and manager
  • CROSS JOIN
  • FULL OUTER JOIN: standard vs MySQL
YOU WILL BUILD:
Invoice from 4 tablesCustomers who never orderedOrg chart with managers
🔗
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M8Where is this used in real work?

One invoice = four tables joined

bazaar.jharkhand.shop/invoice/1004
TAX INVOICE #1004 07 Apr 2025
Bill to: Deepa Tirkey
Jamshedpur customers
Order status: Shipped
Paid by UPI orders
Item productsQty order_itemsAmount
Tussar Silk Saree14,500.00
Thekua Pack 500g2440.00
Total4,940.00
🧾

Invoices and receipts

Customer name, order details and product names come from different tables and are joined at print time.
🏫

Report cards

Student + enrollments + courses + teachers = one report card row. That is a 4-table JOIN.
💼

Interview favourite

INNER vs LEFT JOIN and "find customers who never ordered" are asked in almost every SQL interview.
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Concept

Why split data into many tables?

one big table (bad)
order_idcustomercitymobileitem
1001Ravi KumarRanchi9835098350Rice
1001Ravi KumarRanchi9835098350Oil
1003Ravi KumarRanchi Jn9835098350Kurta
ProblemsRavi's name, city and mobile are typed again for every item. If he changes his mobile we must update many rows - and one typo ("Ranchi Jn") makes the data disagree.
customers
customer_idnamecity
1Ravi KumarRanchi
↕ customer_id
orders
order_idcustomer_idorder_date
100112025-04-02
100312025-04-05
BetterStore each fact once. Link tables with keys. Then use a JOIN to put them back together when you need a report. (Design rules: M12.)
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Animated explainer

INNER JOIN: matching rows step by step

students s
student_idname
1Priya
2Aman
10Arjun
6Vikash
enrollments e
student_idcourse_id
1101
1104
2101
2103
➤
result
namecourse_id
Priya101
Priya104
Aman101
Aman103
LEFT JOIN result would addArjun | NULL and Vikash | NULL
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Concept

INNER JOIN in SQL

  • FROM a JOIN b ON a.key = b.key - JOIN means INNER JOIN.
  • Aliases (students s) keep queries short. Prefix columns with the alias: s.name.
  • If both tables have the same column name, the prefix is required (otherwise ERROR 1052 "ambiguous").
  • USING (student_id) is a short form when the column names are the same.
join.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Concept

The join family

AB
INNER JOIN
only matching rows
AB
LEFT JOIN
all of A + matches from B
AB
RIGHT JOIN
all of B + matches from A
AB
LEFT JOIN ... WHERE b.key IS NULL
A rows with NO match
AB
FULL OUTER JOIN
everything from both
✖️

CROSS JOIN

Every row of A with every row of B (no ON). 6 classes × 5 periods = 30 timetable slots.
👪

SELF JOIN

A table joined with itself using two aliases: employee e and manager m.
📜 SQL standard vs MySQL
SQL:2023 standardA FULL OUTER JOIN B ON ...
MySQL 9.7No FULL OUTER JOIN. Write A LEFT JOIN B ... UNION A RIGHT JOIN B ... (see Example 10).
Most usedINNER and LEFT JOIN cover about 95% of real queries. RIGHT JOIN can always be rewritten as a LEFT JOIN by swapping tables.
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Concept

LEFT JOIN keeps every row of the left table

  • All rows of the left table (written first) appear, matched or not.
  • Where there is no match, the right-side columns are NULL.
  • COUNT(e.enroll_id) then gives 0 for courses with nobody, because COUNT skips NULLs. COUNT(*) would wrongly give 1!
Watch the WHEREA condition on the right table in WHERE (e.g. WHERE e.score > 50) removes the NULL rows and turns your LEFT JOIN back into an INNER JOIN. Put such conditions in the ON clause instead.
leftjoin.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 1 of 10  •  Easy

Example 1: Students with their course names

● Easy💼 Real project: Batch-wise class lists
enrollments only has ids. Two joins add the student name and the course name.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Show only the students of "Spoken English".
WHERE c.course_name = 'Spoken English'
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 2 of 10  •  Easy

Example 2: Orders with customer names

● Easy💼 Real project: Order list in the admin panel
Each order has a customer_id; the join brings the customer's name and city.
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show the April orders of customers from Ranchi only.
WHERE c.city = 'Ranchi' AND o.order_date < '2025-05-01'
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 3 of 10  •  Easy

Example 3: Products with their category

● Easy💼 Real project: Product catalogue page
A category name is stored once in categories; products only keep its id.
ex03.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Count products per category name.
SELECT cat.name, COUNT(*) ... GROUP BY cat.name
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 4 of 10  •  Easy

Example 4: Employees with their department

● Easy💼 Real project: HR staff directory
USING (dept_id) is the short form of ON e.dept_id = d.dept_id when both columns have the same name.
ex04.sqlcompany_setup.sql
REAL RUN
✍ Try it yourself Show employees who work in a department located in Ranchi.
WHERE d.location = 'Ranchi'
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 5 of 10  •  Easy

Example 5: All courses, even with no students

● Easy💼 Real project: Course popularity report
Hindi Vyakaran has no enrollment yet. INNER JOIN would hide it; LEFT JOIN shows it with 0.
ex05.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Change LEFT JOIN to JOIN. Which course disappears?
Hindi Vyakaran - INNER JOIN drops courses without enrollments.
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 6 of 10  •  Medium

Example 6: Customers who never ordered

● Medium💼 Real project: Win-back marketing campaign
The classic anti-join: LEFT JOIN, then keep only rows where the right side is NULL. These customers get a discount SMS.
ex06.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Find products that were never ordered.
LEFT JOIN order_items i ON i.product_id = p.product_id WHERE i.product_id IS NULL
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 7 of 10  •  Medium

Example 7: Invoice: order + items + products

● Medium💼 Real project: GST invoice printing
Four tables in one query print the invoice of order 1004. The second query adds the bill total with GROUP BY.
ex07.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Print the invoice of order 1011 and add the category name of each item.
Add JOIN categories cat ON cat.category_id = p.category_id.
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 8 of 10  •  Medium

Example 8: Employee and manager (self join)

● Medium💼 Real project: Org chart and approval flow
Each employee row stores its manager's emp_id. Joining the table to itself (aliases e and m) shows both names. LEFT JOIN keeps the CEO, who has no manager.
ex08.sqlcompany_setup.sql
REAL RUN
✍ Try it yourself Count how many people report to each manager.
GROUP BY m.name on an INNER JOIN, COUNT(*).
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 9 of 10  •  Hard

Example 9: Class timetable grid (CROSS JOIN)

● Hard💼 Real project: School timetable generator
CROSS JOIN makes every combination: 3 sections × 4 periods = 12 slots. Then a LEFT JOIN fills the subjects already planned; empty slots show "-- free --".
ex09.sql
REAL RUN
✍ Try it yourself Count the free periods per section.
Add WHERE pl.subject IS NULL and GROUP BY s.section.
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Practice 10 of 10  •  Hard

Example 10: Full sales report from 5 tables + FULL OUTER JOIN

● Hard💼 Real project: Management sales review
Sales per category and city from customers, orders, order_items, products and categories. Then the FULL OUTER JOIN emulation: LEFT JOIN UNION RIGHT JOIN lists every category and every city pair even with no sales.
ex10.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Add the number of orders (COUNT DISTINCT order_id) to the first report.
COUNT(DISTINCT o.order_id) AS orders
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Which join keeps ALL rows of the first table?
✔ Unmatched rows get NULLs on the right side.
Q2. Customers with no orders: LEFT JOIN orders o ... WHERE ...
✔ No match = NULL in the right table's columns.
Q3. MySQL has no FULL OUTER JOIN. Emulate it with...
✔ UNION combines both sides and removes duplicate rows.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 2  |  Joining Tables
M8Module summary

Recap: Joining Tables

What you learned in M8

  • ✔Data is split into tables to store each fact once; JOINs rebuild the full picture.
  • ✔INNER JOIN keeps matches only; LEFT JOIN keeps every left row (NULLs when no match).
  • ✔Anti-join: LEFT JOIN ... WHERE right.key IS NULL finds missing rows.
  • ✔Join 3-5 tables by chaining JOIN ... ON; use short aliases.
  • ✔SELF JOIN for hierarchies; CROSS JOIN for all combinations.
  • ✔FULL OUTER JOIN = LEFT JOIN UNION RIGHT JOIN in MySQL.
🏆

Module 8 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M9 Subqueries & Set Operations: queries inside queries, EXISTS, UNION, INTERSECT and EXCEPT.
Complete MySQL Course  |  Part 2  |  Joining Tables
1 / 1

✎ SQL Lab