Everything so far works on a few rows. This chapter is what separates a query that returns in milliseconds from one that crawls on a million rows: indexes and how to read the query plan — plus the built-in functions and transactions you'll reach for constantly.
Indexes
Without an index, finding matching rows means scanning the whole table. An index is a sorted lookup structure (like a book's index) that lets the database jump straight to matching rows:
-- Index the columns you filter or join onCREATE INDEX idx_students_email ON students(email);CREATE INDEX idx_students_programme ON students(programme_id);-- A composite index helps queries filtering on both, in orderCREATE INDEX idx_prog_pkg ON students(programme_id, package);
EXPLAIN — read the plan
Prefix any query with EXPLAIN to see how MySQL will run it. The word to hunt for is a full-table scan when you expected an index to be used:
EXPLAIN SELECT * FROM students WHERE email = 'aanya@example.com';-- Look at the 'type' and 'key' columns:-- type = 'ref' or 'const', key = idx_students_email → good (used the index)-- type = 'ALL', key = NULL → full scan (add an index)
Built-in functions
| Category | Examples |
|---|---|
| Strings | CONCAT, UPPER, LENGTH, SUBSTRING, TRIM |
| Numbers | ROUND, CEIL, FLOOR, ABS, MOD |
| Dates | NOW, CURDATE, DATE_ADD, DATEDIFF, YEAR |
| Aggregate | COUNT, SUM, AVG, MIN, MAX |
| Logic | IF, IFNULL, COALESCE, CASE |
SELECTCONCAT(name, ' (', YEAR(enrolled), ')') AS label,ROUND(package, 1) AS pkg,IFNULL(email, 'no email') AS contact,DATEDIFF(CURDATE(), enrolled) AS days_sinceFROM students;
Transactions
When several statements must all succeed or all fail together (a money transfer, an enrolment + payment), wrap them in a transaction. COMMIT makes them permanent; ROLLBACK undoes them all:
START TRANSACTION;UPDATE accounts SET balance = balance - 5000 WHERE id = 1;UPDATE accounts SET balance = balance + 5000 WHERE id = 2;COMMIT; -- both applied; or ROLLBACK to undo both
Practice
Add indexes to the columns you join and filter on, then run EXPLAIN on a query before and after to see the plan change. Write a query using CONCAT, ROUND and DATEDIFF, and wrap two related updates in a transaction.
Key takeaways
- 01Indexes turn full-table scans into fast lookups — index the columns you filter, join and sort on.
- 02Indexes cost space and slow writes, so index deliberately, not everything.
- 03EXPLAIN shows the query plan; type=ALL / key=NULL means a full scan — add an index.
- 04Built-in string/number/date/aggregate functions do transformation in the database.
- 05Wrap must-succeed-together statements in a transaction: COMMIT to keep, ROLLBACK to undo.
