PART 4 of 5  •  about 20 class hours

Programming & Performance

Views, indexes and EXPLAIN for speed; stored procedures, triggers and events; transactions and locking for safety.

13

Views & Indexes

10 examples  •  5 h
14

Query Performance & EXPLAIN

10 examples  •  5 h
15

Stored Procedures, Functions, Triggers & Events

10 examples  •  5 h
16

Transactions & Concurrency

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
M13

Views & Indexes

Views save complex queries under a simple name and hide private columns. Indexes are the "book index" of a table: they turn a search through lakhs of rows into a jump to the right page.

  • Views: saved queries
  • Updatable views and WITH CHECK OPTION
  • Views for security
  • What an index is (B-tree)
  • CREATE INDEX, UNIQUE index, SHOW INDEX
  • Composite indexes and the leftmost rule
  • FULLTEXT search
  • Functional and invisible indexes
YOU WILL BUILD:
Report-card viewProduct search with FULLTEXTSpeed test on 1,00,000 rows
🗂️
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M13Where is this used in real work?

Fast searches and simple reports

jharsewa.jharkhand.gov.in/track?mobile=98...
🔍 Track application by mobile
🐢
No index
reads all 50 lakh rows
2.8 s
⚡
Index on mobile
jumps to the right row
0.001 s
Illustration. Our real 1,00,000-row speed test is in Example 10.
⚡

Speed

Every login (by mobile/email), search box and report filter depends on the right index. Without it, websites slow down as data grows.
👁️

Simple reports

A view hides a 5-table JOIN behind one name. Report tools and juniors just SELECT * FROM v_report_card.
🔐

Security

Give a user access to a view that shows names and marks, but not mobiles or fees.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Concept

Views: a saved SELECT with a name

  • CREATE VIEW v_name AS SELECT ...; stores the query, not the data.
  • Use it like a table: SELECT * FROM v_name WHERE .... MySQL runs the saved query each time, so data is always current.
  • CREATE OR REPLACE VIEW changes it; DROP VIEW removes it.
  • Name views with a prefix like v_ so everyone knows they are views.
view.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Animated explainer

How an index finds a row: the B-tree

root: [ 40 | 70 ]
[ 10 | 20 | 30 ]
[ 50 | 60 ]
[ 80 | 90 ]
41 → row
48 → row
52 → row
55 → row
58 → row
63 → row
🐢 Without index
reads 1, 2, 3 ... 50,00,000 rows
⚡ With index
root → branch → leaf → row (3-4 reads)
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Concept

Creating and seeing indexes

  • CREATE INDEX idx_name ON table (column);
  • CREATE UNIQUE INDEX also blocks duplicates.
  • PRIMARY KEY, UNIQUE and FOREIGN KEY columns get an index automatically.
  • SHOW INDEX FROM table; lists them.
  • Index columns used in WHERE, JOIN ON and ORDER BY. Do not index everything: each index slows INSERT/UPDATE and uses disk.
index.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Concept

Composite indexes: the leftmost-prefix rule

An index on (city, marks) is sorted by city first, then by marks inside each city - like a phone book sorted by surname, then first name.

Query filterCan use (city, marks)?
WHERE city = 'Ranchi'✅ yes (leftmost column)
WHERE city = 'Ranchi' AND marks > 80✅ yes, both columns
WHERE marks > 80❌ no - skips the first column
WHERE city LIKE 'Ra%'✅ yes (prefix match)
WHERE city LIKE '%chi'❌ no - leading %
index (city, marks) - sorted
citymarksrow
Dhanbad64→ 4
Patna78→ 2
Ranchi72→ 8
Ranchi85→ 3
Ranchi90→ 12
Ranchi91→ 1
Order mattersPut the column used with = first and the range column (>, BETWEEN) last. One good composite index often beats three single-column ones.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Concept

More index types in MySQL 8 / 9

📝

FULLTEXT

Word search in text: MATCH(name, description) AGAINST ('silk saree'). Ranks by relevance. Like a mini Google for your table.
🧮

Functional index

Index an expression: CREATE INDEX i ON orders ((YEAR(order_date))). Note the double brackets. (8.0.13+)
🙈

Invisible index

ALTER TABLE t ALTER INDEX i INVISIBLE - the optimizer ignores it. Test removing an index safely, then drop or make it VISIBLE again.
⬇️

Descending index

(order_date DESC) stored newest first - great for "latest 10 orders" pages.
📦

Multi-valued index

Index every value inside a JSON array (tags, skills) - see M17.
📏

Prefix index

(email(10)) indexes only the first 10 characters of long text, saving space.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 1 of 10  •  Easy

Example 1: View: student report card

● Easy💼 Real project: Report card printing
The office staff do not know JOINs. A view gives them one simple "table" with name, course, score and grade.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Create a view v_fee_paid with each student's total fees paid.
CREATE VIEW v_fee_paid AS SELECT student_id, SUM(amount) total FROM fees GROUP BY student_id;
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 2 of 10  •  Easy

Example 2: View for a shop counter (hide costs)

● Easy💼 Real project: Point-of-sale screen
The counter staff need product name, price and stock - but not supplier data. A view shows only those columns, ready for the billing screen.
ex02.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Change the view to also show price with 5% GST using CREATE OR REPLACE VIEW.
CREATE OR REPLACE VIEW v_counter AS SELECT ..., ROUND(p.price*1.05,2) AS price_gst ...
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 3 of 10  •  Easy

Example 3: Create an index on mobile

● Easy💼 Real project: Login with mobile number
Every login runs WHERE mobile = ?. EXPLAIN (details in M14) shows the plan before and after the index: type ALL = full scan, type ref = index lookup.
ex03.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Add an index on email and check with EXPLAIN.
CREATE INDEX idx_email ON students (email);
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 4 of 10  •  Easy

Example 4: Show all indexes of a table

● Easy💼 Real project: Database health check
SHOW INDEX lists every index, its columns and their order (Seq_in_index). The composite PRIMARY KEY of order_items shows two rows.
ex04.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Which indexes did MySQL create automatically for the foreign keys?
Look for index names equal to the FK column (category_id, customer_id, product_id).
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 5 of 10  •  Easy

Example 5: Unique index on email

● Easy💼 Real project: Stopping duplicate sign-ups
A UNIQUE index is both a speed-up and a rule. Adding it fails if duplicates already exist - so clean data first.
⚠ The error in this example is on purpose.
ex05.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself NULL emails exist in the table. Why did the unique index still work?
UNIQUE allows many NULLs.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 6 of 10  •  Medium

Example 6: Composite index for city + marks

● Medium💼 Real project: Scholarship search screen
Searches filter by city and a minimum marks. One composite index serves both columns. The second EXPLAIN shows a query that cannot use it (marks only).
ex06.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Create the index the other way round (marks, city). Which query can use it now?
Then WHERE marks > 80 can use it; city alone cannot.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 7 of 10  •  Medium

Example 7: Updatable view with CHECK OPTION

● Medium💼 Real project: Branch-wise data entry
The Ranchi clerk works through a view of Ranchi students. WITH CHECK OPTION stops him from inserting or moving a student to another city through the view.
⚠ The error in this example is on purpose.
ex07.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Remove WITH CHECK OPTION. Can the Patna student be inserted now? Can the clerk see him afterwards?
Yes it inserts, but he disappears from the view - confusing. That is why CHECK OPTION exists.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 8 of 10  •  Medium

Example 8: FULLTEXT product search

● Medium💼 Real project: Search box on a shopping site
FULLTEXT finds words anywhere in the text and ranks the results by relevance. Better than LIKE '%silk%', which cannot use an index.
ex08.sql
REAL RUN
✍ Try it yourself Search for "dokra" in BOOLEAN MODE: AGAINST ('+dokra' IN BOOLEAN MODE).
Boolean mode lets you require (+) or exclude (-) words.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 9 of 10  •  Hard

Example 9: Functional index on YEAR(order_date)

● Hard💼 Real project: Yearly reports on a big order table
A filter like WHERE YEAR(order_date) = 2025 cannot use a normal index on order_date. A functional index on the expression can. Compare the plans.
ex09.sqlsetup.sql
REAL RUN
✍ Try it yourself Rewrite the filter without a function so a plain index on order_date works (sargable, M14).
WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01'
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Practice 10 of 10  •  Hard

Example 10: Speed test: 1,00,000 rows with and without an index

● Hard💼 Real project: Performance tuning a slow portal
The setup file makes 1,00,000 orders with a recursive CTE. We time the same mobile search before and after CREATE INDEX. Look at the "(x.xx sec)" lines and the plan: Table scan (100000 rows) before, index lookup (1 row) after. \G prints the plan vertically.
ex10.sqlsetup.sql
REAL RUN
✍ Try it yourself Run it on your PC. Times depend on your computer, but the difference stays huge. Try 10 lakh rows (change 100000 in the setup).
Set cte_max_recursion_depth higher than the row count first.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Check your understanding

Quick Quiz

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

Q1. A view stores...
✔ Data is read fresh every time you use the view.
Q2. Index (city, marks) helps which filter?
✔ Leftmost-prefix rule: city must be used.
Q3. Downside of too many indexes?
✔ Every index must be updated on each write.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M13Module summary

Recap: Views & Indexes

What you learned in M13

  • ✔A view is a saved SELECT used like a table - great for reports and security.
  • ✔WITH CHECK OPTION stops writes through a view that would leave the view.
  • ✔An index is a sorted B-tree: 3-4 steps instead of a full table scan.
  • ✔Index WHERE / JOIN / ORDER BY columns; PK, UNIQUE and FK are indexed automatically.
  • ✔Composite indexes follow the leftmost-prefix rule.
  • ✔FULLTEXT for word search; functional, invisible and descending indexes in MySQL 8/9.
🏆

Module 13 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M14 Query Performance & EXPLAIN: read query plans like a pro and fix slow queries step by step.
Complete MySQL Course  |  Part 4  |  Views & Indexes
M14

Query Performance & EXPLAIN

A query that takes 0.01 s with 100 rows can take 30 s with 1 crore. Learn how MySQL plans a query, read EXPLAIN like a doctor reads an X-ray, and fix slow queries with simple rules.

  • How MySQL runs a query
  • EXPLAIN: type, key, rows, Extra
  • Access types: ALL → const
  • EXPLAIN ANALYZE (real timings)
  • Covering indexes
  • Sargable conditions
  • ORDER BY + LIMIT with an index
  • Histograms, slow query log, keyset pagination
YOU WILL BUILD:
Before/after tuning reportFast "latest orders" pageKeyset pagination
🏎️
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M14Where is this used in real work?

Slow queries cost money and users

monitor.tprosys.in/slow-queries
QueryCalls/dayAvg timeFix
Login by mobile48,0001.9 sindex mobile
Orders this month2,1004.2 ssargable date
Latest 20 orders15,0000.8 sindex for ORDER BY
Example monitoring screen (illustration). Each slow query here is fixed in this module.
⏳

Users leave

If a page takes more than 3 seconds, many users close it. Most slow pages are caused by one slow query.
💸

Servers cost money

A missing index can make a server work 1000 times harder. Fixing it can save buying a bigger cloud server.
🩺

Interview + job skill

"How do you find and fix a slow query?" - EXPLAIN is the expected answer.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Animated explainer

What happens when you send a query

📝
Parser
grammar + names
➤
🧠
Optimizer
chooses the plan
➤
⚙️
Executor
runs the plan
➤
🗃️
InnoDB
pages, indexes, rows
explain.sql
EXPLAIN SELECT name FROM students WHERE mobile = '9835012345';
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Concept

Reading EXPLAIN

ColumnWhat it tells you
typehow rows are found (see the ladder →). ALL = full scan = usually bad on big tables
possible_keysindexes the optimizer could use
keythe index it actually chose (NULL = none)
rowsestimated rows to read - smaller is better
filtered% of those rows expected to pass WHERE
ExtraUsing index (great: covering), Using where, Using filesort / Using temporary (extra work)

Access type ladder (best to worst)

const / eq_ref1 row by PK
refindex =
rangeindex range
indexwhole index
ALLwhole table
Rule of thumbOn a big table, look for type ALL with a large rows number, and Using filesort. Those are your first suspects.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Concept

EXPLAIN on a join

  • One EXPLAIN row per table, in the order MySQL reads them.
  • eq_ref on the second table = for each row, exactly one match by primary key. Ideal for joins.
  • EXPLAIN FORMAT=TREE shows the plan as a tree; EXPLAIN ANALYZE adds real times (it runs the query!).
Do not EXPLAIN ANALYZE a DELETE on productionIt really runs the statement.
explain_join.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Concept

Sargable: write WHERE so indexes can work

❌ Index cannot be used✅ Index-friendly rewrite
WHERE YEAR(order_date) = 2025WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01'
WHERE LEFT(mobile, 2) = '98'WHERE mobile LIKE '98%'
WHERE name LIKE '%kumar'FULLTEXT index, or store a reversed column
WHERE amount * 1.18 > 1000WHERE amount > 1000 / 1.18
WHERE mobile = 9835012345 (number vs CHAR)WHERE mobile = '9835012345'
Sargable"Search ARGument ABLE": the column stands alone on one side of the comparison. If you wrap the column in a function or calculation, MySQL must compute it for every row - so it scans the whole table.
Type mismatch trapComparing a CHAR column with a number makes MySQL convert every row, and the index is ignored. Always quote text values.
Other habitsSELECT only needed columns (not *); add LIMIT to lists; avoid OR across different columns (use UNION or two indexes); keep statistics fresh with ANALYZE TABLE.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 1 of 10  •  Easy

Example 1: Your first EXPLAIN

● Easy💼 Real project: Checking a query before it goes live
Search by primary key gives type const - one row, the fastest possible. Search by city (no index) gives type ALL - every row is read.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself EXPLAIN a search by email. What type do you get?
ALL - email has no index in the school database.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 2 of 10  •  Easy

Example 2: Full scan vs index lookup on 1,00,000 rows

● Easy💼 Real project: Branch filter on an order list
Same query, before and after an index on city. Watch type change from ALL to ref, and rows drop from about 1,00,000 to the rows of one city.
ex02.sqlsetup.sql
REAL RUN
✍ Try it yourself EXPLAIN said rows = 31130, but the real count is 16,666. Why?
EXPLAIN shows an ESTIMATE from sampled statistics, not an exact count.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 3 of 10  •  Easy

Example 3: EXPLAIN ANALYZE: real timings

● Easy💼 Real project: Proving a fix with numbers
EXPLAIN ANALYZE runs the query and shows actual time and actual rows for every step. Times change on each run and each PC - compare them, do not memorise them.
ex03.sqlsetup.sql
REAL RUN
✍ Try it yourself Add an index on order_date and run it again. Which step disappears?
The "Table scan" becomes an "Index range scan".
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 4 of 10  •  Easy

Example 4: Covering index: "Using index"

● Easy💼 Real project: Fast count and list screens
If the index contains every column the query needs, MySQL never touches the table rows. EXPLAIN shows Using index.
ex04.sqlsetup.sql
REAL RUN
✍ Try it yourself Why is the second query not covered?
order_date is not in the index, so rows must be read.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 5 of 10  •  Easy

Example 5: A leading % breaks the index

● Easy💼 Real project: Search box design
LIKE '98007%' can use the index (range scan). LIKE '%91900' cannot - it must look at every value.
ex05.sqlsetup.sql
REAL RUN
✍ Try it yourself Which one would you use for "search by last 4 digits"? How could you make it fast?
Store a column last4 = RIGHT(mobile,4) with its own index (or a functional index).
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 6 of 10  •  Medium

Example 6: Rewrite a non-sargable date filter

● Medium💼 Real project: Monthly report on a big order table
The report used MONTH() and YEAR() on the column. Rewriting it as a date range lets the index on order_date work. Same answer, far fewer rows read.
ex06.sqlsetup.sql
REAL RUN
✍ Try it yourself Rewrite WHERE DATE_FORMAT(order_date, '%Y') = '2024' the sargable way.
order_date >= '2024-01-01' AND order_date < '2025-01-01'
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 7 of 10  •  Medium

Example 7: Index for ORDER BY + LIMIT

● Medium💼 Real project: "Latest 5 orders" on a dashboard
Without an index MySQL sorts all 1,00,000 rows (Using filesort) to return 5. With an index on order_date it reads the last 5 entries of the index and stops.
ex07.sqlsetup.sql
REAL RUN
✍ Try it yourself Would the index help ORDER BY amount DESC LIMIT 5?
No - it is on order_date. You need an index on amount.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 8 of 10  •  Medium

Example 8: Histogram for a skewed column

● Medium💼 Real project: Helping the optimizer choose well
For columns without an index, MySQL guesses how many rows match. A histogram stores the real value distribution so the guesses (filtered %) become accurate.
ex08.sqlsetup.sql
REAL RUN
✍ Try it yourself Drop the histogram and compare the "filtered" value.
ANALYZE TABLE big_orders DROP HISTOGRAM ON city;
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 9 of 10  •  Hard

Example 9: Tune a slow report step by step

● Hard💼 Real project: Performance ticket from the operations team
The ticket: "City-wise sales for March is slow." Step 1 measure, step 2 find the scan, step 3 add a composite index (date, city, amount), step 4 measure again. The plan changes from a table scan to a covering index range scan.
ex09.sqlsetup.sql
REAL RUN
✍ Try it yourself Write a one-line "ticket closed" note: what was slow, what you changed, before/after time.
Example: "Table scan of 1 lakh rows replaced by covering index range scan; time reduced from X ms to Y ms."
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Practice 10 of 10  •  Hard

Example 10: Pagination: OFFSET vs keyset

● Hard💼 Real project: Infinite scroll on a mobile app
OFFSET 90000 still reads and throws away 90,000 rows. Keyset pagination remembers the last id seen and asks for ids after it - an index range scan that stays fast on every page.
ex10.sqlsetup.sql
REAL RUN
✍ Try it yourself What is the drawback of keyset pagination? (Think about "jump to page 57".)
You can only go next/previous easily, not jump to any page number.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Check your understanding

Quick Quiz

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

Q1. EXPLAIN type ALL on a 50-lakh-row table means...
✔ Every row is read - look for a missing index.
Q2. Which WHERE can use an index on order_date?
✔ The column must stand alone (sargable).
Q3. Extra = "Using index" means...
✔ No table rows were read at all.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M14Module summary

Recap: Query Performance & EXPLAIN

What you learned in M14

  • ✔Parser → optimizer (chooses a plan) → executor → InnoDB.
  • ✔EXPLAIN shows the plan: watch type, key, rows and Extra.
  • ✔EXPLAIN ANALYZE runs the query and shows real step times.
  • ✔Write sargable conditions: no functions on indexed columns.
  • ✔Covering and ORDER BY indexes remove table reads and sorting.
  • ✔Histograms help estimates; keyset pagination beats big OFFSETs.
🏆

Module 14 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M15 Stored Procedures, Functions, Triggers & Events: put business rules inside the database and automate jobs.
Complete MySQL Course  |  Part 4  |  Query Performance & EXPLAIN
M15

Stored Procedures, Functions, Triggers & Events

Some rules must run on the server every time, no matter which app sends the data. Stored programs keep that logic inside MySQL: procedures for tasks, functions for calculations, triggers for automatic actions and events for scheduled jobs.

  • Why store logic in the database
  • DELIMITER and CREATE PROCEDURE
  • IN, OUT and INOUT parameters
  • Variables, IF, CASE, WHILE, LOOP
  • Stored functions
  • Triggers BEFORE / AFTER
  • SIGNAL: your own error messages
  • Cursors, handlers and the event scheduler
YOU WILL BUILD:
GST functionPrice-change audit logNightly overdue-books job
⚙️
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M15Where is this used in real work?

Business rules that run on the server

📦
Procedure
A named task with steps
CALL pay_fee(7, 4500);
🧮
Function
Returns one value
SELECT gst(450);
⚡
Trigger
Runs automatically on INSERT/UPDATE/DELETE
AFTER UPDATE ON products
⏰
Event
Runs on a schedule
EVERY 1 DAY STARTS ...
🛑
SIGNAL
Stops bad data with your own message
SIGNAL SQLSTATE '45000'
🔄
Cursor
Walks through rows one by one
FETCH cur INTO ...
🏦

Banks and billing

Money transfer, interest posting and invoice numbering are often procedures - every app calls the same tested code.
🔎

Audit trails

Triggers record who changed a price or a mark and when - required in government and finance systems.
⚠️

Use with care

Too much logic in the database is hard to test and version. Keep it for rules that must never be skipped.
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Concept

Your first stored procedure

  • The body has many ; inside, so we change the statement end to // with DELIMITER //, and back with DELIMITER ; afterwards.
  • CREATE PROCEDURE name(IN p TYPE) ... BEGIN ... END.
  • Run it with CALL name(value);
  • In Workbench you can skip DELIMITER when you use the "Create Stored Procedure" screen.
IN, OUT, INOUTIN = value goes in (default). OUT = procedure fills it for you (read it from a @variable). INOUT = both.
proc.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Concept

Variables and control flow

ItemSyntax
Local variableDECLARE total DECIMAL(10,2) DEFAULT 0;
Set a valueSET total = total + 100; or SELECT SUM(x) INTO total FROM ...
User variable@name - lives for your session, no DECLARE
DecisionIF ... THEN ... ELSEIF ... ELSE ... END IF;
LoopWHILE cond DO ... END WHILE; / LOOP ... LEAVE label; END LOOP;
📜 SQL standard vs MySQL
SQL:2023 standardSQL/PSM (Persistent Stored Modules) defines procedures and functions
MySQL 9.7Follows SQL/PSM closely. (MySQL Enterprise 9.x also allows JavaScript stored programs.)
vars.sqlschool_setup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Animated explainer

How a trigger fires

products
product_idprice
3220.00
price_log
product_idold_pricenew_pricechanged_bychanged_at
3220.00240.00clerk@localhost2026-11-25 ...
clerk.sql
UPDATE products
SET price = 240
WHERE product_id = 3;
OLD.price = 220
NEW.price = 240
trigger.sql
CREATE TRIGGER trg_price_audit
AFTER UPDATE ON products FOR EACH ROW
INSERT INTO price_log VALUES
(NEW.product_id, OLD.price, NEW.price,
 USER(), NOW());
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Concept

SIGNAL: stop with your own error

  • SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '...'; raises an error like MySQL's own errors. The statement is cancelled.
  • SQLSTATE 45000 means "user-defined error".
  • Use it in BEFORE triggers and procedures for business rules that CHECK cannot express (rules that look at other tables).
signal.sqlbazaar_setup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Concept

Functions vs procedures, and when not to use stored code

Stored FUNCTIONStored PROCEDURE
Returnsexactly one value (RETURN)zero or more result sets, OUT params
Used inSELECT gst(price), WHERE, viewsCALL name(...)
Can change data?should not (side-effect free)yes: INSERT, UPDATE, transactions
KeywordsDETERMINISTIC / READS SQL DATA-
Binary logging ruleWhen binary logging is on (default in MySQL 8+/9), a function must be declared DETERMINISTIC, NO SQL or READS SQL DATA - otherwise ERROR 1418.
✅

Good uses

Rules every app must follow (no negative stock), audit logs, nightly clean-up jobs, complex multi-step updates done in one round trip.
⚠️

Think twice

Heavy business logic that changes often is easier to test and version in application code (Python, PHP, Node.js). Triggers are invisible - document them!
🔍

See what exists

SHOW PROCEDURE STATUS WHERE Db = 'school';
SHOW TRIGGERS;   SHOW EVENTS;
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 1 of 10  •  Easy

Example 1: Procedure: list students of a section

● Easy💼 Real project: Teacher's class list button
The app calls one procedure instead of sending SQL text. If the query changes later, only the procedure changes - not every app.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Call it for 10-C. Then create topper_of(IN p_section) that returns only the highest scorer.
ORDER BY marks DESC LIMIT 1 inside the new procedure.
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 2 of 10  •  Easy

Example 2: Procedure with OUT: total fees

● Easy💼 Real project: Fee counter "total collected" box
OUT parameters hand values back. The caller passes user variables (@total) and reads them after CALL.
ex02.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Call it for May 2024.
CALL fee_summary('2024-05-01','2024-05-31', @t, @c); SELECT @t, @c;
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 3 of 10  •  Easy

Example 3: Function: GST amount

● Easy💼 Real project: Billing software helper
A stored function returns one value and can be used inside any SELECT, like a built-in function. DETERMINISTIC = same input always gives the same output.
ex03.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Write with_gst(amount, rate) that returns the amount plus GST.
RETURN ROUND(p_amount * (1 + p_rate/100), 2);
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 4 of 10  •  Easy

Example 4: Function: grade from marks

● Easy💼 Real project: Report card generator
The grading rule lives in one place. Change the function, and every report and view that uses it changes too.
ex04.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Use the function on enrollments.score (which has NULLs).
SELECT score, grade_of(score) FROM enrollments;
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 5 of 10  •  Easy

Example 5: Trigger: fill a value automatically

● Easy💼 Real project: Auto-generated receipt codes
A BEFORE INSERT trigger can set NEW values. Here every new fee gets a receipt code like RCP-2026-00017 - nobody can forget it.
ex05.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Make the trigger also refuse amounts below Rs 100 using SIGNAL.
IF NEW.amount < 100 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = '...'; END IF;
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 6 of 10  •  Medium

Example 6: Trigger: audit log of price changes

● Medium💼 Real project: Audit trail for GST / price control
Every price change is recorded with old and new value, the user and the time. Even a direct UPDATE from Workbench is logged.
ex06.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Add an AFTER DELETE trigger that logs deleted products.
Use OLD.* values; NEW does not exist in a DELETE trigger.
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 7 of 10  •  Medium

Example 7: SIGNAL: block an order with no stock

● Medium💼 Real project: Stock control in a shop
A BEFORE INSERT trigger on order_items checks the product's stock in another table - something a CHECK constraint cannot do - and reduces stock when the order is fine.
⚠ The error in this example is on purpose.
ex07.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Show the error message text the app would display.
The client prints: ERROR 1644 (45000): Not enough stock for this item
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 8 of 10  •  Medium

Example 8: Cursor: build a report row by row

● Medium💼 Real project: Generating SMS text for each defaulter
A cursor walks through a SELECT one row at a time. A handler sets a flag when there are no more rows. (Use cursors only when set-based SQL cannot do the job.)
ex08.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Rewrite the whole procedure as ONE INSERT ... SELECT statement. Which is simpler?
INSERT INTO sms_queue SELECT mobile, CONCAT('Dear ', name, ...) FROM students s WHERE NOT EXISTS (...);
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 9 of 10  •  Hard

Example 9: Fee payment procedure with validation

● Hard💼 Real project: School ERP fee counter
A complete business procedure: checks the student exists, checks the amount, inserts the payment inside a transaction, and returns the receipt id. Errors come back as clear messages. (Transactions: M16.)
⚠ The error in this example is on purpose.
ex09.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Add a rule: mode must be UPI, Cash or Card.
IF p_mode NOT IN ('UPI','Cash','Card') THEN SIGNAL ... END IF;
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Practice 10 of 10  •  Hard

Example 10: Nightly event: mark overdue books

● Hard💼 Real project: Library automation (scheduled job)
The event scheduler runs SQL on a timetable, like an alarm clock inside MySQL. For the demo the event runs every 1 second; in real life it would be EVERY 1 DAY STARTS '2026-11-26 02:00:00'.
ex10.sql
REAL RUN
✍ Try it yourself Change the event to run daily at 2 AM and disable it with ALTER EVENT ... DISABLE.
ALTER EVENT ev_mark_overdue ON SCHEDULE EVERY 1 DAY STARTS '2026-11-26 02:00:00'; ALTER EVENT ev_mark_overdue DISABLE;
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Check your understanding

Quick Quiz

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

Q1. Why change the DELIMITER before CREATE PROCEDURE?
✔ Otherwise the client sends the body in pieces.
Q2. Inside an UPDATE trigger, the value before the change is...
✔ OLD = before, NEW = after.
Q3. SIGNAL SQLSTATE '45000' is used to...
✔ It cancels the statement with your message.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M15Module summary

Recap: Stored Procedures, Functions, Triggers & Events

What you learned in M15

  • ✔Stored programs keep rules inside MySQL, so every app follows them.
  • ✔Procedures (CALL) do tasks; IN / OUT / INOUT parameters pass values.
  • ✔Functions return one value and work inside SELECT.
  • ✔Triggers run automatically BEFORE/AFTER INSERT, UPDATE, DELETE using OLD and NEW.
  • ✔SIGNAL SQLSTATE '45000' stops bad data with your own message.
  • ✔Cursors walk rows one by one; events run SQL on a schedule.
🏆

Module 15 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M16 Transactions & Concurrency: all-or-nothing changes, and what happens when two people book the last seat.
Complete MySQL Course  |  Part 4  |  Stored Procedures, Functions, Triggers & Events
M16

Transactions & Concurrency

Money must never disappear halfway through a transfer, and two people must never get the same train seat. Transactions make groups of changes all-or-nothing, and locks keep many users from stepping on each other.

  • ACID in simple words
  • START TRANSACTION, COMMIT, ROLLBACK
  • Autocommit
  • SAVEPOINT
  • Two users at the same time
  • Isolation levels and read problems
  • SELECT ... FOR UPDATE, NOWAIT, SKIP LOCKED
  • Deadlocks and InnoDB MVCC
YOU WILL BUILD:
UPI-style transferLast-seat booking with locksJob queue with SKIP LOCKED
🔐
about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete MySQL Course  |  BrainBit Infotech, Ranchi
M16Where is this used in real work?

All-or-nothing, even with lakhs of users

pay.example-upi.in/transfer
💸
Ravi → Sunita: ₹1,000
1. debit Ravi −1000➤2. credit Sunita +1000
Power cut between step 1 and 2? Without a transaction Ravi loses ₹1,000 and Sunita gets nothing.
With a transactionBoth steps succeed together, or MySQL undoes step 1 automatically.
🏦

Banks and wallets

Every transfer, EMI deduction and refund is a transaction. Money is never created or lost by a crash.
🚆

Booking systems

IRCTC, bus and cinema apps lock a seat while you pay so two people cannot book it.
📦

Stock and orders

Order + stock reduction + payment record must all happen, or none.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Animated explainer

ACID: the four promises of a transaction

A
Atomicity
all or nothing
C
Consistency
rules always hold
I
Isolation
no half-finished views
D
Durability
committed = saved
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Concept

START TRANSACTION, COMMIT and ROLLBACK

  • START TRANSACTION; (or BEGIN;) opens a transaction.
  • Changes are visible to you at once, but other sessions see them only after COMMIT;
  • ROLLBACK; undoes everything since START TRANSACTION.
  • DDL (CREATE, ALTER, DROP, TRUNCATE) causes an implicit commit - it cannot be rolled back.
AutocommitBy default MySQL runs each statement in its own tiny transaction and commits it at once (autocommit = 1). START TRANSACTION switches that off until COMMIT/ROLLBACK.
txn.sqlsetup.sql
REAL RUN
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Animated explainer

Two people, one last seat: why we need locks

❌ Without locks
A: SELECT ... seat free ✔
B: SELECT ... seat free ✔
A: UPDATE ... 'Priya'; COMMIT
B: UPDATE ... 'Aman'; COMMIT ⚠
✅ With FOR UPDATE
A: SELECT ... FOR UPDATE 🔒
B: SELECT ... FOR UPDATE ⏳ waiting
A: UPDATE 'Priya'; COMMIT 🔓
B: sees 'Priya' - seat taken
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Concept

Isolation levels: how much can I see of others' work?

LevelDirty readNon-repeatable readPhantom read
READ UNCOMMITTED⚠ possible⚠ possible⚠ possible
READ COMMITTED✅ no⚠ possible⚠ possible
REPEATABLE READ (MySQL default)✅ no✅ no✅ no*
SERIALIZABLE✅ no✅ no✅ no

* InnoDB's consistent snapshots and next-key locks prevent phantoms for plain reads in REPEATABLE READ.

📜 SQL standard vs MySQL
SQL:2023 standardDefault isolation level is SERIALIZABLE
MySQL 9.7Default is REPEATABLE READ (PostgreSQL / SQL Server default to READ COMMITTED)
👁️

Dirty read

Seeing another user's change before they COMMIT - which may still be rolled back.
🔄

Non-repeatable read

You read a balance twice in one transaction and get two different values.
👻

Phantom read

You count rows twice and a new row "appears" in between.
📸

MVCC

InnoDB keeps old versions of rows (undo log), so readers see a snapshot and do not block writers.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 1 of 10  •  Easy

Example 1: Commit a fee payment

● Easy💼 Real project: Fee counter: receipt + ledger together
A fee payment writes the receipt and updates the student ledger. Both happen inside one transaction and are saved together by COMMIT.
ex01.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Repeat with a second payment of Rs 1,000 for student 10. What is total_paid now?
Rs 4,500 - the ledger adds the new amount.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 2 of 10  •  Easy

Example 2: Rollback a mistake

● Easy💼 Real project: Undo before it is too late
The clerk deletes the wrong rows. Because he was inside a transaction, ROLLBACK brings them back. After COMMIT this would be impossible.
ex02.sqlschool_setup.sql
REAL RUN
✍ Try it yourself Try the same with TRUNCATE TABLE inside the transaction. Can you roll it back?
No - TRUNCATE causes an implicit commit.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 3 of 10  •  Easy

Example 3: Autocommit on and off

● Easy💼 Real project: Understanding why changes "save themselves"
With autocommit = 0 every change waits for COMMIT, even without START TRANSACTION. Forgetting COMMIT then loses work when you disconnect!
ex03.sqlsetup.sql
REAL RUN
✍ Try it yourself Which setting does Workbench use? (Look for the auto-commit toggle icon in the SQL editor toolbar.)
Workbench has autocommit ON by default; the toggle switches it.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 4 of 10  •  Easy

Example 4: SAVEPOINT in a multi-step order

● Easy💼 Real project: Shopping cart checkout
A SAVEPOINT is a bookmark inside a transaction. ROLLBACK TO SAVEPOINT undoes only the steps after it - here the gift wrap fails but the order stays.
⚠ The error in this example is on purpose.
ex04.sqlbazaar_setup.sql
REAL RUN
✍ Try it yourself Add a second SAVEPOINT before a stock update and roll back only that step.
SAVEPOINT stock_step; UPDATE ...; ROLLBACK TO SAVEPOINT stock_step;
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 5 of 10  •  Easy

Example 5: Undo all steps when one fails

● Easy💼 Real project: Data import that must be complete
Three branch records are imported. The third breaks a rule, so the app sends ROLLBACK and none are saved - no half imports.
⚠ The error in this example is on purpose.
ex05.sqlsetup.sql
REAL RUN
✍ Try it yourself What would happen with COMMIT instead of ROLLBACK?
The first two rows would be saved, the third not - a half import.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 6 of 10  •  Medium

Example 6: UPI-style money transfer

● Medium💼 Real project: Wallet / bank transfer
Debit and credit inside one transaction. The second transfer would make Sunita's balance negative: the CHECK fails, the app rolls back and Ravi is not debited.
⚠ The error in this example is on purpose.
ex06.sqlsetup.sql
REAL RUN
✍ Try it yourself Write it as a stored procedure transfer(from, to, amount) with an exit handler that rolls back on error (combine M15 + M16).
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END;
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 7 of 10  •  Medium

Example 7: Two sessions: the last train seat

● Medium💼 Real project: Railway / bus seat booking
Two real MySQL sessions. A locks the seat with FOR UPDATE; B must wait. When A commits, B is released and sees Priya's name, so the app shows "seat not available". Look at B's waiting time.
two_sessions.sqlsetup.sql
REAL RUN
✍ Try it yourself Open two Workbench tabs (two connections) and try it yourself with your friend.
Each SQL tab in Workbench is a separate session.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 8 of 10  •  Medium

Example 8: Job queue with SKIP LOCKED

● Medium💼 Real project: Two SMS workers sharing one queue
Two worker programs take jobs from the same table. SKIP LOCKED makes worker B skip the rows A has locked and take the next free ones - no waiting, no double SMS. NOWAIT fails at once instead of waiting.
⚠ The error in this example is on purpose.
workers.sqlsetup.sql
REAL RUN
✍ Try it yourself What would worker B get without SKIP LOCKED?
It would wait for A to commit, then get the same jobs 1 and 2.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 9 of 10  •  Hard

Example 9: Deadlock on purpose and how to avoid it

● Hard💼 Real project: Concurrent transfers in a payment system
A locks account 101 then wants 102; B locks 102 then wants 101. Each waits for the other forever - a deadlock. InnoDB detects it in milliseconds and rolls back one transaction (ERROR 1213). Fix: always lock accounts in the same order (smaller acc_no first) and let the app retry.
⚠ The error in this example is on purpose.
deadlock.sqlsetup.sql
REAL RUN
✍ Try it yourself Rewrite B so it updates 101 first, then 102. Can a deadlock still happen?
No - both lock 101 first, so the second one simply waits.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Practice 10 of 10  •  Hard

Example 10: Isolation levels side by side

● Hard💼 Real project: Choosing settings for a reporting server
Part 1: with READ UNCOMMITTED, B sees A's uncommitted 999999 - a dirty read of money that never existed. Part 2: with REPEATABLE READ (default), B reads the same balance twice inside its transaction even though A changed it (autocommit) in between.
isolation.sqlsetup.sql
REAL RUN
✍ Try it yourself Repeat part 2 with READ COMMITTED for B. What does the second read show?
5001 - READ COMMITTED sees other sessions' commits immediately (non-repeatable read).
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Check your understanding

Quick Quiz

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

Q1. ROLLBACK undoes...
✔ All changes of the open transaction are undone.
Q2. MySQL's default isolation level is...
✔ InnoDB default: REPEATABLE READ.
Q3. Two workers must take different jobs without waiting. Use...
✔ Locked rows are skipped, not waited for.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
M16Module summary

Recap: Transactions & Concurrency

What you learned in M16

  • ✔A transaction is all-or-nothing: START TRANSACTION ... COMMIT / ROLLBACK.
  • ✔ACID: Atomicity, Consistency, Isolation, Durability.
  • ✔Autocommit saves each statement at once; DDL commits implicitly.
  • ✔SAVEPOINT lets you undo part of a transaction.
  • ✔SELECT ... FOR UPDATE locks rows; NOWAIT / SKIP LOCKED avoid waiting.
  • ✔Deadlocks: InnoDB rolls one back (1213) - lock in a fixed order and retry.
🏆

Module 16 complete!

You practised 10 real examples on a real MySQL server.

👉 Coming next

M17 JSON & Modern SQL Features: store flexible data as JSON, query it with ->>, and turn JSON into rows with JSON_TABLE.
Complete MySQL Course  |  Part 4  |  Transactions & Concurrency
1 / 1

✎ SQL Lab