PART 3 of 5  •  about 19 class hours

Advanced Queries & Design

Subqueries, CTEs and recursion, window functions, and how to design a database the professional way.

9

Subqueries & Set Operations

10 examples  •  5 h
10

Common Table Expressions & Recursion

10 examples  •  5 h
11

Window Functions

10 examples  •  5 h
12

Database Design & Normalization

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

Subqueries & Set Operations

Some questions need a question inside them: "students above the average", "products never sold", "top order of each customer". Subqueries and set operations answer them.

  • Subquery in WHERE (scalar and IN)
  • Correlated subqueries
  • EXISTS and NOT EXISTS
  • Derived tables in FROM
  • ANY and ALL
  • UNION vs UNION ALL
  • INTERSECT and EXCEPT (MySQL 8.0.31+)
  • LATERAL derived tables
YOU WILL BUILD:
Above-average listTop scorer per courseDuplicate registration finder
🧮
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M9Where is this used in real work?

Questions inside questions

erp.brainbit-teaching.com/reports/above-average
🏆 Students above class average (76.3)
NameMarks
Pooja Singh95
Priya Kumari91
Sahil Ansari90
......
... WHERE marks > (SELECT AVG(marks) FROM students)
🎯

Compare with a calculated value

Above average, below target, more than last year - the inner query calculates the value first.
🔎

Exists / does not exist

Customers with at least one order, products never sold, students with no fee paid.
🔗

Combine lists

Merge two branch lists (UNION), find common members (INTERSECT), or the difference (EXCEPT).
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Concept

Subquery in WHERE: scalar and IN

  • A subquery is a SELECT inside brackets. MySQL runs the inner one first and uses its answer.
  • Scalar subquery returns one value: WHERE marks > (SELECT AVG(marks) FROM students).
  • IN subquery returns a list: WHERE student_id IN (SELECT student_id FROM fees).
  • If a scalar subquery returns more than one row: ERROR 1242.
subquery.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Animated explainer

Correlated subquery: the inner query uses the outer row

outer query: each enrollment
namecoursescore
Priya10192
Aman10174
Pooja10197
Sneha10591
Pooja10595
inner query runs again for EACH outer row:
SELECT MAX(score) FROM enrollments
WHERE course_id = ?
...
Priya 92 = 97? ❌
Aman 74 = 97? ❌
Pooja 97 = 97? ✅ top of 101
Sneha 91 = 95? ❌
Pooja 95 = 95? ✅ top of 105
correlated.sql
SELECT s.name, e.course_id, e.score FROM enrollments e JOIN students s USING (student_id)
WHERE e.score = (SELECT MAX(e2.score) FROM enrollments e2 WHERE e2.course_id = e.course_id);
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Concept

EXISTS and NOT EXISTS

  • EXISTS (subquery) is true if the subquery returns at least one row. The columns it selects do not matter - write SELECT 1.
  • NOT EXISTS finds rows with no match - like the LEFT JOIN anti-join in M8.
  • Safer than NOT IN: if the list contains a NULL, NOT IN returns no rows at all!
NOT IN + NULL trapWHERE id NOT IN (1, 2, NULL) is never true. Use NOT EXISTS when the subquery column can be NULL.
exists.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Concept

Derived tables, ANY and ALL

  • A subquery in FROM is a derived table. It needs an alias: FROM (SELECT ...) AS t.
  • Great for "aggregate of an aggregate": average of order totals.
  • > ALL (subquery) = bigger than every value. > ANY (...) = bigger than at least one.
derived.sqlbazaar_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Concept

Set operations: UNION, INTERSECT, EXCEPT

OperationResultDuplicates
A UNION Brows in A or Bremoved
A UNION ALL Brows in A or Bkept (faster)
A INTERSECT Brows in bothremoved
A EXCEPT Brows in A, not in Bremoved
RulesBoth SELECTs need the same number of columns with compatible types. Column names come from the first SELECT. ORDER BY goes at the very end.
📜 SQL standard vs MySQL
SQL:2023 standardUNION, INTERSECT, EXCEPT (+ ALL versions)
MySQL 9.7All supported since MySQL 8.0.31. Older servers: use IN / NOT EXISTS instead.
AB
UNION
AB
INTERSECT
AB
A EXCEPT B
AB
UNION ALL (keeps both copies)
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 1 of 10  •  Easy

Example 1: Students above the class average

● Easy💼 Real project: Merit recognition
The inner query calculates the average once; the outer query compares every student with it. A second scalar subquery shows the average next to each name.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Find students below the average of their own section. (Hint: correlated - compare with the same section.)
WHERE marks < (SELECT AVG(marks) FROM students s2 WHERE s2.section = s.section)
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 2 of 10  •  Easy

Example 2: The most expensive product

● Easy💼 Real project: Featured product banner
MAX alone gives the price but not the name. A subquery finds the row that has the max price.
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show the cheapest product in the Electronics category (id 2).
Add AND category_id = 2 in both the outer and inner query.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 3 of 10  •  Easy

Example 3: Customers who ordered at least once

● Easy💼 Real project: Active customer list
IN (subquery) builds the list of customer ids from orders. DISTINCT is not needed - IN ignores repeats.
ex03.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Rewrite it with EXISTS.
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id AND ...)
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 4 of 10  •  Easy

Example 4: UNION of two branch lists

● Easy💼 Real project: Merging data from two branches
The Ranchi and Patna branches keep separate tables. UNION gives one list with no duplicates; UNION ALL keeps both copies of a student registered at both.
ex04.sql
REAL RUN
✍ Try it yourself Use INTERSECT to find students registered at both branches.
SELECT name, mobile FROM ranchi_branch INTERSECT SELECT name, mobile FROM patna_branch;
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 5 of 10  •  Easy

Example 5: Products never sold

● Easy💼 Real project: Dead stock report
NOT EXISTS keeps products for which no order_items row exists. The shop can put them on sale.
ex05.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Write the same with NOT IN. Is it safe here? (Can order_items.product_id be NULL?)
It is part of the primary key, so never NULL - NOT IN is safe here.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 6 of 10  •  Medium

Example 6: Top scorer in each course (correlated)

● Medium💼 Real project: Course-wise toppers board
For each enrollment, the inner query finds the best score of that course. Ties would show both toppers.
ex06.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Show the lowest scorer per course instead (ignore NULL scores).
Use MIN; NULLs are skipped automatically.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 7 of 10  •  Medium

Example 7: Students in both Maths and Computer (INTERSECT)

● Medium💼 Real project: Combo-course discount eligibility
INTERSECT keeps ids present in both lists. EXCEPT gives Maths students who did not take Computer - a list for the sales team.
ex07.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Find students in Python (105) but not in Maths (101).
SELECT ... course_id = 105 EXCEPT SELECT ... course_id = 101
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 8 of 10  •  Medium

Example 8: Average of order totals (derived table)

● Medium💼 Real project: Average basket size (AOV)
First total each order (inner query), then average those totals (outer query). You cannot write AVG(SUM(...)) directly.
ex08.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Try SELECT AVG(SUM(qty*price)) FROM order_items GROUP BY order_id; What error do you get?
ERROR 1111: Invalid use of group function.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 9 of 10  •  Hard

Example 9: Top 2 orders per customer (LATERAL)

● Hard💼 Real project: Customer profile page: "recent big orders"
A LATERAL derived table can use columns of the table before it - like a correlated subquery that returns several rows and columns. Here: the 2 biggest orders of each customer.
ex09.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Change it to show only the single latest order (by date) per customer.
ORDER BY o.order_date DESC LIMIT 1 inside the LATERAL query.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Practice 10 of 10  •  Hard

Example 10: Find duplicate registrations

● Hard💼 Real project: Data quality check before a scholarship payment
The same mobile registered twice may mean double payment. GROUP BY + HAVING finds the duplicated mobiles; an IN subquery lists every row involved so an officer can decide.
ex10.sql
REAL RUN
✍ Try it yourself Delete the later duplicates and keep the first app_id of each mobile. (Careful: MySQL needs a derived table here.)
DELETE FROM applicants WHERE app_id NOT IN (SELECT keep FROM (SELECT MIN(app_id) keep FROM applicants GROUP BY mobile) t);
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Check your understanding

Quick Quiz

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

Q1. A subquery in FROM must have...
✔ FROM (SELECT ...) AS t - every derived table needs a name.
Q2. Which is safest to find rows with no match when NULLs are possible?
✔ NOT IN with a NULL in the list returns nothing.
Q3. UNION vs UNION ALL?
✔ UNION ALL keeps all rows and is faster.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M9Module summary

Recap: Subqueries & Set Operations

What you learned in M9

  • ✔A subquery is a SELECT in brackets: scalar (one value) or a list (IN).
  • ✔Correlated subqueries use the outer row and run once per row.
  • ✔EXISTS / NOT EXISTS test for matching rows; avoid NOT IN with NULLs.
  • ✔Derived tables (subquery in FROM) allow aggregates of aggregates.
  • ✔UNION / UNION ALL / INTERSECT / EXCEPT combine result sets (MySQL 8.0.31+).
  • ✔LATERAL lets a derived table use the outer row - "top N per group".
🏆

Module 9 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M10 Common Table Expressions & Recursion: name your subqueries with WITH, and walk org charts, category trees and date series.
Complete MySQL Course  |  Part 3  |  Subqueries & Set Operations
M10

Common Table Expressions & Recursion

WITH lets you name a sub-result and build a query in clear steps, like rough work in maths. Recursive CTEs go further: they can count, make calendars and walk family trees and org charts.

  • WITH: name a sub-query
  • Several CTEs in a chain
  • CTE vs derived table vs view
  • Recursive CTE: anchor + recursive part
  • Number and date series
  • Hierarchies: org chart, categories
  • Depth and path columns
  • Stopping recursion safely
YOU WILL BUILD:
Sales calendar with zero daysOrg chart with levelsEMI schedule
🌳
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M10Where is this used in real work?

Step-by-step queries and trees

hr.tprosys.in/org-chart
Nandini Sahay
CEO
Rajesh Mahto
CTO
Farhan Ali
Sales Head
Seema Kujur
Team Lead
Mamta Hansda
Support Lead
Pinky, Suraj
Sales
WITH RECURSIVE chart AS (... UNION ALL ...)
🧱

Readable reports

Long reports become a list of named steps: totals, then ranks, then the final filter. Easy to check and change.
🌳

Trees and hierarchies

Org charts, product categories, bill of materials, comment replies, referral chains.
📅

Series and calendars

Every day of the month (even days with no sales), every EMI month, every bus stop on a route.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Concept

WITH: give a sub-query a name

  • WITH name AS (SELECT ...) creates a temporary named result - a Common Table Expression (CTE).
  • The main query uses it like a table. It exists only for this one statement.
  • Several CTEs: WITH a AS (...), b AS (SELECT ... FROM a) - later ones can use earlier ones.
  • Part of the SQL standard; in MySQL since 8.0.
Why not a subquery?Same result, but a CTE reads top-to-bottom, can be used twice in one query, and can be recursive.
cte.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Animated explainer

Recursive CTE: how 1, 2, 3, 4, 5 is produced

recursive.sql
WITH RECURSIVE nums (n) AS (
  SELECT 1                 -- anchor
  UNION ALL
  SELECT n + 1 FROM nums   -- recursive part
  WHERE n < 5              -- stop condition
)
SELECT n FROM nums;
nums (grows each round)
nmade by
1anchor
2n = 1 + 1
3n = 2 + 1
4n = 3 + 1
5n = 4 + 1
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Concept

Recursive CTE for a hierarchy

  • Anchor: the top person (manager_id IS NULL).
  • Recursive part: employees whose manager is already in the result - JOIN the table to the CTE.
  • Add lvl + 1 for the level and CONCAT(path, ' > ', name) for the path.
  • Safety net: cte_max_recursion_depth (default 1000) stops endless loops with ERROR 3636.
orgchart.sqlcompany_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Concept

CTE, derived table or view?

Derived tableCTE (WITH)View (M13)
Writteninside FROM ( ... ) tbefore the SELECTCREATE VIEW once
Lives forone statementone statementstored in the database
Use twice in a query❌ copy it✅ yes✅ yes
Recursive❌✅ WITH RECURSIVE❌ (but a view can contain one)
Best forsmall one-off stepslong reports, trees, seriesreused reports, security
💡

Rule of thumb

If you read your query and lose track of brackets, turn the inner parts into CTEs.
⚠️

Recursion limit

Generating 5,000 dates? Run SET cte_max_recursion_depth = 10000; first.
📜

Standard SQL

WITH and WITH RECURSIVE are standard; the same query works in PostgreSQL and SQL Server (without the word RECURSIVE there).
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 1 of 10  •  Easy

Example 1: Your first CTE: toppers

● Easy💼 Real project: Clean, readable merit report
Step 1 (the CTE) picks students with 85+. Step 2 (the main query) sorts and labels them. Each part is easy to test alone.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Add a second CTE top_per_section that counts toppers per section, and select from it.
WITH toppers AS (...), top_per_section AS (SELECT section, COUNT(*) n FROM toppers GROUP BY section) SELECT * FROM top_per_section;
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 2 of 10  •  Easy

Example 2: Two CTEs: totals, then ranking

● Easy💼 Real project: Best customers report
The first CTE totals each customer's spending; the second keeps only big spenders; the main query adds names.
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Change the limit to Rs 2,000. How many customers now?
Edit only the number in the big CTE.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 3 of 10  •  Easy

Example 3: Numbers 1 to 10

● Easy💼 Real project: Test data and serial numbers
The smallest recursive CTE. Developers use it to generate test rows, serial numbers and slots.
ex03.sql
REAL RUN
✍ Try it yourself Generate the even numbers from 2 to 20.
Start at 2 and add 2 each time, stop when n < 20.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 4 of 10  •  Easy

Example 4: Multiplication table

● Easy💼 Real project: Primary school maths worksheet
A recursive CTE makes 1-10, and a calculated column builds each line of the table of 17.
ex04.sql
REAL RUN
✍ Try it yourself Print the table of 19 up to 20.
Change 17 to 19 and n < 10 to n < 20.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 5 of 10  •  Easy

Example 5: Dates of one week

● Easy💼 Real project: Weekly schedule screens
The anchor is a start date; each round adds 1 day. DAYNAME labels each date.
ex05.sql
REAL RUN
✍ Try it yourself Generate all dates of December 2026.
Anchor '2026-12-01', stop when d < '2026-12-31'.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 6 of 10  •  Medium

Example 6: Daily sales including zero days

● Medium💼 Real project: Sales trend chart without gaps
Charts look wrong if days without sales are missing. Generate every date, then LEFT JOIN the sales: missing days become 0.
ex06.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show the running total too. (Preview of M11: SUM(...) OVER (ORDER BY d).)
SUM(IFNULL(sales.amount,0)) OVER (ORDER BY days.d) AS running
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 7 of 10  •  Medium

Example 7: Organisation chart with levels and path

● Medium💼 Real project: HR org chart and approval chain
Starting from the CEO, each round adds the next layer of reportees. The path column shows the whole reporting chain.
ex07.sqlcompany_setup.sql
REAL RUN
✍ Try it yourself Show only the people in Rajesh Mahto's team (all levels below him).
Start the anchor at emp_id = 2 instead of the CEO.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 8 of 10  •  Medium

Example 8: Category breadcrumb path

● Medium💼 Real project: Shopping site breadcrumbs (Home > Electronics > Audio)
Categories nest inside categories. The recursive CTE walks up from a leaf to the root and builds the breadcrumb.
ex08.sql
REAL RUN
✍ Try it yourself Print the breadcrumb for Dokra Art (id 6).
Change id = 4 to id = 6 in the anchor.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 9 of 10  •  Hard

Example 9: EMI schedule with a recursive CTE

● Hard💼 Real project: Bike / education loan calculator
Loan Rs 1,00,000 at 12% a year for 6 months. EMI = P×r×(1+r)n/((1+r)n-1). Each round takes the previous balance, adds interest and subtracts the EMI. The last closing shows a few paise of rounding - real banks adjust the final EMI by that amount.
ex09.sql
REAL RUN
✍ Try it yourself Change the loan to Rs 2,50,000 for 12 months at 10.5%.
Edit only @P, @r and @n in the first line.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Practice 10 of 10  •  Hard

Example 10: Bus route stops from Ranchi to Patna

● Hard💼 Real project: Bus ticket booking (route planner)
Each row says "from this stop the bus goes next to ...". Following the links from Ranchi gives the ordered list of stops with distance so far. The visited-path check prevents endless loops. Note the CAST in the anchor: the anchor decides the column type, so it must be wide enough for longer names.
ex10.sql
REAL RUN
✍ Try it yourself Add a ticket fare of Rs 1.6 per km for each stop.
ROUND(total_km * 1.6) AS fare
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Check your understanding

Quick Quiz

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

Q1. A recursive CTE needs...
✔ The anchor starts it; the recursive part repeats until no new rows.
Q2. What stops a recursive CTE?
✔ When the recursive part returns no rows, it stops.
Q3. Can a later CTE use an earlier CTE in the same WITH?
✔ WITH a AS (...), b AS (SELECT ... FROM a) is fine.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M10Module summary

Recap: Common Table Expressions & Recursion

What you learned in M10

  • ✔WITH name AS (SELECT ...) names a sub-result for one statement.
  • ✔Chain CTEs to write long reports as clear steps.
  • ✔WITH RECURSIVE = anchor + UNION ALL + recursive part + stop condition.
  • ✔Generate numbers and calendars; LEFT JOIN them to show zero days.
  • ✔Walk hierarchies with level and path columns.
  • ✔cte_max_recursion_depth protects against endless loops.
🏆

Module 10 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M11 Window Functions: ranks, running totals, moving averages and "top N per group" - without losing your rows.
Complete MySQL Course  |  Part 3  |  Common Table Expressions & Recursion
M11

Window Functions

Window functions calculate across related rows WITHOUT collapsing them: rank students, add running totals, compare today with yesterday, and pick the top 3 of every group. Analysts love them.

  • OVER(): group without collapsing
  • PARTITION BY
  • ROW_NUMBER, RANK, DENSE_RANK
  • NTILE and PERCENT_RANK
  • LAG and LEAD
  • Running totals
  • Frames: ROWS BETWEEN ... (moving average)
  • Named windows; top N per group
YOU WILL BUILD:
Class rank listRunning sales totalTop 3 per category
🪟
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M11Where is this used in real work?

Ranks, trends and running totals

analytics.jharkhandbazaar.in/sales
DateSalesRunning totalvs yesterday
01 Nov12,50012,500-
02 Nov9,80022,300▼ 2,700
03 Nov15,20037,500▲ 5,400
SUM(amount) OVER (ORDER BY sale_date), amount - LAG(amount) OVER (...)
🏅

Rank lists

Merit lists with ties, sales leaderboards, "rank in class" on report cards.
📈

Trends

Running totals, month-over-month growth, 7-day moving averages on dashboards.
🥇

Top N per group

Top 3 products per category, latest order per customer, best scorer per section - in one query.
Complete MySQL Course  |  Part 3  |  Window Functions
M11Animated explainer

GROUP BY collapses rows; a window keeps them

GROUP BY section
namesecmarks
Priya10-A91
Anjali10-A88
Aman10-A78
Sneha10-B85
Rahul10-B72
result: 2 rows
secAVG
10-A85.7
10-B78.5
window: all 5 rows stay
namesecmarkssec_avgrank
Priya10-A9185.71
Anjali10-A8885.72
Aman10-A7885.73
Sneha10-B8578.51
Rahul10-B7278.52
Complete MySQL Course  |  Part 3  |  Window Functions
M11Concept

OVER, PARTITION BY and ORDER BY

  • func() OVER () - the window is the whole result.
  • OVER (PARTITION BY col) - a separate window per value of col (like GROUP BY, without collapsing).
  • OVER (ORDER BY col) - order inside the window. Needed for ranks, LAG/LEAD and running totals.
  • Windows are calculated after WHERE and GROUP BY, so you cannot use them in WHERE - wrap the query in a CTE and filter outside.
over.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Window Functions
M11Concept

ROW_NUMBER, RANK and DENSE_RANK

marksROW_NUMBERRANKDENSE_RANK
95111
90222
90322
88443
  • ROW_NUMBER: 1, 2, 3 ... always unique (ties broken arbitrarily - add a second ORDER BY column).
  • RANK: ties share a rank, then a gap (sports style: 1, 2, 2, 4).
  • DENSE_RANK: ties share, no gap (1, 2, 2, 3).
ranks.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Window Functions
M11Animated explainer

Frames: the moving window of a moving average

01
12.5k
02
9.8k
03
15.2k
04
11.0k
05
18.9k
06
21.5k
frame.sql
AVG(amount) OVER (ORDER BY sale_date
                  ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS moving_avg_3
Complete MySQL Course  |  Part 3  |  Window Functions
M11Concept

LAG, LEAD, FIRST_VALUE and running totals

  • LAG(x) = value from the previous row; LEAD(x) = next row. Second argument = how many rows back/ahead.
  • SUM(x) OVER (ORDER BY d) = running total (default frame: start to current row).
  • FIRST_VALUE(x) = value of the first row of the window.
Watch the tiesWith ORDER BY and the default frame, rows with the same date are added together (RANGE frame). Use ROWS UNBOUNDED PRECEDING for a strict row-by-row running total.
lag.sqlsetup.sql
REAL RUN
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 1 of 10  •  Easy

Example 1: Number the rows

● Easy💼 Real project: Serial numbers on printed lists
ROW_NUMBER() OVER (ORDER BY ...) adds S.No. 1, 2, 3 to any list without changing the table.
ex01.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Number the products from costliest to cheapest.
ROW_NUMBER() OVER (ORDER BY price DESC)
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 2 of 10  •  Easy

Example 2: Rank students by marks

● Easy💼 Real project: School merit list
RANK gives equal marks the same rank. Our data has no ties in marks, so RANK equals ROW_NUMBER here.
ex02.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Use DENSE_RANK instead. Would the result change if two students had 90?
With a tie at 90: RANK 3,3,5 and DENSE_RANK 3,3,4.
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 3 of 10  •  Easy

Example 3: Rank within each section

● Easy💼 Real project: Section-wise rank on report cards
PARTITION BY section restarts the ranking for each section: every section has its own rank 1.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Also show the overall school rank in another column.
Add RANK() OVER (ORDER BY marks DESC) AS school_rank
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 4 of 10  •  Easy

Example 4: Running total of daily sales

● Easy💼 Real project: Month-to-date sales tracker
SUM with OVER(ORDER BY date) keeps adding: day 3 shows the total of days 1-3. PARTITION BY branch keeps the two branches separate.
ex04.sqlsetup.sql
REAL RUN
✍ Try it yourself Show the running total of both branches together (one company total).
Remove PARTITION BY branch and GROUP BY date first in a CTE.
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 5 of 10  •  Easy

Example 5: Percent of total

● Easy💼 Real project: Category share pie chart
SUM(x) OVER () is the grand total on every row, so each row can be divided by it to get its share.
ex05.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show each student's share of total fees paid.
SUM(amount) per student, divided by SUM(SUM(amount)) OVER ().
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 6 of 10  •  Medium

Example 6: Day-over-day change (LAG)

● Medium💼 Real project: Daily sales alert to the owner
LAG brings yesterday's amount onto today's row. The percentage change powers the green/red arrows on dashboards.
ex06.sqlsetup.sql
REAL RUN
✍ Try it yourself Use LEAD to show tomorrow's amount instead.
LEAD(amount) OVER w AS next_day
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 7 of 10  •  Medium

Example 7: Top 2 products per category

● Medium💼 Real project: Bestsellers per category on the home page
Window functions cannot go in WHERE, so rank inside a CTE, then keep rn <= 2 outside. This "top N per group" pattern is used everywhere.
ex07.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Change it to the 2 cheapest products per category.
ORDER BY p.price ASC inside OVER.
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 8 of 10  •  Medium

Example 8: 3-day moving average

● Medium💼 Real project: Smoothing a noisy sales chart
A moving average hides one-day spikes and shows the real trend. The frame ROWS 2 PRECEDING = today and the 2 days before.
ex08.sqlsetup.sql
REAL RUN
✍ Try it yourself Make it a centred average (yesterday, today, tomorrow).
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 9 of 10  •  Hard

Example 9: Merit list with ties and percentile

● Hard💼 Real project: Competitive exam results
A real merit list: dense rank for ties, percentile (how many you beat), and quartile groups for counselling rounds. Marks 90 is given to two students on purpose to show the tie. Notice NTILE splits the tied pair into quartiles 1 and 2 - use percentile when ties must stay together.
ex09.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Give "Round 1" to quartile 1, "Round 2" to quartile 2, others "Waitlist".
CASE NTILE(4) OVER w WHEN 1 THEN ... inside a CTE, or directly in SELECT.
Complete MySQL Course  |  Part 3  |  Window Functions
M11Practice 10 of 10  •  Hard

Example 10: Customer order gaps and streaks

● Hard💼 Real project: Customer retention (churn) analysis
For each customer, LAG gives the previous order date; DATEDIFF shows the gap. A long gap means the customer may be leaving - the marketing team calls them.
ex10.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show only each customer's LAST order and how many days ago it was from 2025-06-01.
Keep rows where nth = total_orders; DATEDIFF('2025-06-01', order_date).
Complete MySQL Course  |  Part 3  |  Window Functions
M11Check your understanding

Quick Quiz

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

Q1. Difference between GROUP BY and OVER(PARTITION BY)?
✔ Windows calculate per group but do not collapse rows.
Q2. Ranks 1, 2, 2, 3 come from...
✔ DENSE_RANK leaves no gaps after ties.
Q3. Previous row's value?
✔ LAG looks back, LEAD looks ahead.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 3  |  Window Functions
M11Module summary

Recap: Window Functions

What you learned in M11

  • ✔func() OVER (PARTITION BY ... ORDER BY ...) calculates per window, keeping rows.
  • ✔ROW_NUMBER / RANK / DENSE_RANK for lists; NTILE and PERCENT_RANK for groups and percentiles.
  • ✔LAG / LEAD compare with previous / next rows.
  • ✔SUM(...) OVER (ORDER BY ...) gives running totals.
  • ✔Frames (ROWS n PRECEDING) make moving averages.
  • ✔Top N per group = rank in a CTE, filter outside.
🏆

Module 11 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M12 Database Design & Normalization: design databases the professional way: ER diagrams and the normal forms.
Complete MySQL Course  |  Part 3  |  Window Functions
M12

Database Design & Normalization

Before writing CREATE TABLE, professionals draw the design. Learn to turn a real requirement into entities and relationships, draw an ER diagram, and remove repetition with the normal forms.

  • From a requirement to tables
  • Entities, attributes, relationships
  • ER diagrams (crow's foot)
  • 1:1, 1:N and M:N (junction tables)
  • Update, insert and delete anomalies
  • 1NF, 2NF, 3NF step by step
  • BCNF and when to denormalise
  • Naming rules; Workbench EER diagrams
YOU WILL BUILD:
Coaching institute schemaHospital OPD schemaOnline shop schema
📐
about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M12Where is this used in real work?

Design first, code later

Requirement from a coaching centre in Lalpur, Ranchi:
"We have students and courses. A student can join many courses and a course has many students. Each course has one teacher. Students pay fees in installments. We want attendance per class."
nouns → tablesverbs → relationshipsdetails → columns
students
student_id PK
name
mobile
enrollments
student_id FK
course_id FK
courses
course_id PK
teacher_id FK
💰

Cheaper to fix on paper

Changing a design after 2 lakh rows and 3 apps use it costs weeks. Changing a diagram costs minutes.
🧹

No repeated data

A well designed database stores each fact once, so it never disagrees with itself.
💼

A senior skill

Database design is what separates a developer who writes queries from one who leads projects.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Concept

ER diagrams: entities, attributes and relationships

students
student_id INT PK
name VARCHAR
mobile CHAR(10)
section_id INT FK
>──│
many students
belong to one section
sections
section_id INT PK
title VARCHAR
room VARCHAR
TermMeaningBecomes
Entitya thing we store (student, course)a table
Attributea property (name, fee)a column
Relationshiphow entities connect (joins, pays)a foreign key or junction table
Cardinalityhow many: 1:1, 1:N, M:Nwhere the FK goes
🔽

Crow's foot notation

A line with a "crow's foot" (>) on one end means "many" on that side. A single bar means "one". It is the most used notation in industry and in MySQL Workbench.
🛠️

Tools

MySQL Workbench: Database > Reverse Engineer draws the diagram of an existing database. Forward Engineer creates tables from a diagram. Also: draw.io, dbdiagram.io, paper!
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Concept

Three kinds of relationships

1️⃣

One-to-one (1:1)

One student has one hostel bed. Put a UNIQUE foreign key on one side: beds.student_id UNIQUE. Often used to split rarely used columns into a side table.
👥

One-to-many (1:N)

One section has many students. The foreign key goes on the many side: students.section_id. The most common relationship.
🔀

Many-to-many (M:N)

Students take many courses; courses have many students. Needs a junction table enrollments(student_id, course_id) with two foreign keys.
students
student_id PK
name
│──<
enrollments
student_id PK, FK
course_id PK, FK
enroll_date
score
>──│
courses
course_id PK
course_name
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Animated explainer

Anomalies: what goes wrong in a badly designed table

bills (unnormalised)
bill_nocustomermobileitems
1Ravi98350..Rice, Oil
2Ravi98350..Kurta
3Sunita94310..Bulb x10
1NF: list in a cell
Update anomaly: data disagrees
Insert anomaly: cannot add a customer alone
Delete anomaly: losing a bill loses the customer
customersbillsbill_itemsproducts
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Concept

Normal forms in plain words

FormRule (simple words)Fix
1NFOne value per cell; no repeating groups (item1, item2, item3)Move lists into rows of a child table
2NF1NF + every non-key column depends on the whole key (matters for composite keys)Move columns that depend on part of the key
3NF2NF + no column depends on another non-key columnMove "facts about facts" to their own table
BCNFStricter 3NF: every determinant is a keyRarely needed in normal business apps
Memory lineEvery column must depend on the key, the whole key, and nothing but the key.
⚖️

When to denormalise

Reports on crores of rows may store a pre-calculated total (e.g. orders.total_amount) to avoid joins. Do it on purpose, document it, and keep it in sync (triggers, M15).
🏷️

Naming conventions

Tables plural, snake_case (order_items); PK table_id; FK same name as the PK it points to; dates end with _on / _at; booleans start with is_.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 1 of 10  •  Easy

Example 1: Split a messy register into two tables

● Easy💼 Real project: Moving from Excel to a database
The old register repeats the teacher's phone for every course. We create a teachers table and keep only teacher_id in courses. The JOIN rebuilds the old view.
ex01.sql
REAL RUN
✍ Try it yourself Add a teacher with no course yet. Was that possible in the old one-table register?
Yes now - insert into teachers only. In the old register, no (insert anomaly).
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 2 of 10  •  Easy

Example 2: One-to-many: sections and students

● Easy💼 Real project: School class allocation
One section, many students: the foreign key section_id lives in the students table (the "many" side).
ex02.sql
REAL RUN
✍ Try it yourself Move Aman to section 10-B with one UPDATE.
UPDATE students SET section_id = 2 WHERE student_id = 2;
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 3 of 10  •  Easy

Example 3: Many-to-many: students and clubs

● Easy💼 Real project: School clubs and activities
A student can join many clubs and a club has many students. The junction table memberships has a composite primary key so nobody joins the same club twice.
ex03.sql
REAL RUN
✍ Try it yourself List each student with all their clubs.
GROUP BY s.name and GROUP_CONCAT(c.club).
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 4 of 10  •  Easy

Example 4: One-to-one: student and hostel bed

● Easy💼 Real project: Hostel management
Each bed holds one student and each student has at most one bed. A UNIQUE foreign key turns 1:N into 1:1. Booking a second bed for Priya fails.
⚠ The error in this example is on purpose.
ex04.sql
REAL RUN
✍ Try it yourself Free bed G-101 (Priya leaves the hostel).
UPDATE beds SET student_id = NULL WHERE bed_no = 'G-101';
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 5 of 10  •  Easy

Example 5: Lookup table for cities

● Easy💼 Real project: Dropdown lists in forms
Typing the city in every row gives "Ranchi", "ranchi", "Ranchi Jn". A lookup table + foreign key makes the form show a dropdown and keeps names consistent.
ex05.sql
REAL RUN
✍ Try it yourself Rename "Kanke" to "Kanke Block" - how many rows do you update?
Only one row in cities, however many customers live there.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 6 of 10  •  Medium

Example 6: Fix a 1NF violation (comma lists)

● Medium💼 Real project: Cleaning an old system before migration
An old app stored subjects as "Maths,Science". Recursive splitting is complex; MySQL's JSON_TABLE (M17) can turn the list into rows in one go. Then we store them properly - one row per subject.
ex06.sql
REAL RUN
✍ Try it yourself Try counting Science students in the OLD table. Which is easier?
Old: WHERE FIND_IN_SET('Science', subjects) - slow and error-prone.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 7 of 10  •  Medium

Example 7: Fix 2NF and 3NF

● Medium💼 Real project: Exam marks database
In marks(roll, subject, student_name, score, teacher, teacher_phone), student_name depends only on roll (2NF problem) and teacher_phone depends on teacher (3NF problem). We split into 4 tables and join them back.
ex07.sql
REAL RUN
✍ Try it yourself Which table changes if Sanjay Lakra gets a new phone? How many rows?
teachers - exactly one row.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 8 of 10  •  Medium

Example 8: Coaching institute schema

● Medium💼 Real project: Coaching ERP (students, batches, fees, attendance)
A compact but complete design: batches belong to courses, students enroll in batches, fees and attendance hang off the enrollment. Workbench can draw this as an EER diagram.
ex08.sql
REAL RUN
✍ Try it yourself Add a teachers table and link each batch to a teacher.
teachers(teacher_id PK, ...); ALTER TABLE batches ADD teacher_id INT, ADD FOREIGN KEY ...
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 9 of 10  •  Hard

Example 9: Hospital OPD schema with sample queries

● Hard💼 Real project: Hospital management system (HMS)
Patients, doctors, departments, visits and prescriptions. The design lets us answer real questions: patients per department today, and each doctor's load.
ex09.sql
REAL RUN
✍ Try it yourself Add a prescriptions table (visit_id, medicine, dose) and list today's prescriptions.
FK visit_id REFERENCES visits; JOIN visits ... WHERE visit_date = ...
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Practice 10 of 10  •  Hard

Example 10: Online shop schema: design check queries

● Hard💼 Real project: Reviewing a database design before launch
Our bazaar sample database is already normalised. These queries document it: every foreign key and the tables it links - exactly what a reviewer checks before go-live.
ex10.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Run the same queries on the school database and draw its ER diagram on paper.
Change 'bazaar' to 'school' in both queries.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Check your understanding

Quick Quiz

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

Q1. Students take many courses and courses have many students. You need...
✔ M:N always needs a junction (link) table.
Q2. "Maths,Science" stored in one cell breaks...
✔ 1NF: one value per cell.
Q3. In 1:N, the foreign key goes on...
✔ Each student row points to its one section.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
M12Module summary

Recap: Database Design & Normalization

What you learned in M12

  • ✔Turn requirements into entities (tables), attributes (columns) and relationships (keys).
  • ✔Draw an ER diagram first - crow's foot shows "many".
  • ✔1:N = FK on the many side; 1:1 = UNIQUE FK; M:N = junction table.
  • ✔Bad design causes update, insert and delete anomalies.
  • ✔1NF one value per cell; 2NF whole key; 3NF nothing but the key.
  • ✔Denormalise only on purpose, for speed, and document it.
🏆

Module 12 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M13 Views & Indexes: save queries as views and make searches 100 times faster with indexes.
Complete MySQL Course  |  Part 3  |  Database Design & Normalization
1 / 1

✎ SQL Lab