It is absolutely horrifying in parts, no question. But the writing is exquisite a rarity these days , which is why I loved it. I was also so moved, in a good way, by the ending that I cried, something I seldom do when reading. The picture he painted with the writing was incredibly vivid which made it even more depressing for me. I also cried at the end of the book. All Rights Reserved. How does the never to be differ from what never was? Parents Forum Parent Cafe.
Please enter a valid email address. Thanks for subscribing! In many database servers, IN is just a synonym for multiple OR clauses, because the two are logically equivalent.
Not so in MySQL, which sorts the values in the IN list and uses a fast binary search to see whether a value is in the list.
This is O log n in the size of the list, whereas an equivalent series of OR clauses is O n in the size of the list i.
You may end up just defeating it, or making your queries more complicated and harder to maintain for zero benefit. In general, you should let the optimizer do its work. Some of the options are to add a hint to the query, rewrite the query, redesign your schema, or add indexes. The engines may provide the optimizer with statistics such as the number of pages per table or index, the cardinality of tables and indexes, the length of rows and keys, and key distribution information.
The optimizer can use this information to help it decide on the best execution plan. In sum, it considers every query a join—not just every query that matches rows from two tables, but every query, period including subqueries, and even a SELECT against a single table. Each of the individual queries is a join, in MySQL terminology—and so is the act of reading from the resulting temporary table.
This means MySQL runs a loop to find a row from a table, then runs a nested loop to find a matching row in the next table. It continues until it has found a matching row in each table in the join. It tries to build the next row by looking for more matching rows in the last table. It keeps backtracking until it finds another row in some table, at which point, it looks for a matching row in the next table, and so on.
This query execution plan applies as easily to a single-table query as it does to a many-table query, which is why even a single-table query can be considered a join—the single-table join is the basic operation from which more complex joins are composed.
Read it from left to right and top to bottom. Figure Swim-lane diagram illustrating retrieving rows using a join. MySQL executes every kind of query in essentially the same way. In short, MySQL coerces every kind of query into this execution plan. Still other queries can be executed with nested loops, but perform very badly as a result. We look at some of those later. Instead, the query execution plan is actually a tree of instructions that the query execution engine follows to produce the query results.
The final plan contains enough information to reconstruct the original query. Any multitable query can conceptually be represented as a tree. For example, it might be possible to execute a four-table join as shown in Figure This is what computer scientists call a balanced tree.
This is not how MySQL executes the query, though. As we described in the previous section, MySQL always begins with one table and finds matching rows in the next table.
The most important part of the MySQL query optimizer is the join optimizer , which decides the best order of execution for multitable queries. It is often possible to join the tables in several different orders and get the same results. The join optimizer estimates the cost for various plans and tries to choose the least expensive one that gives the same result. You can probably think of a few different query plans.
This should be efficient, right? This is quite a different plan from the one suggested in the previous paragraph. Is this really more efficient? This shows why MySQL wants to reverse the join order: doing so will enable it to examine fewer rows in the first table.
The difference is how many of these indexed lookups it will have to do:. If the server scans the actor table first, it will have to do only index lookups into later tables. In other words, the reversed join order will require less backtracking and rereading.
The reordered query had an estimated cost of , while the estimated cost of forcing the join order was 1, Reordering joins is usually a very effective optimization. In most cases, the join optimizer will outperform a human. The join optimizer tries to produce a query execution plan tree with the lowest achievable cost.
When possible, it examines all potential combinations of subtrees, beginning with all one-table plans. Unfortunately, a join over n tables will have n -factorial combinations of join orders to examine. This is called the search space of all possible query plans, and it grows very quickly—a table join can be executed up to 3,, different ways! When the search space grows too large, it can take far too long to optimize the query, so the server stops doing a full analysis. MySQL has many heuristics, accumulated through years of research and experimentation, that it uses to speed up the optimization stage.
This is because the results for one table depend on data retrieved from another table. These dependencies help the join optimizer reduce the search space by eliminating choices. Sorting results can be a costly operation, so you can often improve performance by avoiding sorts or by performing them on fewer rows.
We showed you how to use indexes for sorting in Chapter 3. If the values to be sorted will fit into the sort buffer, MySQL can perform the sort entirely in memory with a quicksort. It uses a quicksort to sort each chunk and then merges the sorted chunk into the results. On the other hand, it stores a minimal amount of data during the sort, so if the rows to be sorted are completely in memory, it can be cheaper to store less data and reread the rows to generate the final result.
Reads all the columns needed for the query, sorts them by the ORDER BY columns, and then scans the sorted list and outputs the specified columns. This algorithm is available only in MySQL 4. However, it has the potential to use a lot more space, because it holds all desired columns from each row, not just the columns needed to sort the rows. This means fewer tuples will fit into the sort buffer, and the filesort will have to perform more sort merge passes.
When sorting a join, MySQL may perform the filesort at two stages during the query execution. The plan is a data structure; it is not executable byte-code, which is how many other databases execute queries. In contrast to the optimization stage, the execution stage is usually not all that complex: MySQL simply follows the instructions given in the query execution plan. Many of the operations in the plan invoke methods implemented by the storage engine interface, also known as the handler API.
Each table in the query is represented by an instance of a handler. If a table appears three times in the query, for example, the server creates three handler instances. Though we glossed over this before, MySQL actually creates the handler instances early in the optimization stage. The optimizer uses them to get information about the tables, such as their column names and index statistics.
This is enough for a query that does an index scan. Not everything is a handler operation. For example, the server manages table locks. As explained in Chapter 1 , anything that all storage engines share is implemented in the server, such as date and time functions, views, and triggers. To execute the query, the server just repeats the instructions until there are no more rows to examine. The final step in executing a query is to reply to the client.
If the query is cacheable, MySQL will also place the results into the query cache at this stage. The server generates and sends results incrementally.
Think back to the single-sweep multijoin method we mentioned earlier. As soon as MySQL processes the last table and generates one row successfully, it can and should send that row to the client.
This has two benefits: it lets the server avoid holding the row in memory, and it means the client starts getting the results as soon as possible. Some of these limitations will probably be eased or removed entirely in future versions, and some have already been fixed in versions not yet released as GA generally available.
In particular, there are a number of subquery optimizations in the MySQL 6 source code, and more are in progress. MySQL sometimes optimizes subqueries very badly. This feels natural to write with a subquery, as follows:. We said an IN list is generally very fast, so you might expect the query to be optimized to something like this:.
Unfortunately, exactly the opposite happens. It rewrites the query as follows:. Sometimes this can be faster than a JOIN. MySQL has been criticized thoroughly for this particular type of subquery execution plan. Although it definitely needs to be fixed, the criticism often confuses two different issues: execution order and caching. Rewriting the query yourself lets you take control over both aspects. Future versions of MySQL should be able to optimize this type of query much better, although this is no easy task.
There are very bad worst cases for any execution plan, including the inside-out execution plan that some people think would be simple to optimize. Instead, benchmark and make your own decision. Sometimes a correlated subquery is a perfectly reasonable, or even optimal, way to get a result.
This is an example of the early-termination algorithm we mentioned earlier in this chapter. So, in theory, MySQL will execute the queries almost identically. In reality, benchmarking is the only way to tell which approach is really faster. We benchmarked both queries on our standard setup. The results are shown in Table Sometimes a subquery can be faster. For example, it can work well when you just want to see rows from one table that match rows in another table.
The following join, which is designed to find every film that has an actor, will return duplicates because some films have multiple actors:. But what are we really trying to express with this query, and is it obvious from the SQL? Again, we benchmarked to see which strategy was faster. In this example, the subquery performs much faster than the join. We showed this lengthy example to illustrate two points: you should not heed categorical advice about subqueries, and you should use benchmarks to prove your assumptions about query plans and execution speed.
Index merge algorithms, introduced in MySQL 5. In MySQL 5. There are three variations on the algorithm: union for OR conditions, intersection for AND conditions, and unions of intersections for combinations of the two. The following query uses a union of two index scans, as you can see by examining the Extra column:. This is especially true if not all of the indexes are very selective, so the parallel scans return lots of rows to the merge operation.
This is another reason to design realistic benchmarks. Equality propagation can have unexpected costs sometimes. This is normally helpful, because it gives the query optimizer and execution engine more options for where to actually execute the IN check. But when the list is very large, it can result in slower optimization and execution. This is a feature offered by some other database servers, but not MySQL. However, you can emulate hash joins using hash indexes. MySQL has historically been unable to do loose index scans, which scan noncontiguous ranges of an index.
MySQL will scan the entire range of rows within these end points. An example will help clarify this. Suppose we have a table with an index on columns a, b , and we want to run the following query:. Figure shows what that strategy would look like if MySQL were able to do it. A loose index scan, which MySQL cannot currently do, would be more efficient.
Beginning in MySQL 5. This is a good optimization for this special purpose, but it is not a general-purpose loose index scan. Until MySQL supports general-purpose loose index scans, the workaround is to supply a constant or list of constants for the leading columns of the index.
We showed several examples of how to get good performance with these types of queries in our indexing case study in the previous chapter. However, in this case, MySQL will scan the whole table, which you can verify by profiling the query. This general strategy often works well when MySQL would otherwise choose to scan more rows than necessary.
True, but sometimes you have to compromise your principles to get high performance. The query updates each row with the number of similar rows in the table:. To work around this limitation, you can use a derived table, because MySQL materializes it as a temporary table.
In this section, we give advice on how to optimize certain kinds of queries. Most of the advice in this section is version-dependent, and it may not hold for future versions of MySQL. You can do a web search and find more misinformation on this topic than we care to think about.
COUNT is a special function that works in two very different ways: it counts values and rows. If you specify a column name or other expression inside the parentheses, COUNT counts how many times that expression has a value. This is confusing for many people, in part because values and NULL are confusing.
The Internet is not necessarily a good source of accurate information on this topic, either. One of the most common mistakes we see is specifying column names inside the parentheses when you want to count rows. This communicates your intention clearly and avoids poor performance. MySQL can optimize this away because the storage engine always knows how many rows are in the table.
MyISAM does not have any magical speed optimizations for counting rows when the query has a WHERE clause, or for the more general case of counting values instead of rows.
It may be faster than other storage engines for a given query, or it may not be. That depends on a lot of factors. The following example uses the standard World database to show how you can efficiently find the number of cities whose ID is greater than 5.
You might write this query as follows:. If you negate the conditions and subtract the number of cities whose ID s are less than or equal to 5 from the total number of cities, you can reduce that to five rows:. This version reads fewer rows because the subquery is turned into a constant during the query optimization phase, as you can see with EXPLAIN :. A frequent question on mailing lists and IRC channels is how to retrieve counts for several different values in the same column with just one query, to reduce the number of queries required.
For example, say you want to create a single query that counts how many items have each of several colors. Here is a query that solves this problem:. Your only other option for optimizing within MySQL itself is to use a covering index, which we discussed in Chapter 3.
Consider summary tables also covered in Chapter 3 , and possibly an external caching system such as memcached. This topic is actually spread throughout most of the book, but we mention a few highlights:. Consider the join order when adding indexes. Unused indexes are extra overhead.
Be careful when upgrading MySQL, because the join syntax, operator precedence, and other behaviors have changed at various times.
What used to be a normal join can sometimes become a cross product, a different kind of join that returns different results, or even invalid syntax. The most important advice we can give on subqueries is that you should usually prefer a join where possible, at least in current versions of MySQL. We covered this topic extensively earlier in this chapter. Subqueries are the subject of intense work by the optimizer team, and upcoming versions of MySQL may have more subquery optimizations.
The server is getting smarter all the time, and the cases where you have to tell it how to do something instead of what results to return are becoming fewer. MySQL optimizes these two kinds of queries similarly in many cases, and in fact converts between them as needed internally during the optimization process.
Either one can be more efficient for any given query. Grouping by actor. However, sometimes your only concern will be making MySQL execute the query as quickly as possible. The purists will be satisfied with the following way of writing the query:. But sometimes the cost of creating and filling the temporary table required for the subquery is high compared to the cost of fudging pure relational theory a little bit.
Mar 11, PM. AB books view quotes. Mar 08, PM. Ernest 63 books view quotes. Jan 21, PM. Alec 0 books view quotes. Dec 22, PM. Alessandro books view quotes. Dec 14, PM. Amy 3, books view quotes. Nov 20, PM. Robbie Dee 1, books view quotes. Sep 19, PM. Liam books view quotes. Sep 14, AM. William 44 books view quotes. Sep 12, PM. Craig books view quotes. Jul 31, PM. Saleh 1, books view quotes. Jun 06, AM.
Maya books view quotes. Jan 17, PM. Maryjoelisa books view quotes. Oct 21, AM. Roxnostalgia 82 books view quotes. Sep 30, PM. Angelia 30 books view quotes. Sep 21, PM. Anahit books view quotes. Alyssa books view quotes. Jul 01, AM. Maitri 1 book view quotes. May 24, PM. El Mehdi 1, books view quotes. May 15, PM.
Joanna 2, books view quotes. May 10, PM. Accuni 29 books view quotes. Apr 25, PM. Lindsay books view quotes. Apr 10, PM. Jack Henry books view quotes. Mar 12, PM. Lissa 59 books view quotes. Jan 30, PM. Connaire 0 books view quotes. Jan 10, PM. Amanda books view quotes. Dec 25, PM. Nov 06, AM. Sierraa 30 books view quotes. Oct 04, PM. Kris books view quotes. Jul 09, AM.
0コメント