Debian Codegraph @

www/queryplanner-ng.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>The Next-Generation Query Planner</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 The Next-Generation Query Planner
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#_introduction">1. Introduction</a></div>
129 <div class="fancy-toc1"><a href="#_background">2. Background</a></div>
130 <div class="fancy-toc2"><a href="#_query_planning_in_sqlite">2.1. Query Planning In SQLite</a></div>
131 <div class="fancy-toc2"><a href="#_the_sqlite_query_planner_stability_guarantee">2.2. The SQLite Query Planner Stability Guarantee</a></div>
132 <div class="fancy-toc1"><a href="#_a_difficult_case">3. A Difficult Case</a></div>
133 <div class="fancy-toc2"><a href="#_query_details">3.1. Query Details</a></div>
134 <div class="fancy-toc2"><a href="#_complications">3.2. Complications</a></div>
135 <div class="fancy-toc2"><a href="#_finding_the_best_query_plan">3.3. Finding The Best Query Plan</a></div>
136 <div class="fancy-toc2"><a href="#_the_n_nearest_neighbors_or_n3_heuristic">3.4. The N Nearest Neighbors or "N3" Heuristic</a></div>
137 <div class="fancy-toc1"><a href="#_hazards_of_upgrading_to_ngqp">4. Hazards Of Upgrading To NGQP</a></div>
138 <div class="fancy-toc2"><a href="#_case_study_upgrading_fossil_to_the_ngqp">4.1. Case Study: Upgrading Fossil to the NGQP</a></div>
139 <div class="fancy-toc2"><a href="#_fixing_the_problem">4.2. Fixing The Problem</a></div>
140 <div class="fancy-toc2"><a href="#update_2017_a_better_fix">4.3. Update 2017: A Better Fix</a></div>
141 <div class="fancy-toc1"><a href="#_checklist_for_avoiding_or_fixing_query_planner_problems">5. Checklist For Avoiding Or Fixing Query Planner Problems</a></div>
142 <div class="fancy-toc1"><a href="#_summary">6. Summary</a></div>
143 </div>
144 </div>
145 <script>
146 function toggle_toc(){
147 var sub = document.getElementById("toc_sub")
148 var mk = document.getElementById("toc_mk")
149 if( sub.style.display!="block" ){
150 sub.style.display = "block";
151 mk.innerHTML = "&#x25bc;";
152 } else {
153 sub.style.display = "none";
154 mk.innerHTML = "&#x25ba;";
155 }
156 }
157 </script>
158 </div>
159
160
161
162
163
164 <h1 id="_introduction"><span>1. </span> Introduction</h1>
165
166 <p>
167 The task of the "query planner" is to figure
168 out the best algorithm or "query plan" to accomplish an SQL statement.
169 Beginning with SQLite <a href="releaselog/3_8_0.html">version 3.8.0</a> (2013-08-26),
170 the query planner component has been
171 rewritten so that it runs faster and generates better plans. The
172 rewrite is called the "next generation query planner" or "NGQP".
173 </p>
174
175 <p>This article overviews the importance of query planning, describes some
176 of the problems inherent to query planning, and outlines how the NGQP
177 solves those problems.</p>
178
179 <p>The NGQP is almost always better than the legacy query planner.
180 However, there may exist legacy applications that unknowingly depend on
181 undefined and/or suboptimal behavior in the legacy query planner, and
182 upgrading to the NGQP on those legacy applications could cause performance
183 regressions. This risk is considered and a checklist is provided
184 for reducing the risk and for fixing any issues that do arise.</p>
185
186 <p>This document focuses on the NGQP. For a more general overview of the
187 SQLite query planner that encompasses the entire history of SQLite, see the
188 "<a href="optoverview.html">The SQLite Query Optimizer Overview</a>" and
189 "<a href="queryplanner.html">How Indexes Work</a>" documents.</p>
190
191 <h1 id="_background"><span>2. </span> Background</h1>
192
193 <p>For simple queries against a single table with few indexes, there is usually
194 an obvious choice for the best algorithm.
195 But for larger and more complex queries, such as
196 multi-way joins with many indexes
197 and subqueries, there can be hundreds, thousands, or millions
198 of reasonable algorithms for computing the result.
199 The job of the query planner is to choose the single "best" query plan from
200 this multitude of possibilities.</p>
201
202 <p>Query planners are what make SQL database engines so amazingly useful and powerful.
203 (This is true of all SQL database engines, not just SQLite.)
204 The query planner frees the programmer from the chore of selecting
205 a particular query plan, and thereby allows the programmer to
206 focus more mental energy on higher-level application issues and on
207 providing more value to the end user. For simple queries where the choice
208 of query plan is obvious, this is convenient but not hugely important.
209 But as applications and schemas and queries grow more complex, a
210 clever query planner can greatly speed and simplify the work of application
211 development.
212 There is amazing power in being about to tell
213 the database engine what content is desired, and then let the database
214 engine figure out the best way to retrieve that content.</p>
215
216 <p>Writing a good query planner is more art than science.
217 The query planner must work with incomplete information.
218 It cannot determine how long any particular plan will take
219 without actually running that plan. So when comparing two
220 or more plans to figure out which is "best", the query planner has to make
221 some guesses and assumptions and those guesses and assumptions will
222 sometimes be wrong. A good query planner is one that will
223 find the correct solution often enough that application
224 programmers rarely need to get involved.</p>
225
226 <h2 id="_query_planning_in_sqlite"><span>2.1. </span> Query Planning In SQLite</h2>
227
228 <p>SQLite computes joins using nested loops,
229 one loop for each table
230 in the join. (Additional loops might be inserted for IN
231 and OR operators in the WHERE clause. SQLite considers those too,
232 but for simplicity we will ignore them in this essay.)
233 One or more indexes might be used on each loop to speed the search,
234 or a loop might be a "full table scan" that reads every row in the
235 table. Thus query planning decomposes into two subtasks:</p>
236 <ol>
237 <li> Picking the nested order of the various loops
238 </li><li> Choosing good indexes for each loop
239 </li></ol>
240 <p>Picking the nesting order is generally the more challenging problem.
241 Once the nesting order of the join is established, the choice of indexes
242 for each loop is normally obvious.</p>
243
244 <a name="qpstab"></a>
245
246 <h2 id="_the_sqlite_query_planner_stability_guarantee"><span>2.2. </span> The SQLite Query Planner Stability Guarantee</h2>
247
248 <p>When the Query Planner Stability Guarantee (QPSG) is enabled
249 SQLite will always pick the same query plan for any
250 given SQL statement as long as:
251
252 </p><ol type="a">
253 <li>the database schema does not change in significant ways such as
254 adding or dropping indexes,</li>
255 <li>the ANALYZE command is not rerun, </li>
256 <li>the same version of SQLite is used.</li>
257 </ol>
258
259 <p>The QPSG is disabled by default. It can be enabled at compile-time
260 using the <a href="compile.html#enable_qpsg">SQLITE_ENABLE_QPSG</a> compile-time option, or at run-time by
261 invoking <a href="c3ref/db_config.html">sqlite3_db_config</a>(db,<a href="c3ref/c_dbconfig_defensive.html#sqlitedbconfigenableqpsg">SQLITE_DBCONFIG_ENABLE_QPSG</a>,1,0).
262
263 </p><p>The QPSG means that if all of your queries run efficiently
264 during testing, and if your application does not change the schema,
265 then SQLite will not suddenly decide to start using a different
266 query plan, possibly causing a performance problem after your application
267 is released to users. If your application works in the lab, it
268 will continue working the same way after deployment.</p>
269
270 <p>Client/server SQL database engines do not normally
271 make this guarantee.
272 In client/server SQL database engines, the server keeps track of
273 statistics on the sizes of tables and on the quality of indexes
274 and the query planner uses those statistics to help select the best plans.
275 As content is added, deleted, or changed in the database, the statistics
276 will evolve and may cause the query planner to begin using a different
277 query plan for some particular query. Usually the new plan will be better
278 for the evolving structure of the data. But sometimes the new query plan will
279 cause a performance reduction. With a client/server database engine, there
280 is typically a Database Administrator (DBA) on hand to deal with these
281 rare problems as they come up. But DBAs are not available to fix problems
282 in an embedded database like SQLite, and hence SQLite is careful to
283 ensure that plans do not change unexpectedly after deployment.</p>
284
285 <p>It is important to note that changing versions of SQLite might cause
286 changes in query plans.
287 The same version of SQLite will
288 always pick the same query plan, but if you relink your application to use
289 a different version of SQLite, then query plans might change. In rare
290 cases, an SQLite version change might lead to a performance regression.
291 This is one reason
292 you should consider statically linking your applications against SQLite
293 rather than use a system-wide SQLite shared library which might
294 change without your knowledge or control.</p>
295
296 <p>See also:
297 </p><ul>
298 <li> <a href="lang_analyze.html#req">Recommended usage patterns for ANALYZE</a>
299 </li><li> <a href="pragma.html#pragma_optimize">PRAGMA optimize</a>
300 </li></ul>
301
302 <h1 id="_a_difficult_case"><span>3. </span> A Difficult Case</h1>
303
304 <p>
305 "TPC-H Q8" is a test query from the
306 <a href="http://www.tpc.org/tpch/">Transaction Processing Performance
307 Council</a>. The query planners in SQLite versions 3.7.17 and earlier
308 do not choose good plans for TPC-H Q8. And it has been determined that
309 no amount
310 of tweaking of the legacy query planner will fix that. In order to find
311 a good solution to the TPC-H Q8 query, and to continue improving the
312 quality of SQLite's query planner, it became necessary to redesign the
313 query planner. This section tries to explain why this redesign was
314 necessary and how the NGQP is different and addresses the TPC-H Q8 problem.
315 </p>
316
317 <h2 id="_query_details"><span>3.1. </span> Query Details</h2>
318
319 <p>
320 TPC-H Q8 is an eight-way join.
321 As observed above, the main task of the query planner is
322 to figure out the best nesting order of the eight loops in order to minimize
323 the work needed to complete the join.
324 A simplified model of this problem for the case of TPC-H Q8 is shown
325 by the following diagram:
326 </p>
327
328 <center>
329 <div style="max-width:677px;"><svg xmlns='http://www.w3.org/2000/svg' class="pikchr" viewBox="0 0 677.503 310.031">
330 <circle cx="132" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
331 <text x="132" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">S</text>
332 <circle cx="234" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
333 <text x="234" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">L</text>
334 <circle cx="336" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
335 <text x="336" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">O</text>
336 <circle cx="438" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
337 <text x="438" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">C</text>
338 <circle cx="539" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
339 <text x="539" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">N1</text>
340 <circle cx="641" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
341 <text x="641" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">R</text>
342 <circle cx="234" cy="205" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
343 <text x="234" y="205" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">P</text>
344 <circle cx="30" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
345 <text x="30" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">N2</text>
346 <polygon points="104,101 91,101 94,93" style="fill:rgb(0,0,0)"/>
347 <path d="M58,101 L 70,96 Q 81,92 90,95 L 98,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
348 <text x="81" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">6.00</text>
349 <polygon points="58,106 71,106 68,114" style="fill:rgb(0,0,0)"/>
350 <path d="M104,106 L 92,111 Q 81,115 72,112 L 64,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
351 <text x="81" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">2.08</text>
352 <polygon points="205,101 193,101 196,93" style="fill:rgb(0,0,0)"/>
353 <path d="M160,101 L 171,96 Q 183,92 191,95 L 200,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
354 <text x="183" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">9.17</text>
355 <polygon points="160,106 172,106 169,114" style="fill:rgb(0,0,0)"/>
356 <path d="M205,106 L 194,111 Q 183,115 174,112 L 166,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
357 <text x="183" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">2.30</text>
358 <polygon points="307,101 295,101 298,93" style="fill:rgb(0,0,0)"/>
359 <path d="M262,101 L 273,96 Q 285,92 293,95 L 302,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
360 <text x="285" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">2.77</text>
361 <polygon points="262,106 274,106 271,114" style="fill:rgb(0,0,0)"/>
362 <path d="M307,106 L 296,111 Q 285,115 276,112 L 267,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
363 <text x="285" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">4.03</text>
364 <polygon points="409,101 397,101 400,93" style="fill:rgb(0,0,0)"/>
365 <path d="M364,101 L 375,96 Q 387,92 395,95 L 404,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
366 <text x="387" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">2.64</text>
367 <polygon points="364,106 376,106 373,114" style="fill:rgb(0,0,0)"/>
368 <path d="M409,106 L 398,111 Q 387,115 378,112 L 369,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
369 <text x="387" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">5.30</text>
370 <polygon points="511,101 499,101 502,93" style="fill:rgb(0,0,0)"/>
371 <path d="M466,101 L 477,96 Q 489,92 497,95 L 506,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
372 <text x="489" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">2.08</text>
373 <polygon points="466,106 478,106 475,114" style="fill:rgb(0,0,0)"/>
374 <path d="M511,106 L 500,111 Q 489,115 480,112 L 471,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
375 <text x="489" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">6.40</text>
376 <polygon points="613,101 601,101 604,93" style="fill:rgb(0,0,0)"/>
377 <path d="M568,101 L 579,96 Q 590,92 599,95 L 608,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
378 <text x="590" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">1.79</text>
379 <polygon points="568,106 580,106 577,114" style="fill:rgb(0,0,0)"/>
380 <path d="M613,106 L 602,111 Q 590,115 582,112 L 573,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
381 <text x="590" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">3.47</text>
382 <polygon points="237,177 237,165 245,168" style="fill:rgb(0,0,0)"/>
383 <path d="M237,132 L 241,143 Q 245,155 242,163 L 239,172" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
384 <text x="245" y="155" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">2.64</text>
385 <polygon points="231,132 231,144 223,141" style="fill:rgb(0,0,0)"/>
386 <path d="M231,177 L 227,166 Q 222,155 226,146 L 229,137" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
387 <text x="222" y="155" text-anchor="end" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">6.01</text>
388 <circle cx="30" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
389 <text x="30" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
390 <polygon points="30,75 26,64 34,64" style="fill:rgb(0,0,0)"/>
391 <path d="M30,30L30,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
392 <text x="30" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 5.52</text>
393 <circle cx="132" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
394 <text x="132" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
395 <polygon points="132,75 128,64 136,64" style="fill:rgb(0,0,0)"/>
396 <path d="M132,30L132,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
397 <text x="132" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 9.47</text>
398 <circle cx="234" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
399 <text x="234" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
400 <polygon points="234,75 229,64 238,64" style="fill:rgb(0,0,0)"/>
401 <path d="M234,30L234,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
402 <text x="234" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 16.40</text>
403 <circle cx="336" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
404 <text x="336" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
405 <polygon points="336,75 331,64 340,64" style="fill:rgb(0,0,0)"/>
406 <path d="M336,30L336,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
407 <text x="336" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 13.87</text>
408 <circle cx="438" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
409 <text x="438" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
410 <polygon points="438,75 433,64 442,64" style="fill:rgb(0,0,0)"/>
411 <path d="M438,30L438,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
412 <text x="438" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 12.56</text>
413 <circle cx="539" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
414 <text x="539" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
415 <polygon points="539,75 535,64 544,64" style="fill:rgb(0,0,0)"/>
416 <path d="M539,30L539,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
417 <text x="539" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 5.52</text>
418 <circle cx="641" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
419 <text x="641" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
420 <polygon points="641,75 637,64 646,64" style="fill:rgb(0,0,0)"/>
421 <path d="M641,30L641,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
422 <text x="641" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 3.56</text>
423 <circle cx="234" cy="293" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
424 <text x="234" y="293" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
425 <polygon points="234,234 238,245 229,245" style="fill:rgb(0,0,0)"/>
426 <path d="M234,279L234,240" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
427 <text x="234" y="256" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 7.71</text>
428 </svg>
429 </div>
430 </center>
431
432 <p>
433 In the diagram, each of the 8 tables in the FROM clause of the query is
434 identified by a large circle with the label of the FROM-clause term:
435 N2, S, L, P, O, C, N1 and R.
436 The arcs in the graph represent the estimated cost of computing each term
437 assuming that the origin of the arc is in an outer loop. For example, the
438 cost of running the S loop as an inner loop to L is 2.30 whereas the
439 cost of running the S loop as an outer loop to L is 9.17.</p>
440
441 <p>The "cost" here is logarithmic. With nested loops, the work
442 is multiplied, not added. But it is customary to think of graphs
443 with additive weights and so the graph shows the logarithm of the
444 various costs. The graph shows a cost advantage of S being inside of
445 L of about 6.87, but this translates into the query running about
446 963 times faster when S loop is inside of the L loop rather than
447 being outside of it.</p>
448
449 <p>The arrows from the small circles labeled with "*" indicate the cost
450 of running each loop with no dependencies. The outermost loop must use this
451 *-cost. Inner loops have the option of using the *-cost or a cost assuming
452 one of the other terms is in an outer loop, whichever gives the best
453 result. One can think of the *-costs as a short-hand notation indicating
454 multiple arcs, one from each of the other nodes in the
455 graph. The graph is therefore "complete", meaning that there are arcs
456 (some explicit and some implied) in both directions between every pair of
457 nodes in the graph.</p>
458
459 <p>The problem of finding the best query plan is equivalent to finding
460 a minimum-cost path through the graph that visits each node
461 exactly once.</p>
462
463 <p>(Side note: The cost estimates in the TPC-H Q8 graph above were computed
464 by the query planner in SQLite 3.7.16 and converted using a natural logarithm.)
465 </p>
466
467 <h2 id="_complications"><span>3.2. </span> Complications</h2>
468
469 <p>The presentation of the query planner problem above is a simplification.
470 The costs are estimates. We cannot
471 know what the true cost of running a loop is until we actually run the loop.
472 SQLite makes guesses for the cost of running a loop based on
473 the availability of indexes and constraints found in the WHERE
474 clause. These guesses are usually pretty good, but they can sometimes be
475 off. Using the <a href="lang_analyze.html">ANALYZE</a> command to collect additional statistical
476 information about the database can sometimes enable SQLite to make better
477 guesses about the cost.</p>
478
479 <p>The costs are comprised of multiple numbers, not a single number as
480 shown in the graph.
481 SQLite computes several different estimated costs for each loop that apply at
482 different times. For example, there is a "setup" cost that is incurred
483 just once when the query starts. The setup cost is the cost of computing
484 an <a href="optoverview.html#autoindex">query-time index</a> for a table that does not already
485 have an index. Then there
486 is the cost of running each step of the loop. Finally, there is an estimate
487 of the number rows generated by the loop, which is information needed in
488 estimating the costs of inner loops. Sorting costs may come into play
489 if the query has an ORDER BY clause.</p>
490
491 <p>In a general query, dependencies need not be on a single loop, and hence
492 the matrix of dependencies might not be representable as a graph.
493 For example, one of the WHERE clause constraints might be
494 S.a=L.b+P.c, implying that the S loop must be an inner loop of both
495 L and P. Such dependencies cannot be drawn as a graph
496 since there is no way for an arc to originate at two or more nodes at
497 once.</p>
498
499 <p>If the query contains an ORDER BY clause or a GROUP BY clause or if
500 the query uses the DISTINCT keyword then it is advantageous to select a
501 path through the graph that causes rows to naturally appear in sorted order,
502 so that no separate sorting step is required. Automatic elimination of
503 ORDER BY clauses
504 can make a large performance difference, so this is another factor
505 that needs to be considered in a complete implementation.</p>
506
507 <p>In the TPC-H Q8 query, the setup costs are all negligible,
508 all dependencies are between individual nodes, and there is no ORDER BY,
509 GROUP BY, or DISTINCT clause. So for TPC-H Q8,
510 the graph above is a reasonable representation of what needs to be computed.
511 The general case involves a lot of extra complication, which for clarity
512 is neglected in the remainder of this article.</p>
513
514 <h2 id="_finding_the_best_query_plan"><span>3.3. </span> Finding The Best Query Plan</h2>
515
516 <p>Prior to <a href="releaselog/3_8_0.html">version 3.8.0</a> (2013-08-26), SQLite always used
517 the "Nearest Neighbor" or "NN" heuristic when searching for the best query plan.
518 The NN heuristic makes a single traversal of the graph, always choosing
519 the lowest-cost arc as the next step.
520 The NN heuristic works surprisingly well in most cases.
521 And NN is fast, so that SQLite is able to quickly find good plans
522 for even large 64-way joins. In contrast, other SQL database engines that
523 do more extensive searching tend to bog down when the
524 number of tables in a join goes above 10 or 15.</p>
525
526 <p>Unfortunately, the query plan computed by NN for TPC-H Q8 is not optimal.
527 The plan computed using NN is R-N1-N2-S-C-O-L-P with a cost of 36.92.
528 The notation
529 in the previous sentence means that the R table is run in the outer loop,
530 N1 is in the next inner loop, N2 is in the third loop, and so forth down
531 to P which is in the inner-most loop. The shortest path through the
532 graph (as found via exhaustive search) is P-L-O-C-N1-R-S-N2
533 with a cost of 27.38. The difference might not seem like much, but
534 remember that
535 the costs are logarithmic, so the shortest path is nearly 750 times
536 faster than that path found using the NN heuristic.</p>
537
538 <p>One solution to this problem is to change SQLite to do an exhaustive
539 search for the best path. But an exhaustive search requires time
540 proportional to
541 K! (where K is the number of tables in the join) and so when you get
542 beyond a 10-way join, the time
543 to run <a href="c3ref/prepare.html">sqlite3_prepare()</a> becomes very large.</p>
544
545 <h2 id="_the_n_nearest_neighbors_or_n3_heuristic"><span>3.4. </span> The N Nearest Neighbors or "N3" Heuristic</h2>
546
547 <p>The NGQP uses a new heuristic for seeking the best path through the
548 graph: "N Nearest Neighbors" (hereafter "N3"). With N3, instead of
549 choosing just one nearest neighbor for each step, the algorithm keeps
550 track of the N bests paths at each step for some small integer N.</p>
551
552 <p>Suppose N=4. Then for the TPC-H Q8 graph, the first step finds
553 the four shortest paths to visit any single node in the graph:
554
555 </p><blockquote>
556 R (cost: 3.56) <br>
557 N1 (cost: 5.52) <br>
558 N2 (cost: 5.52) <br>
559 P (cost: 7.71) <br>
560 </blockquote>
561
562 <p>The second step finds the four shortest paths to visit two nodes
563 beginning with one of the four paths from the previous step. In the
564 case where two or more paths are equivalent (they have the same set of
565 visited nodes, though possibly in a different order) only the
566 first and lowest-cost path is retained. We have:</p>
567
568 <blockquote>
569 R-N1 (cost: 7.03) <br>
570 R-N2 (cost: 9.08) <br>
571 N2-N1 (cost: 11.04) <br>
572 R-P {cost: 11.27} <br>
573 </blockquote>
574
575 <p>The third step starts with the four shortest two-node paths and finds
576 the four shortest three-node paths:</p>
577
578 <blockquote>
579 R-N1-N2 (cost: 12.55) <br>
580 R-N1-C (cost: 13.43) <br>
581 R-N1-P (cost: 14.74) <br>
582 R-N2-S (cost: 15.08) <br>
583 </blockquote>
584
585 <p>And so forth. There are 8 nodes in the TPC-H Q8 query,
586 so this process repeats a total of 8
587 times. In the general case of a K-way join, the storage requirement
588 is O(N) and the computation time is O(K*N), which is significantly faster
589 than the O(2<small><sup>K</sup></small>) exact solution.</p>
590
591 <p>But what value to choose for N? One might try N=K. This makes the
592 algorithm O(K<small><sup>2</sup></small>)
593 which is actually still quite efficient, since the
594 maximum value of K is 64 and K rarely exceeds 10.
595 But that is not enough for the TPC-H Q8
596 problem. With N=8 on TPC-H Q8 the N3 algorithm finds
597 the solution R-N1-C-O-L-S-N2-P with a cost of 29.78.
598 That is a big improvement over NN, but it is still
599 not optimal. N3 finds the optimal solution for TPC-H Q8
600 when N is 10 or greater.</p>
601
602 <p>The initial implementation of NGQP chooses N=1 for simple queries, N=5
603 for two-way joins and N=10 for all joins with three or more tables. This
604 formula for selecting N might change in subsequent releases.</p>
605
606 <a name="hazards"></a>
607
608 <h1 id="_hazards_of_upgrading_to_ngqp"><span>4. </span> Hazards Of Upgrading To NGQP</h1>
609
610 <p><i>&rarr; Update: <b>This section is obsolete and retained for
611 historical reference only.</b> This section was important
612 when the NGQP was new. But a decade has elapsed, the NGQP has been
613 deployed successfully to billions of devices, and everyone has upgraded,
614 and no performance regressions were ever reported back to the SQLite
615 developers. The upgrade hazard has vanished.
616 This section is retained for historical reference only.
617 Modern readers can <b>skip ahead to the <a href="queryplanner-ng.html#howtofix">query planner checklist</a></b>.&larr;</i>
618
619 </p><p>For most applications, upgrading from the legacy query planner to the NGQP
620 requires little thought or effort.
621 Simply replace the older SQLite version with the newer version of SQLite
622 and recompile and the application will run faster.
623 There are no API changes nor modifications
624 to compilation procedures.</p>
625
626 <p>But as with any query planner change, upgrading to the NGQP does carry
627 a small risk of introducing performance regressions. The problem here is
628 not that the NGQP is incorrect or buggy or inferior to the legacy query
629 planner. Given reliable information about the selectivity of indexes,
630 the NGQP should always pick a plan that is as good as before, or better.
631 The problem is that some applications may be using low-quality and
632 low-selectivity indexes without having run <a href="lang_analyze.html">ANALYZE</a>. The older query
633 planners look at many fewer possible implementations for each query and
634 so they may have stumbled over a good plan by stupid luck. The NGQP, on
635 the other hand, looks at many more query plan possibilities, and it may
636 choose a different query plan that
637 works better in theory, assuming good indexes, but which gives a performance
638 regression in practice, because of the shape of the data.</p>
639
640 <p>Key points:</p>
641
642 <ul>
643 <li><p>The NGQP will always find an equal or better query plan, compared to
644 prior query planners, as long as it
645 has access to accurate <a href="lang_analyze.html">ANALYZE</a> data in the <a href="fileformat2.html#stat1tab">SQLITE_STAT1</a> file.</p>
646 </li><li><p>The NGQP will always find a good query plan
647 as long as the schema does not contain indexes that have more than
648 about 10 or 20 rows with the same value in the left-most column of the
649 index.</p>
650 </li></ul>
651
652 <p>Not all applications meet these conditions. Fortunately,
653 the NGQP will still usually find good query plans, even without these conditions.
654 However, cases do arise (rarely) where performance regressions can occur.</p>
655
656 <a name="fossilcasestudy"></a>
657
658 <h2 id="_case_study_upgrading_fossil_to_the_ngqp"><span>4.1. </span> Case Study: Upgrading Fossil to the NGQP</h2>
659
660 <p>The <a href="http://www.fossil-scm.org/">Fossil DVCS</a> is the version
661 control system used to track all of the SQLite source code.
662 A Fossil repository is an SQLite database file.
663 (Readers are invited to ponder this recursion as an independent exercise.)
664 Fossil is both the version-control system for SQLite and a test
665 platform for SQLite. Whenever enhancements are made to SQLite,
666 Fossil is one of the first applications to test and evaluate those
667 enhancements. So Fossil was an early adopter of the NGQP.</p>
668
669 <p>Unfortunately, the NGQP caused a
670 performance regression in Fossil.</p>
671
672 <p>One of the many reports that Fossil makes available is a timeline of
673 changes to a single branch showing all merges in and out of that branch. See
674 <a href="https://www.sqlite.org/src/timeline?nd&n=200&r=trunk">https://www.sqlite.org/src/timeline?nd&n=200&r=trunk</a>
675 for a typical
676 example of such a report. Generating such a report normally takes just
677 a few milliseconds. But after upgrading to the NGQP we noticed that
678 this one report was taking closer to 10 seconds for the trunk of the
679 repository.</p>
680
681 <p>The core query used to generate the branch timeline is shown below.
682 (Readers are not expected to understand the details of this query.
683 Commentary will follow.)</p>
684
685 <blockquote><pre>
686 SELECT
687 blob.rid AS blobRid,
688 uuid AS uuid,
689 datetime(event.mtime,'localtime') AS timestamp,
690 coalesce(ecomment, comment) AS comment,
691 coalesce(euser, user) AS user,
692 blob.rid IN leaf AS leaf,
693 bgcolor AS bgColor,
694 event.type AS eventType,
695 (SELECT group_concat(substr(tagname,5), ', ')
696 FROM tag, tagxref
697 WHERE tagname GLOB 'sym-*'
698 AND tag.tagid=tagxref.tagid
699 AND tagxref.rid=blob.rid
700 AND tagxref.tagtype>0) AS tags,
701 tagid AS tagid,
702 brief AS brief,
703 event.mtime AS mtime
704 FROM event CROSS JOIN blob
705 WHERE blob.rid=event.objid
706 AND (EXISTS(SELECT 1 FROM tagxref
707 WHERE tagid=11 AND tagtype>0 AND rid=blob.rid)
708 OR EXISTS(SELECT 1 FROM plink JOIN tagxref ON rid=cid
709 WHERE tagid=11 AND tagtype>0 AND pid=blob.rid)
710 OR EXISTS(SELECT 1 FROM plink JOIN tagxref ON rid=pid
711 WHERE tagid=11 AND tagtype>0 AND cid=blob.rid))
712 ORDER BY event.mtime DESC
713 LIMIT 200;
714 </pre></blockquote>
715
716 <p>This query is not
717 especially complicated, but even so it replaces hundreds or
718 perhaps thousands of lines of procedural code.
719 The gist of the query is this: Scan down the EVENT table looking
720 for the most recent 200 check-ins that satisfy any one of three conditions:
721
722 </p><p></p><ol>
723 <li> The check-in has a "trunk" tag.
724 </li><li> The check-in has a child that has a "trunk" tag.
725 </li><li> The check-in has a parent that has a "trunk" tag.
726 </li></ol>
727
728 <p>
729 The first condition causes all of the trunk check-ins to be displayed and
730 the second and third cause check-ins that merge into or fork from
731 the trunk to also be included.
732 The three conditions are implemented by the three OR-connected
733 EXISTS statements in the WHERE clause of the query.
734 The slowdown that occurred with the NGQP was caused by the second and
735 third conditions. The problem is the same in each, so we will examine
736 just the second one.
737 The subquery of the second condition can be rewritten (with minor
738 and immaterial simplifications) as follows:</p>
739
740 <blockquote><pre>
741 SELECT 1
742 FROM plink JOIN tagxref ON tagxref.rid=plink.cid
743 WHERE tagxref.tagid=$trunk
744 AND plink.pid=$ckid;
745 </pre></blockquote>
746
747 <p>The PLINK table holds parent-child relationships between
748 check-ins. The TAGXREF table maps tags into check-ins.
749 For reference, the relevant portions of the schemas
750 for these two tables is shown here:</p>
751
752 <blockquote><pre>
753 CREATE TABLE plink(
754 pid INTEGER REFERENCES blob,
755 cid INTEGER REFERENCES blob
756 );
757 CREATE UNIQUE INDEX plink_i1 ON plink(pid,cid);
758
759 CREATE TABLE tagxref(
760 tagid INTEGER REFERENCES tag,
761 mtime TIMESTAMP,
762 rid INTEGER REFERENCE blob,
763 UNIQUE(rid, tagid)
764 );
765 CREATE INDEX tagxref_i1 ON tagxref(tagid, mtime);
766 </pre></blockquote>
767
768 <p>There are only two reasonable ways to implement this query.
769 (There are many other possible algorithms, but none of the
770 others are contenders for being the "best" algorithm.)</p>
771
772 <ol type="1">
773 <li value="1"><p>
774 Find all children of check-in $ckid and test each one to see if
775 it has the $trunk tag.
776 </p></li><li value="2"><p>
777 Find all check-ins with the $trunk tag and test each one to see if
778 it is a child of $ckid.
779 </p></li></ol>
780
781 <p>
782 Intuitively, we humans understand that algorithm-1 is best.
783 Each check-in is likely to have few children (one child is
784 the most common case) and each child can be tested for the
785 $trunk tag in logarithmic time. Indeed, algorithm-1 is the
786 faster choice in practice. But the NGQP has no intuition. The
787 NGQP must use hard math, and algorithm-2 is slightly
788 better mathematically. This is because, in the absence of other information,
789 the NGQP must assume that the indexes PLINK_I1 and TAGXREF_I1 are of
790 equal quality and are equally selective. Algorithm-2 uses one field
791 of the TAGXREF_I1 index and both fields of the PLINK_I1 index whereas
792 algorithm-1 only uses the first field of each index. Since
793 algorithm-2 uses more index material, the NGQP is correct
794 to judge it to be the better algorithm. The scores are close and
795 algorithm-2 just barely squeaks ahead of algorithm-1. But
796 algorithm-2 really is the correct choice here.
797 </p>
798
799 <p>
800 Unfortunately, algorithm-2 is slower than algorithm-1 in
801 this application.
802 </p>
803
804 <p>
805 The problem is that the indexes are not of equal quality.
806 A check-in is likely to only have one child. So the first
807 field of PLINK_I1 will usually narrow down the search to just a single
808 row. But there are thousands and thousands check-ins tagged with "trunk",
809 so the first field of TAGXREF_I1 will be
810 of little help in narrowing down the search.
811 </p>
812
813 <p>
814 The NGQP has no way of knowing that TAGXREF_I1 is almost useless in this
815 query, unless <a href="lang_analyze.html">ANALYZE</a> has been run on the database. The <a href="lang_analyze.html">ANALYZE</a> command
816 gathers statistics on the quality of the various indexes and stores those
817 statistics in <a href="fileformat2.html#stat1tab">SQLITE_STAT1</a> table.
818 Having access to this statistical information,
819 the NGQP easily chooses algorithm-1 as the best algorithm, by a wide
820 margin.</p>
821
822 <p>Why didn't the legacy query planner choose algorithm-2?
823 Easy: because the NN algorithm
824 never even considered algorithm-2. Graphs of the planning
825 problem look like this:</p>
826
827 <center>
828 <div style="max-width:523px;"><svg xmlns='http://www.w3.org/2000/svg' class="pikchr" viewBox="0 0 523.232 186.76">
829 <circle cx="55" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
830 <text x="55" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">P</text>
831 <circle cx="157" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
832 <text x="157" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">T</text>
833 <polygon points="129,101 117,101 120,93" style="fill:rgb(0,0,0)"/>
834 <path d="M84,101 L 95,96 Q 106,92 115,95 L 124,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
835 <text x="106" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">4.8</text>
836 <polygon points="84,106 96,106 93,114" style="fill:rgb(0,0,0)"/>
837 <path d="M129,106 L 118,111 Q 106,115 98,112 L 89,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
838 <text x="106" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">4.4</text>
839 <circle cx="55" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
840 <text x="55" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
841 <polygon points="55,75 51,64 60,64" style="fill:rgb(0,0,0)"/>
842 <path d="M55,30L55,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
843 <text x="55" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 4.9</text>
844 <circle cx="157" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
845 <text x="157" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
846 <polygon points="157,75 153,64 162,64" style="fill:rgb(0,0,0)"/>
847 <path d="M157,30L157,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
848 <text x="157" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 5.2</text>
849 <text x="106" y="171" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="125%" dominant-baseline="central">without ANALYZE</text>
850 <circle cx="384" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
851 <text x="384" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">P</text>
852 <circle cx="486" cy="104" r="28.3066" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
853 <text x="486" y="104" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="156.25%" dominant-baseline="central">T</text>
854 <polygon points="457,101 445,101 448,93" style="fill:rgb(0,0,0)"/>
855 <path d="M412,101 L 423,96 Q 435,92 443,95 L 452,99" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
856 <text x="435" y="84" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">4.4</text>
857 <polygon points="412,106 424,106 421,114" style="fill:rgb(0,0,0)"/>
858 <path d="M457,106 L 446,111 Q 435,115 426,112 L 417,108" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
859 <text x="435" y="123" text-anchor="middle" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central">3.8</text>
860 <circle cx="384" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
861 <text x="384" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
862 <polygon points="384,75 379,64 388,64" style="fill:rgb(0,0,0)"/>
863 <path d="M384,30L384,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
864 <text x="384" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 3.9</text>
865 <circle cx="486" cy="16" r="14.1533" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
866 <text x="486" y="16" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" dominant-baseline="central">*</text>
867 <polygon points="486,75 481,64 490,64" style="fill:rgb(0,0,0)"/>
868 <path d="M486,30L486,69" style="fill:none;stroke-width:2.16;stroke:rgb(0,0,0);" />
869 <text x="486" y="53" text-anchor="start" fill="rgb(0,0,0)" font-size="80%" dominant-baseline="central"> 6.1</text>
870 <text x="435" y="171" text-anchor="middle" font-weight="bold" fill="rgb(0,0,0)" font-size="125%" dominant-baseline="central">with ANALYZE</text>
871 </svg>
872 </div>
873 </center>
874
875 <p>
876 In the "without ANALYZE" case on the left, the NN algorithm chooses
877 loop P (PLINK) as the outer loop because 4.9 is less than 5.2, resulting
878 in path P-T which is algorithm-1. NN only looks at the single best choice
879 at each step so it completely misses the fact that
880 5.2+4.4 makes a slightly cheaper plan than 4.9+4.8. But the N3 algorithm
881 keeps track of the 5 best paths for a 2-way join, so it ends up
882 selecting path T-P because of its slightly lower overall cost.
883 Path T-P is algorithm-2.
884 </p>
885
886 <p>
887 Note that with ANALYZE the cost estimates are
888 better aligned with reality and algorithm-1 is
889 selected by both NN and N3.
890 </p>
891
892 <p>(Side note: The costs estimates in the two most recent graphs
893 were computed by the NGQP using a base-2 logarithm and slightly different
894 cost assumptions compared to the legacy query planner.
895 Hence, the cost estimates in
896 these latter two graphs are not directly comparable to the cost estimates
897 in the TPC-H Q8 graph.)</p>
898
899 <h2 id="_fixing_the_problem"><span>4.2. </span> Fixing The Problem</h2>
900
901 <p>Running <a href="lang_analyze.html">ANALYZE</a> on the repository database immediately fixed the
902 performance problem. However, we want Fossil to be robust and to always
903 work quickly regardless of whether or not its repository has been analyzed.
904 For this reason, the query was modified to use the CROSS JOIN operator
905 instead of the plain JOIN operator.
906 SQLite will not reorder the tables of a CROSS JOIN.
907 This is a long-standing feature of SQLite that is specifically designed
908 to allow knowledgeable programmers
909 to enforce a particular loop nesting order. Once the join
910 was changed to CROSS JOIN (the addition of a single keyword) the NGQP was
911 forced to choose the faster algorithm-1 regardless of whether or not
912 statistical information had been gathered using ANALYZE.</p>
913
914 <p>We say that algorithm-1 is "faster", but this
915 is not strictly true. Algorithm-1 is faster in common repositories, but
916 it is possible to construct a repository in which
917 every check-in is on a different uniquely-named branch and
918 all check-ins are children of the root check-in.
919 In that case, TAGXREF_I1 would become more selective
920 than PLINK_I1 and algorithm-2 really would be the faster choice.
921 However such repositories are very unlikely to appear in
922 practice and so hard-coding the loop nested order using the
923 CROSS JOIN syntax is a reasonable solution
924 to the problem in this case.</p>
925
926 <h2 id="update_2017_a_better_fix"><span>4.3. </span>Update 2017: A Better Fix</h2>
927
928 <p>The prior text was written in early 2013, before the first release of
929 SQLite version 3.8.0. This paragraph was added in mid 2021.
930 While all of the previous discussion remains true, a lot of improvements
931 have been made to the query planner, making this whole section largely moot.
932
933 </p><p>In 2017, Fossil was enhanced to make use of the new
934 <a href="pragma.html#pragma_optimize">PRAGMA optimize</a> statement. Whenever Fossil is about to close the
935 database connection to its repository, it first runs
936 "PRAGMA optimize", which will in turn cause ANALYZE to be run if it
937 is needed. Usually an ANALYZE is not needed, and so there is no
938 measurable performance penalty for doing this. But every now and
939 then ANALYZE might be run on a few of the tables in the repository
940 database. Because if this, query planning issues such as the one
941 described here no longer come up in Fossil. The fact that ANALYZE
942 is run periodically to keep the <a href="fileformat2.html#stat1tab">sqlite_stat1</a> table up-to-date means
943 that hand-tuning of queries is no longer required. We have not had
944 to tweak a query in Fossil in ages.
945
946 </p><p>Therefore, the current recommendation for avoiding problems such
947 as this one is to simply run "PRAGMA optimize" just prior to closing
948 each database connection. Or, if your application is long-running and
949 never closes any database connections, then run "PRAGMA optimize" once
950 per day or so. Also consider running "PRAGMA optimize" after any
951 schema change.
952
953 <a name="howtofix"></a>
954
955 </p><h1 id="_checklist_for_avoiding_or_fixing_query_planner_problems"><span>5. </span> Checklist For Avoiding Or Fixing Query Planner Problems</h1>
956
957 <ol>
958 <li><p><b>Don't panic!</b>
959 Cases where the query planner picks an inferior plan are actually quite
960 rare. You are unlikely to run across any problems in your application.
961 If you are not having performance issues, you do not need to worry
962 about any of this.</p>
963
964 </li><li><p><b>Create appropriate indexes.</b>
965 Most SQL performance problems arise not because of query planner issues
966 but rather due to lack of appropriate indexes. Make sure indexes are
967 available to assist all large queries. Most performance issues can be
968 resolved by one or two CREATE INDEX commands and with no changes to
969 application code.</p>
970
971 </li><li><p><b>Avoid creating low-quality indexes.</b>.
972 A low-quality index (for the purpose of this checklist) is one where
973 there are more than 10 or 20 rows in the table that have the same value
974 for the left-most column of the index. In particular, avoid using
975 boolean or "enum" columns as the left-most columns of your indexes.</p>
976
977 <p>The Fossil performance problem described in the previous section of
978 this document arose because there were over
979 ten-thousand entries in the TAGXREF table with the same value for the
980 left-most column (the TAGID column) of the TAGXREF_I1 index.</p>
981
982 </li><li><p><b>If you must use a low-quality index, be sure to run <a href="lang_analyze.html">ANALYZE</a>.</b>
983 Low-quality indexes will not confuse the query planner as long as the
984 query planner knows that the indexes are of low quality. And the way
985 the query planner knows this is by the content of the <a href="fileformat2.html#stat1tab">SQLITE_STAT1</a> table,
986 which is computed by the ANALYZE command.</p>
987
988 <p>Of course, ANALYZE only works effectively if you have a significant
989 amount of content in your database in the first place. When creating a
990 new database that you expect to accumulate a lot of data, you can run
991 the command "ANALYZE sqlite_schema" to create the SQLITE_STAT1 table,
992 then prepopulate the <a href="fileformat2.html#stat1tab">sqlite_stat1</a> table (using ordinary INSERT statements)
993 with content that describes a typical
994 database for your application - perhaps content that you extracted after
995 running ANALYZE on a well-populated template database in the lab.
996 Or, you could just run "<a href="pragma.html#pragma_optimize">PRAGMA optimize</a>" before shutting down
997 database connections so that ANALYZE will be run automatically as
998 needed to keep the <a href="fileformat2.html#stat1tab">sqlite_stat1</a> table current.</p></li>
999
1000 <li><p><b>Instrument your code.</b>
1001 Add logic that lets you know quickly and easily which queries are taking
1002 too much time. Then work on just those specific queries.</p>
1003
1004 <p>
1005 </p><hr>
1006 <i>Update 2024: The query planner has been improved so much over
1007 the years that you should never need to use any of the
1008 hacks described below. The capabilities described below are still
1009 available, for backwards compatibility. But you shouldn't use
1010 them. If you do find a case where you are getting a suboptimal query
1011 plan, please report it to the SQLite developers on the
1012 <a href="https://sqlite.org/forum">SQLite Forum</a> so that they can try to fix
1013 the problem. In other words:
1014 <p>
1015 </p><center><b>Stop Reading Here!</b></center>
1016 <p>To help encourage you to stop reading, the remainder of this checklist
1017 is now grayed out.
1018 </p><hr>
1019
1020 </i></li><li><p style="color:grey;">Use <a href="lang_corefunc.html#unlikely">unlikely()</a> and <a href="lang_corefunc.html#likelihood">likelihood()</a> SQL functions.
1021 SQLite normally assumes that terms in the WHERE clause that cannot be used
1022 by indexes have a strong probability of being true. If this assumption
1023 is incorrect, it could lead to a suboptimal query plan. The
1024 <a href="lang_corefunc.html#unlikely">unlikely()</a> and <a href="lang_corefunc.html#likelihood">likelihood()</a> SQL functions can be used to provide
1025 hints to the query planner about WHERE clause terms that are probably
1026 not true, and thus aid the query planner in selecting the best possible
1027 plan.
1028
1029 </p></li><li><p style="color:grey;">Use the <a href="optoverview.html#crossjoin">CROSS JOIN</a> syntax to enforce a particular
1030 loop nesting order on queries that might use low-quality indexes in an
1031 unanalyzed database.
1032 SQLite <a href="lang_select.html#crossjoin">treats the CROSS JOIN operator specially</a>, forcing the table to
1033 the left to be an outer loop relative to the table on the right.</p>
1034
1035 </li><li><p style="color:grey;">Use unary "+" operators to disqualify WHERE clause terms.
1036 If the query planner insists on selecting a poor-quality index for a particular
1037 query when a much higher-quality index is available, then
1038 <a href="optoverview.html#uplus">careful use of unary "+" operators</a> in the WHERE clause
1039 can force the query planner away from the poor-quality index.
1040 Avoid using this trick if at all possible, and especially avoid it
1041 early in the application development cycle. Beware that
1042 adding a unary "+" operator to an equality expression might change
1043 the result of that expression if
1044 <a href="datatype3.html#affinity">type affinity</a> is involved.</p>
1045
1046 </li><li><p style="color:grey;">Use the <a href="lang_indexedby.html">INDEXED BY</a> syntax to enforce the selection of
1047 particular indexes on problem queries.
1048 As with the previous two bullets, avoid this step if possible, and
1049 especially avoid doing this early in development as it is clearly a
1050 premature optimization.</p>
1051 </li></ol>
1052
1053 <h1 id="_summary"><span>6. </span> Summary</h1>
1054
1055 <p>The query planner in SQLite normally does a terrific job of selecting
1056 fast algorithms for running your SQL statements. This is true of the
1057 legacy query planner and even more true of the new NGQP. There may be
1058 an occasional situation where, due to incomplete information, the query
1059 planner selects a suboptimal plan. This will happen less often with the
1060 NGQP than with the legacy query planner, but it might still happen. Only
1061 in those rare cases do application developers need to get involved and
1062 help the query planner to do the right thing. In the common case, the
1063 NGQP is just a new enhancement to SQLite that makes the application run
1064 a little faster and which requires no new developer thought or action.</p>
1065
1066