Debian Codegraph @

www/queryplanner.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>Query Planning</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 Query Planning
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="#_searching">1. Searching</a></div>
129 <div class="fancy-toc2"><a href="#_tables_without_indices">1.1. Tables Without Indices</a></div>
130 <div class="fancy-toc2"><a href="#_lookup_by_rowid">1.2. Lookup By Rowid</a></div>
131 <div class="fancy-toc2"><a href="#_lookup_by_index">1.3. Lookup By Index</a></div>
132 <div class="fancy-toc2"><a href="#_multiple_result_rows">1.4. Multiple Result Rows</a></div>
133 <div class="fancy-toc2"><a href="#_multiple_and_connected_where_clause_terms">1.5. Multiple AND-Connected WHERE-Clause Terms</a></div>
134 <div class="fancy-toc2"><a href="#_multi_column_indices">1.6. Multi-Column Indices</a></div>
135 <div class="fancy-toc2"><a href="#_covering_indexes">1.7. Covering Indexes</a></div>
136 <div class="fancy-toc2"><a href="#_or_connected_terms_in_the_where_clause">1.8. OR-Connected Terms In The WHERE Clause</a></div>
137 <div class="fancy-toc1"><a href="#_sorting">2. Sorting</a></div>
138 <div class="fancy-toc2"><a href="#_sorting_by_rowid">2.1. Sorting By Rowid</a></div>
139 <div class="fancy-toc2"><a href="#_sorting_by_index">2.2. Sorting By Index</a></div>
140 <div class="fancy-toc2"><a href="#_sorting_by_covering_index">2.3. Sorting By Covering Index</a></div>
141 <div class="fancy-toc1"><a href="#_searching_and_sorting_at_the_same_time">3. Searching And Sorting At The Same Time</a></div>
142 <div class="fancy-toc2"><a href="#_searching_and_sorting_with_a_multi_column_index">3.1. Searching And Sorting With A Multi-Column Index</a></div>
143 <div class="fancy-toc2"><a href="#_searching_and_sorting_with_a_covering_index">3.2. Searching And Sorting With A Covering Index</a></div>
144 <div class="fancy-toc2"><a href="#_partial_sorting_using_an_index_a_k_a_block_sorting_">3.3. Partial Sorting Using An Index (a.k.a. Block Sorting)</a></div>
145 <div class="fancy-toc1"><a href="#_without_rowid_tables">4. WITHOUT ROWID tables</a></div>
146 </div>
147 </div>
148 <script>
149 function toggle_toc(){
150 var sub = document.getElementById("toc_sub")
151 var mk = document.getElementById("toc_mk")
152 if( sub.style.display!="block" ){
153 sub.style.display = "block";
154 mk.innerHTML = "&#x25bc;";
155 } else {
156 sub.style.display = "none";
157 mk.innerHTML = "&#x25ba;";
158 }
159 }
160 </script>
161 </div>
162
163
164
165
166
167
168 <h2 style="margin-left:1.0em" notoc="1" id="overview"> Overview</h2>
169
170 <p>
171 The best feature of SQL (in <u>all</u> its implementations, not just SQLite)
172 is that it is a <i>declarative</i> language, not a <i>procedural</i>
173 language. When programming in SQL you tell the system <i>what</i> you
174 want to compute, not <i>how</i> to compute it. The task of figuring out
175 the <i>how</i> is delegated to the <i>query planner</i> subsystem within
176 the SQL database engine.</p>
177
178 <p>For any given SQL statement, there might be hundreds or thousands or
179 even millions of different algorithms of performing the operation. All
180 of these algorithms will get the correct answer, though some will run
181 faster than others.
182 The query planner is an
183 <a href="https://en.wikipedia.org/wiki/Artificial_intelligence">AI</a> that
184 tries to pick the fastest and most efficient algorithm for each SQL
185 statement.
186 </p>
187
188 <p>
189 Most of the time, the query planner in SQLite does a good job.
190 However, the query planner needs indices to
191 work with.
192 These indices must normally be added by programmers.
193 Rarely, the query planner AI will make a suboptimal algorithm
194 choice.
195 In those cases, programmers may want to provide additional
196 hints to help the query planner do a better job.
197 </p>
198
199 <p>
200 This document provides background information about how the
201 SQLite query planner and query engine work.
202 Programmers can use this information to help create better
203 indexes, and provide hints to help the query planner when
204 needed.
205 </p>
206
207 <p>
208 Additional information is provided in the
209 <a href="optoverview.html">SQLite query planner</a> and
210 <a href="queryplanner-ng.html">next generation query planner</a> documents.
211 </p>
212
213 <a name="searching"></a>
214
215 <h1 id="_searching"><span>1. </span> Searching</h1>
216
217 <h2 id="_tables_without_indices"><span>1.1. </span> Tables Without Indices</h2>
218
219 <p>
220 Most tables in SQLite consist of zero or more rows with a unique integer
221 key (the <a href="lang_createtable.html#rowid">rowid</a> or <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a>) followed by content.
222 (The exception is <a href="withoutrowid.html">WITHOUT ROWID</a> tables.)
223 The rows
224 are logically stored in order of increasing rowid. As an example, this
225 article uses a table named "FruitsForSale" which relates various fruits
226 to the state
227 where they are grown and their unit price at market. The schema is this:
228 </p>
229
230 <center><table><tr><td><pre>
231 CREATE TABLE FruitsForSale(
232 Fruit TEXT,
233 State TEXT,
234 Price REAL
235 );
236 </pre></table></center>
237
238
239 <p>
240 With some (arbitrary) data, such a table might be logically stored on disk
241 as shown in figure 1:
242 </p>
243
244 <a name='fig1'></a>
245 <p><center>
246 <img src="images/qp/tab.gif" alt="figure 1"><br>
247 Figure 1: Logical Layout Of Table "FruitsForSale"
248 </center></p>
249
250
251 <p>
252 In this example, the rowids are not
253 consecutive but they are ordered. SQLite usually creates rowids beginning
254 with one and increasing by one with each added row. But if rows are
255 deleted, gaps can appear in the sequence. And the application can control
256 the rowid assigned if desired, so that rows are not necessarily inserted
257 at the bottom. But regardless of what happens, the rowids are always
258 unique and in strictly ascending order.
259 </p>
260
261 <p>
262 Suppose you want to look up the price of peaches. The query would
263 be as follows:
264 </p>
265
266 <center><table><tr><td><pre>
267 SELECT price FROM fruitsforsale WHERE fruit='Peach';
268 </pre></table></center>
269
270
271 <p>
272 To satisfy this query, SQLite reads every row out of the
273 table, checks to see if the "fruit" column has the value of "Peach" and if
274 so, outputs the "price" column from that row. The process is illustrated
275 by <a href="#fig2">figure 2</a> below.
276 This is algorithm is called a <i>full table scan</i>
277 since the entire content of the
278 table must be read and examined in order to find the one row of interest.
279 With a table of only 7 rows, a full table scan is acceptable,
280 but if the table contained 7 million rows, a full table scan might read
281 megabytes of content in order to find a single 8-byte number.
282 For that reason, one normally tries to avoid full table scans.
283 </p>
284
285 <a name='fig2'></a>
286 <p><center>
287 <img src="images/qp/fullscan.gif" alt="figure 2"><br>
288 Figure 2: Full Table Scan
289 </center></p>
290
291
292 <h2 id="_lookup_by_rowid"><span>1.2. </span> Lookup By Rowid</h2>
293
294 <p>
295 One technique for avoiding a full table scan is to do lookups by
296 rowid (or by the equivalent <a href="lang_createtable.html#rowid">INTEGER PRIMARY KEY</a>). To lookup the
297 price of peaches, one would query for the entry with a rowid of 4:
298 </p>
299
300 <center><table><tr><td><pre>
301 SELECT price FROM fruitsforsale WHERE rowid=4;
302 </pre></table></center>
303
304
305 <p>
306 Since the information is stored in the table in rowid order, SQLite
307 can find the correct row using a binary search.
308 If the table contains N elements, the time required to look up the
309 desired row is proportional to logN rather than being proportional
310 to N as in a full table scan. If the table contains 10 million elements,
311 that means the query will be on the order of N/logN or about 1 million
312 times faster.
313 </p>
314
315 <a name='fig3'></a>
316 <p><center>
317 <img src="images/qp/rowidlu.gif" alt="figure 3"><br>
318 Figure 3: Lookup By Rowid
319 </center></p>
320
321
322 <h2 id="_lookup_by_index"><span>1.3. </span> Lookup By Index</h2>
323 <p>
324 The problem with looking up information by rowid is that you probably
325 do not care what the price of "item 4" is - you want to know the price
326 of peaches. And so a rowid lookup is not helpful.
327 </p>
328
329 <p>
330 To make the original query more efficient, we can add an index on the
331 "fruit" column of the "fruitsforsale" table like this:
332 </p>
333
334 <center><table><tr><td><pre>
335 CREATE INDEX Idx1 ON fruitsforsale(fruit);
336 </pre></table></center>
337
338
339 <p>
340 An index is another table similar to the original "fruitsforsale" table
341 but with the content (the fruit column in this case) stored in front of the
342 rowid and with all rows in content order.
343 <a href="#fig4">Figure 4</a> gives a logical view of the Idx1 index.
344 The "fruit" column is the primary key used to order the elements of the
345 table and the "rowid" is the secondary key used to break the tie when
346 two or more rows have the same "fruit". In the example, the rowid
347 has to be used as a tie-breaker for the "Orange" rows.
348 Notice that since the rowid
349 is always unique over all elements of the original table, the composite key
350 of "fruit" followed by "rowid" will be unique over all elements of the index.
351 </p>
352
353 <a name='fig4'></a>
354 <p><center>
355 <img src="images/qp/idx1.gif" alt="figure 4"><br>
356 Figure 4: An Index On The Fruit Column
357 </center></p>
358
359
360 <p>
361 This new index can be used to implement a faster algorithm for the
362 original "Price of Peaches" query.
363 </p>
364
365 <center><table><tr><td><pre>
366 SELECT price FROM fruitsforsale WHERE fruit='Peach';
367 </pre></table></center>
368
369
370 <p>
371 The query starts by doing a binary search on the Idx1 index for entries
372 that have fruit='Peach'. SQLite can do this binary search on the Idx1 index
373 but not on the original FruitsForSale table because the rows in Idx1 are sorted
374 by the "fruit" column. Having found a row in the Idx1 index that has
375 fruit='Peach', the database engine can extract the rowid for that row.
376 Then the database engines does a second binary search
377 on the original FruitsForSale table to find the
378 original row that contains fruit='Peach'.
379 From the row in the FruitsForSale table,
380 SQLite can then extract the value of the price column.
381 This procedure is illustrated by <a href="#fig5">figure 5</a>.
382 </p>
383
384 <a name='fig5'></a>
385 <p><center>
386 <img src="images/qp/idx1lu1.gif" alt="figure 5"><br>
387 Figure 5: Indexed Lookup For The Price Of Peaches
388 </center></p>
389
390
391 <p>
392 SQLite has to do two binary searches to find the price of peaches using
393 the method show above. But for a table with a large number of rows, this
394 is still much faster than doing a full table scan.
395 </p>
396
397 <h2 id="_multiple_result_rows"><span>1.4. </span> Multiple Result Rows</h2>
398
399 <p>
400 In the previous query the fruit='Peach' constraint narrowed the result
401 down to a single row. But the same technique works even if multiple
402 rows are obtained. Suppose we looked up the price of Oranges instead of
403 Peaches:
404 </p>
405
406 <center><table><tr><td><pre>
407 SELECT price FROM fruitsforsale WHERE fruit='Orange'
408 </pre></table></center>
409 <a name='fig6'></a>
410 <p><center>
411 <img src="images/qp/idx1lu2.gif" alt="figure 6"><br>
412 Figure 6: Indexed Lookup For The Price Of Oranges
413 </center></p>
414
415
416 <p>
417 In this case, SQLite still does a single binary search to find the first
418 entry of the index where fruit='Orange'. Then it extracts the rowid from
419 the index and uses that rowid to lookup the original table entry via
420 binary search and output the price from the original table. But instead
421 of quitting, the database engine then advances to the next row of index
422 to repeat the process for next fruit='Orange' entry. Advancing to the
423 next row of an index (or table) is much less costly than doing a binary
424 search since the next row is often located on the same database page as
425 the current row. In fact, the cost of advancing to the next row is so
426 cheap in comparison to a binary search that we usually ignore it. So
427 our estimate for the total cost of this query is 3 binary searches.
428 If the number of rows of output is K and the number of rows in the table
429 is N, then in general the cost of doing the query is proportional
430 to (K+1)*logN.
431 </p>
432
433 <h2 id="_multiple_and_connected_where_clause_terms"><span>1.5. </span> Multiple AND-Connected WHERE-Clause Terms</h2>
434
435 <p>
436 Next, suppose that you want to look up the price of not just any orange,
437 but specifically California-grown oranges. The appropriate query would
438 be as follows:
439 </p>
440
441 <center><table><tr><td><pre>
442 SELECT price FROM fruitsforsale WHERE fruit='Orange' AND state='CA'
443 </pre></table></center>
444 <a name='fig7'></a>
445 <p><center>
446 <img src="images/qp/idx1lu3.gif" alt="figure 7"><br>
447 Figure 7: Indexed Lookup Of California Oranges
448 </center></p>
449
450
451 <p>
452 One approach to this query is to use the fruit='Orange' term of the WHERE
453 clause to find all rows dealing with oranges, then filter those rows
454 by rejecting any that are from states other than California. This
455 process is shown by <a href="#fig7">figure 7</a> above. This is a perfectly
456 reasonable approach in most cases. Yes, the database engine did have
457 to do an extra binary search for the Florida orange row that was
458 later rejected, so it was not as efficient as we might hope, though
459 for many applications it is efficient enough.
460 </p>
461
462 <p>
463 Suppose that in addition to the index on "fruit" there was also
464 an index on "state".
465 </p>
466
467 <center><table><tr><td><pre>
468 CREATE INDEX Idx2 ON fruitsforsale(state);
469 </pre></table></center>
470 <a name='fig8'></a>
471 <p><center>
472 <img src="images/qp/idx2.gif" alt="figure 8"><br>
473 Figure 8: Index On The State Column
474 </center></p>
475
476
477 <p>
478 The "state" index works just like the "fruit" index in that it is a
479 new table with an extra column in front of the rowid and sorted by
480 that extra column as the primary key. The only difference is that
481 in Idx2, the first column is "state" instead of "fruit" as it is with
482 Idx1. In our example data set, there is more redundancy in the "state"
483 column and so they are more duplicate entries. The ties are still
484 resolved using the rowid.
485 </p>
486
487 <p>
488 Using the new Idx2 index on "state", SQLite has another option for
489 lookup up the price of California oranges: it can look up every row
490 that contains fruit from California and filter out those rows that
491 are not oranges.
492 </p>
493
494 <a name='fig9'></a>
495 <p><center>
496 <img src="images/qp/idx2lu1.gif" alt="figure 9"><br>
497 Figure 9: Indexed Lookup Of California Oranges
498 </center></p>
499
500
501 <p>
502 Using Idx2 instead of Idx1 causes SQLite to examine a different set of
503 rows, but it gets the same answer in the end (which is very important -
504 remember that indices should never change the answer, only help SQLite to
505 get to the answer more quickly) and it does the same amount of work.
506 So the Idx2 index did not help performance in this case.
507 </p>
508
509 <p>
510 The last two queries take the same amount of time, in our example.
511 So which index, Idx1 or Idx2, will SQLite choose? If the
512 <a href="lang_analyze.html">ANALYZE</a> command has been run on the database, so that SQLite has
513 had an opportunity to gather statistics about the available indices,
514 then SQLite will know that the Idx1 index usually narrows the search
515 down to a single item (our example of fruit='Orange' is the exception
516 to this rule) whereas the Idx2 index will normally only narrow the
517 search down to two rows. So, if all else is equal, SQLite will
518 choose Idx1 with the hope of narrowing the search to as small
519 a number of rows as possible. This choice is only possible because
520 of the statistics provided by <a href="lang_analyze.html">ANALYZE</a>. If <a href="lang_analyze.html">ANALYZE</a> has not been
521 run then the choice of which index to use is arbitrary.
522 </p>
523
524 <h2 id="_multi_column_indices"><span>1.6. </span> Multi-Column Indices</h2>
525
526 <p>
527 To get the maximum performance out of a query with multiple AND-connected
528 terms in the WHERE clause, you really want a multi-column index with
529 columns for each of the AND terms. In this case we create a new index
530 on the "fruit" and "state" columns of FruitsForSale:
531 </p>
532
533 <center><table><tr><td><pre>
534 CREATE INDEX Idx3 ON FruitsForSale(fruit, state);
535 </pre></table></center>
536 <a name='fig10'></a>
537 <p><center>
538 <img src="images/qp/idx3.gif" alt="figure 1"><br>
539 Figure 1: A Two-Column Index
540 </center></p>
541
542
543 <p>
544 A multi-column index follows the same pattern as a single-column index;
545 the indexed columns are added in front of the rowid. The only difference
546 is that now multiple columns are added. The left-most column is the
547 primary key used for ordering the rows in the index. The second column is
548 used to break ties in the left-most column. If there were a third column,
549 it would be used to break ties for the first two columns. And so forth for
550 all columns in the index. Because rowid is guaranteed
551 to be unique, every row of the index will be unique even if all of the
552 content columns for two rows are the same. That case does not happen
553 in our sample data, but there is one case (fruit='Orange') where there
554 is a tie on the first column which must be broken by the second column.
555 </p>
556
557 <p>
558 Given the new multi-column Idx3 index, it is now possible for SQLite
559 to find the price of California oranges using only 2 binary searches:
560 </p>
561
562 <center><table><tr><td><pre>
563 SELECT price FROM fruitsforsale WHERE fruit='Orange' AND state='CA'
564 </pre></table></center>
565 <a name='fig11'></a>
566 <p><center>
567 <img src="images/qp/idx3lu1.gif" alt="figure 11"><br>
568 Figure 11: Lookup Using A Two-Column Index
569 </center></p>
570
571
572 <p>
573 With the Idx3 index on both columns that are constrained by the WHERE clause,
574 SQLite can do a single binary search against Idx3 to find the one rowid
575 for California oranges, then do a single binary search to find the price
576 for that item in the original table. There are no dead-ends and no
577 wasted binary searches. This is a more efficient query.
578 </p>
579
580 <p>
581 Note that Idx3 contains all the same information as the original
582 <a href="#fig3">Idx1</a>. And so if we have Idx3, we do not really need Idx1
583 any more. The "price of peaches" query can be satisfied using Idx3
584 by simply ignoring the "state" column of Idx3:
585 </p>
586
587 <center><table><tr><td><pre>
588 SELECT price FROM fruitsforsale WHERE fruit='Peach'
589 </pre></table></center>
590 <a name='fig12'></a>
591 <p><center>
592 <img src="images/qp/idx3lu2.gif" alt="figure 12"><br>
593 Figure 12: Single-Column Lookup On A Multi-Column Index
594 </center></p>
595
596
597 <p>
598 Hence, a good rule of thumb is that your database schema should never
599 contain two indices where one index is a prefix of the other. Drop the
600 index with fewer columns. SQLite will still be able to do efficient
601 lookups with the longer index.
602 </p>
603
604 <a name="covidx"></a>
605
606 <h2 id="_covering_indexes"><span>1.7. </span> Covering Indexes</h2>
607
608 <p>
609 The "price of California oranges" query was made more efficient through
610 the use of a two-column index. But SQLite can do even better with a
611 three-column index that also includes the "price" column:
612 </p>
613
614 <center><table><tr><td><pre>
615 CREATE INDEX Idx4 ON FruitsForSale(fruit, state, price);
616 </pre></table></center>
617 <a name='fig13'></a>
618 <p><center>
619 <img src="images/qp/idx4.gif" alt="figure 13"><br>
620 Figure 13: A Covering Index
621 </center></p>
622
623
624 <p>
625 This new index contains all the columns of the original FruitsForSale table that
626 are used by the query - both the search terms and the output. We call
627 this a "covering index". Because all of the information needed is in
628 the covering index, SQLite never needs to consult the original table
629 in order to find the price.
630 </p>
631
632 <center><table><tr><td><pre>
633 SELECT price FROM fruitsforsale WHERE fruit='Orange' AND state='CA';
634 </pre></table></center>
635 <a name='fig14'></a>
636 <p><center>
637 <img src="images/qp/idx4lu1.gif" alt="figure 14"><br>
638 Figure 14: Query Using A Covering Index
639 </center></p>
640
641
642 <p>
643 Hence, by adding extra "output" columns onto the end of an index, one
644 can avoid having to reference the original table and thereby
645 cut the number of binary searches for a query in half. This is a
646 constant-factor improvement in performance (roughly a doubling of
647 the speed). But on the other hand, it is also just a refinement;
648 A two-fold performance increase is not nearly as dramatic as the
649 one-million-fold increase seen when the table was first indexed.
650 And for most queries, the difference between 1 microsecond and
651 2 microseconds is unlikely to be noticed.
652 </p>
653
654 <a name="or_in_where"></a>
655
656 <h2 id="_or_connected_terms_in_the_where_clause"><span>1.8. </span> OR-Connected Terms In The WHERE Clause</h2>
657
658 <p>
659 Multi-column indices only work if the constraint terms in the WHERE
660 clause of the query are connected by AND.
661 So Idx3 and Idx4 are helpful when the search is for items that
662 are both Oranges and grown in California, but neither index would
663 be that useful if we wanted all items that were either oranges
664 <i>or</i> are grown in California.
665 </p>
666
667 <center><table><tr><td><pre>
668 SELECT price FROM FruitsForSale WHERE fruit='Orange' OR state='CA';
669 </pre></table></center>
670
671
672 <p>
673 When confronted with OR-connected terms in a WHERE clause, SQLite
674 examines each OR term separately and tries to use an index to
675 find the rowids associated with each term.
676 It then takes the union of the resulting rowid sets to find
677 the end result. The following figure illustrates this process:
678 </p>
679
680 <a name='fig15'></a>
681 <p><center>
682 <img src="images/qp/orquery.gif" alt="figure 15"><br>
683 Figure 15: Query With OR Constraints
684 </center></p>
685
686
687 <p>
688 The diagram above implies that SQLite computes all of the rowids first
689 and then combines them with a union operation before starting to do
690 rowid lookups on the original table. In reality, the rowid lookups
691 are interspersed with rowid computations. SQLite uses one index at
692 a time to find rowids while remembering which rowids it has seen
693 before so as to avoid duplicates. That is just an implementation
694 detail, though. The diagram, while not 100% accurate, provides a good
695 overview of what is happening.
696 </p>
697
698 <p>
699 In order for the OR-by-UNION technique shown above to be useful, there
700 must be an index available that helps resolve every OR-connected term
701 in the WHERE clause. If even a single OR-connected term is not indexed,
702 then a full table scan would have to be done in order to find the rowids
703 generated by the one term, and if SQLite has to do a full table scan, it
704 might as well do it on the original table and get all of the results in
705 a single pass without having to mess with union operations and follow-on
706 binary searches.
707 </p>
708
709 <p>
710 One can see how the OR-by-UNION technique could also be leveraged to
711 use multiple indices on queries where the WHERE clause has terms connected
712 by AND, by using an intersect operator in place of union. Many SQL
713 database engines will do just that. But the performance gain over using
714 just a single index is slight and so SQLite does not implement that technique
715 at this time. However, a future version SQLite might be enhanced to support
716 AND-by-INTERSECT.
717 </p>
718
719 <a name="sorting"></a>
720
721 <h1 id="_sorting"><span>2. </span> Sorting</h1>
722
723 <p>
724 SQLite (like all other SQL database engines) can also use indices to
725 satisfy the ORDER BY clauses in a query, in addition to expediting
726 lookup. In other words, indices can be used to speed up sorting as
727 well as searching.
728 </p>
729
730 <p>
731 When no appropriate indices are available, a query with an ORDER BY
732 clause must be sorted as a separate step. Consider this query:
733 </p>
734
735 <center><table><tr><td><pre>
736 SELECT * FROM fruitsforsale ORDER BY fruit;
737 </pre></table></center>
738
739
740 <p>
741 SQLite processes this by gathering all the output of query and then
742 running that output through a sorter.
743 </p>
744
745 <a name='fig16'></a>
746 <p><center>
747 <img src="images/qp/obfruitnoidx.gif" alt="figure 16"><br>
748 Figure 16: Sorting Without An Index
749 </center></p>
750
751
752 <p>
753 If the number of output rows is K, then the time needed to sort is
754 proportional to KlogK. If K is small, the sorting time is usually
755 not a factor, but in a query such as the above where K==N, the time
756 needed to sort can be much greater than the time needed to do a
757 full table scan. Furthermore, the entire output is accumulated in
758 temporary storage (which might be either in main memory or on disk,
759 depending on various compile-time and run-time settings)
760 which can mean that a lot of temporary storage is required to complete
761 the query.
762 </p>
763
764 <h2 id="_sorting_by_rowid"><span>2.1. </span> Sorting By Rowid</h2>
765
766 <p>
767 Because sorting can be expensive, SQLite works hard to convert ORDER BY
768 clauses into no-ops. If SQLite determines that output will
769 naturally appear in the order specified, then no sorting is done.
770 So, for example, if you request the output in rowid order, no sorting
771 will be done:
772 </p>
773
774 <center><table><tr><td><pre>
775 SELECT * FROM fruitsforsale ORDER BY rowid;
776 </pre></table></center>
777 <a name='fig17'></a>
778 <p><center>
779 <img src="images/qp/obrowid.gif" alt="figure 17"><br>
780 Figure 17: Sorting By Rowid
781 </center></p>
782
783
784 <p>
785 You can also request a reverse-order sort like this:
786 </p>
787
788 <center><table><tr><td><pre>
789 SELECT * FROM fruitsforsale ORDER BY rowid DESC;
790 </pre></table></center>
791
792
793 <p>
794 SQLite will still omit the sorting step. But in order for output to
795 appear in the correct order, SQLite will do the table scan starting at
796 the end and working toward the beginning, rather than starting at the
797 beginning and working toward the end as shown in
798 <a href="#fig17">figure 17</a>.
799 </p>
800
801 <h2 id="_sorting_by_index"><span>2.2. </span> Sorting By Index</h2>
802
803 <p>
804 Of course, ordering the output of a query by rowid is seldom useful.
805 Usually one wants to order the output by some other column.
806 </p>
807
808 <p>
809 If an index is available on the ORDER BY column, that index can be used
810 for sorting. Consider the request for all items sorted by "fruit":
811 </p>
812
813 <center><table><tr><td><pre>
814 SELECT * FROM fruitsforsale ORDER BY fruit;
815 </pre></table></center>
816
817
818 <a name='fig18'></a>
819 <p><center>
820 <img src="images/qp/obfruitidx1.gif" alt="figure 18"><br>
821 Figure 18: Sorting With An Index
822 </center></p>
823
824
825 <p>
826 The Idx1 index is scanned from top to bottom (or from bottom to top if
827 "ORDER BY fruit DESC" is used) in order to find the rowids for each item
828 in order by fruit. Then for each rowid, a binary search is done to lookup
829 and output that row. In this way, the output appears in the requested order
830 without the need to gather the entire output and sort it using a separate step.
831 </p>
832
833 <p>
834 But does this really save time? The number of steps in the
835 <a href="#fig16">original indexless sort</a> is proportional to NlogN since
836 that is how much time it takes to sort N rows. But when we use Idx1 as
837 shown here, we have to do N rowid lookups which take logN time each, so
838 the total time of NlogN is the same!
839 </p>
840
841 <p>
842 SQLite uses a cost-based query planner. When there are two or more ways
843 of solving the same query, SQLite tries to estimate the total amount of
844 time needed to run the query using each plan, and then uses the plan with
845 the lowest estimated cost. A cost is computed mostly from the estimated
846 time, and so this case could go either way depending on the table size and
847 what WHERE clause constraints were available, and so forth. But generally
848 speaking, the indexed sort would probably be chosen, if for no other
849 reason, because it does not need to accumulate the entire result set in
850 temporary storage before sorting and thus uses much less temporary storage.
851 </p>
852
853 <h2 id="_sorting_by_covering_index"><span>2.3. </span> Sorting By Covering Index</h2>
854
855 <p>
856 If a covering index can be used for a query, then the multiple rowid lookups
857 can be avoided and the cost of the query drops dramatically.
858 </p>
859
860 <a name='fig19'></a>
861 <p><center>
862 <img src="images/qp/obfruitidx4.gif" alt="figure 19"><br>
863 Figure 19: Sorting With A Covering Index
864 </center></p>
865
866
867 <p>
868 With a covering index, SQLite can simply walk the index from one end to the
869 other and deliver the output in time proportional to N and without having
870 allocate a large buffer to hold the result set.
871 </p>
872
873 <h1 id="_searching_and_sorting_at_the_same_time"><span>3. </span> Searching And Sorting At The Same Time</h1>
874
875 <p>
876 The previous discussion has treated searching and sorting as separate
877 topics. But in practice, it is often the case that one wants to search
878 and sort at the same time. Fortunately, it is possible to do this
879 using a single index.
880 </p>
881
882 <h2 id="_searching_and_sorting_with_a_multi_column_index"><span>3.1. </span> Searching And Sorting With A Multi-Column Index</h2>
883
884 <p>
885 Suppose we want to find the prices of all kinds of oranges sorted in
886 order of the state where they are grown. The query is this:
887 </p>
888
889 <center><table><tr><td><pre>
890 SELECT price FROM fruitforsale WHERE fruit='Orange' ORDER BY state
891 </pre></table></center>
892
893
894 <p>
895 The query contains both a search restriction in the WHERE clause
896 and a sort order in the ORDER BY clause. Both the search and the sort
897 can be accomplished at the same time using the two-column index Idx3.
898 </p>
899
900 <a name='fig20'></a>
901 <p><center>
902 <img src="images/qp/fruitobstate0.gif" alt="figure 20"><br>
903 Figure 20: Search And Sort By Multi-Column Index
904 </center></p>
905
906
907 <p>
908 The query does a binary search on the index to find the subset of rows
909 that have fruit='Orange'. (Because the fruit column is the left-most column
910 of the index and the rows of the index are in sorted order, all such
911 rows will be adjacent.) Then it scans the matching index rows from top to
912 bottom to get the rowids for the original table, and for each rowid does
913 a binary search on the original table to find the price.
914 </p>
915
916 <p>
917 You will notice that there is no "sort" box anywhere in the above diagram.
918 The ORDER BY clause of the query has become a no-op. No sorting has to be
919 done here because the output order is by the state column and the state
920 column also happens to be the first column after the fruit column in the
921 index. So, if we scan entries of the index that have the same value for
922 the fruit column from top to bottom, those index entries are guaranteed to
923 be ordered by the state column.
924 </p>
925
926 <a name="srchsortcovidx"></a>
927
928 <h2 id="_searching_and_sorting_with_a_covering_index"><span>3.2. </span> Searching And Sorting With A Covering Index</h2>
929
930 <p>
931 A <a href="queryplanner.html#covidx">covering index</a> can also be used to search and sort at the same time.
932 Consider the following:
933 </p>
934
935 <center><table><tr><td><pre>
936 SELECT * FROM fruitforsale WHERE fruit='Orange' ORDER BY state
937 </pre></table></center>
938 <a name='fig21'></a>
939 <p><center>
940 <img src="images/qp/fruitobstate.gif" alt="figure 21"><br>
941 Figure 21: Search And Sort By Covering Index
942 </center></p>
943
944
945 <p>
946 As before, SQLite does single binary search
947 for the range of rows in the covering
948 index that satisfy the WHERE clause, the scans that range from top to
949 bottom to get the desired results.
950 The rows that satisfy the WHERE clause are guaranteed to be adjacent
951 since the WHERE clause is an equality constraint on the left-most
952 column of the index. And by scanning the matching index rows from
953 top to bottom, the output is guaranteed to be ordered by state since the
954 state column is the very next column to the right of the fruit column.
955 And so the resulting query is very efficient.
956 </p>
957
958 <p>
959 SQLite can pull a similar trick for a descending ORDER BY:
960 </p>
961
962 <center><table><tr><td><pre>
963 SELECT * FROM fruitforsale WHERE fruit='Orange' ORDER BY state DESC
964 </pre></table></center>
965
966
967 <p>
968 The same basic algorithm is followed, except this time the matching rows
969 of the index are scanned from bottom to top instead of from top to bottom,
970 so that the states will appear in descending order.
971 </p>
972
973 <a name="partialsort"></a>
974
975 <h2 id="_partial_sorting_using_an_index_a_k_a_block_sorting_"><span>3.3. </span> Partial Sorting Using An Index (a.k.a. Block Sorting)</h2>
976
977 <p>
978 Sometimes only part of an ORDER BY clause can be satisfied using indexes.
979 Consider, for example, the following query:
980 </p>
981
982 <center><table><tr><td><pre>
983 SELECT * FROM fruitforsale ORDER BY fruit, price
984 </pre></table></center>
985
986
987 <p>
988 If the covering index is used for the scan, the "fruit" column will appear
989 naturally in the correct order, but when there are two or more rows with
990 the same fruit, the price might be out of order. When this occurs, SQLite
991 does many small sorts, one sort for each distinct value of fruit, rather
992 than one large sort. Figure 22 below illustrates the concept.
993 </p>
994
995 <a name='fig22'></a>
996 <p><center>
997 <img src="images/qp/partial-sort.gif" alt="figure 22"><br>
998 Figure 22: Partial Sort By Index
999 </center></p>
1000
1001
1002 <p>
1003 In the example, instead of a single sort of 7 elements, there
1004 are 5 sorts of one-element each and 1 sort of 2 elements for the
1005 case of fruit=='Orange'.
1006
1007 </p><p>
1008 The advantages of doing many smaller sorts instead of a single large sort
1009 are:
1010 </p><ol>
1011 <li>Multiple small sorts collectively use fewer CPU cycles than a single
1012 large sort.
1013 </li><li>Each small sort is run independently, meaning that much less information
1014 needs to be kept in temporary storage at any one time.
1015 </li><li>Those columns of the ORDER BY that are already in the correct order
1016 due to indexes can be omitted from the sort key, further reducing
1017 storage requirements and CPU time.
1018 </li><li>Output rows can be returned to the application as each small sort
1019 completes, and well before the table scan is complete.
1020 </li><li>If a LIMIT clause is present, it might be possible to avoid scanning
1021 the entire table.
1022 </li></ol>
1023
1024 <p>Because of these advantages, SQLite always tries to do a partial sort using an
1025 index even if a complete sort by index is not possible.</p>
1026
1027 <h1 id="_without_rowid_tables"><span>4. </span> WITHOUT ROWID tables</h1>
1028
1029 <p>
1030 The basic principals described above apply to both ordinary rowid tables
1031 and <a href="withoutrowid.html">WITHOUT ROWID</a> tables.
1032 The only difference is that the rowid column that serves as the key for
1033 tables and that appears as the right-most term in indexes is replaced by
1034 the PRIMARY KEY.
1035 </p>
1036 <p align="center"><small><i>This page last modified on <a href="https://sqlite.org/docsrc/honeypot" id="mtimelink" data-href="https://sqlite.org/docsrc/finfo/pages/queryplanner.in?m=baee8e6b0d">2022-10-26 13:30:36</a> UTC </small></i></p>
1037