Advanced MySQL
Follows on from SQL basics: subqueries and WITH, transactions and locks, foreign keys, analyzing slow queries, UNION and views, window functions, character sets and collations and database backups. All examples are verified in MySQL and MariaDB.
A subquery is a SELECT inside another query. It comes in handy when a condition depends on other data – products more expensive than the average, customers without an order, the most expensive item in each category. How to write subqueries, why NOT IN can return an empty result and how to make a long query clearer with WITH.
Two customers buy the last item in stock in the same second. Who gets it and how do you make sure it is not sold twice? Transactions, row locks, isolation levels, deadlocks and a safe order from PHP.
An order of a customer who does not exist, or a customer deleted together with their order history. A foreign key prevents such errors directly in the database, whichever script changes the data. How to add it to an existing table, what the ON DELETE options do and what to watch out for when importing.
A website that was fast with a few hundred records starts to crawl after years of use. How to find slow queries, how to read the output of EXPLAIN including the Extra column and how to speed up a query with a suitable index – on a table with ten thousand rows.
UNION puts the results of several queries one below the other, a view (VIEW) stores a complex query under a name so that it can be used like a table. When to use UNION and when UNION ALL, how to get an intersection and a difference and why a view stops working after the database is moved.
Window functions calculate from several rows like GROUP BY, but they keep the rows in the result. A running total of sales, a ranking within a category, the three best-selling products in each group or the change from the previous month – each of these tasks is a single query.
Garbled characters instead of accented letters, question marks instead of emoji or the error “Illegal mix of collations” when joining two tables. All of these have the same origin: character sets and collations. Where they are set, how to fix text that is already damaged and how to convert an old database to utf8mb4.
A backup that nobody has tried to restore is only a hope. How to back up a database with mysqldump (in MariaDB mariadb-dump) with the right options, how to restore it, how to run the backup automatically every night and how to check that it is complete.