Schema and setup (MeowTube / miaowtube)
Create the database and switch to it:users and videos — with a foreign key relationship:
videos with one million rows (MySQL 8+): we use a recursive CTE to generate sequential values. Note you may need privileges to change session variables.
The real question: How many videos did Fluffy upload in July?
We joinvideos with users, filter for username = 'fluffy' and the July 2024 range, then count rows:
EXPLAIN output (before adding helpful indexes)
Run EXPLAIN for the same query:users (u)scanned without an index (key: NULL) — acceptable for 2 rows, but not for many users.videos (v)used the foreign key index onuser_id, but MySQL still applied theupload_datefilter row-by-row (“Using where”), meaning it accessed all of Fluffy’s videos and then filtered by date.
Fix: add the right indexes
Add an index onusers.username and a composite index on videos(user_id, upload_date). The composite index allows MySQL to find Fluffy’s July uploads in a single indexed operation, avoiding per-row date checks.
EXPLAIN output (after indexing)
Run EXPLAIN again for the same query:usersnow usesidx_usernameto find Fluffy immediately.videosuses the compositeidx_user_dateso MySQL can applyuser_id+upload_datevia the index without scanning all rows.
Indexes are the single most effective way to speed up lookups and joins in OLTP workloads. Build them thoughtfully: too many indexes slow writes, and composite indexes are valuable when you filter on several columns together.
Index best-practices quick reference
Indexes speed reads but add overhead to writes (INSERT/UPDATE/DELETE). Monitor index usage (e.g., with EXPLAIN and perf tools) and avoid creating unused indexes.
Additional query-performance habits (no index required)
- Select only needed columns — avoid
SELECT *when you only need a few fields. - Limit results when appropriate:
LIMIT 10for previews. - Apply filters early with WHERE so the engine processes less data.
- Break complex logic into simpler queries when that reduces scanned rows.

Quick challenge
Cody wants to show the most recent videos first, include only those uploaded after 1st of June, and display the top 3 results. Which query is correct? A:WHERE clause must come before ORDER BY. The correct structure is:
Recap
- SQL queries follow a specific clause order; write them accordingly to avoid syntax errors and to ensure correct results.
- Indexes are like bookmarks: with the right indexes (especially composite indexes when filtering on multiple columns), the database can jump directly to matching rows and avoid full scans.
- Even without indexes, you can improve performance by selecting only required fields, limiting results, simplifying queries, and applying filters early.
