Debian Codegraph @

www/optoverview.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 SQLite Query Optimizer Overview</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 SQLite Query Optimizer Overview
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="#where_clause_analysis">2. WHERE Clause Analysis</a></div>
130 <div class="fancy-toc2"><a href="#index_term_usage_examples">2.1. Index Term Usage Examples</a></div>
131 <div class="fancy-toc1"><a href="#the_between_optimization">3. The BETWEEN Optimization</a></div>
132 <div class="fancy-toc1"><a href="#or_optimizations">4. OR Optimizations</a></div>
133 <div class="fancy-toc2"><a href="#converting_or_connected_constraint_into_an_in_operator">4.1. Converting OR-connected constraint into an IN operator</a></div>
134 <div class="fancy-toc2"><a href="#evaluating_or_constraints_separately_and_taking_the_union_of_the_result">4.2. Evaluating OR constraints separately and taking the UNION of the result</a></div>
135 <div class="fancy-toc1"><a href="#the_like_optimization">5. The LIKE Optimization</a></div>
136 <div class="fancy-toc1"><a href="#the_skip_scan_optimization">6. The Skip-Scan Optimization</a></div>
137 <div class="fancy-toc1"><a href="#joins">7. Joins</a></div>
138 <div class="fancy-toc2"><a href="#manual_control_of_join_order">7.1. Manual Control Of Join Order</a></div>
139 <div class="fancy-toc3"><a href="#manual_control_of_query_plans_using_sqlite_stat_tables">7.1.1. Manual Control Of Query Plans Using SQLITE_STAT Tables</a></div>
140 <div class="fancy-toc3"><a href="#manual_control_of_query_plans_using_cross_join">7.1.2. Manual Control of Query Plans using CROSS JOIN</a></div>
141 <div class="fancy-toc1"><a href="#choosing_between_multiple_indexes">8. Choosing Between Multiple Indexes</a></div>
142 <div class="fancy-toc2"><a href="#disqualifying_where_clause_terms_using_unary_">8.1. Disqualifying WHERE Clause Terms using Unary-"+"</a></div>
143 <div class="fancy-toc2"><a href="#range_queries">8.2. Range Queries</a></div>
144 <div class="fancy-toc1"><a href="#covering_indexes">9. Covering Indexes</a></div>
145 <div class="fancy-toc1"><a href="#order_by_optimizations">10. ORDER BY Optimizations</a></div>
146 <div class="fancy-toc2"><a href="#partial_order_by_via_index">10.1. Partial ORDER BY via Index</a></div>
147 <div class="fancy-toc1"><a href="#subquery_flattening">11. Subquery Flattening</a></div>
148 <div class="fancy-toc1"><a href="#subquery_co_routines">12. Subquery Co-routines</a></div>
149 <div class="fancy-toc2"><a href="#using_co_routines_to_defer_work_until_after_the_sorting">12.1. Using Co-routines to Defer Work until after the Sorting</a></div>
150 <div class="fancy-toc1"><a href="#the_min_max_optimization">13. The MIN/MAX Optimization</a></div>
151 <div class="fancy-toc1"><a href="#automatic_query_time_indexes">14. Automatic Query-Time Indexes</a></div>
152 <div class="fancy-toc2"><a href="#hash_joins">14.1. Hash Joins</a></div>
153 <div class="fancy-toc1"><a href="#the_predicate_push_down_optimization">15. The Predicate Push-Down Optimization</a></div>
154 <div class="fancy-toc1"><a href="#the_outer_join_strength_reduction_optimization">16. The OUTER JOIN Strength Reduction Optimization</a></div>
155 <div class="fancy-toc1"><a href="#the_omit_outer_join_optimization">17. The Omit OUTER JOIN Optimization</a></div>
156 <div class="fancy-toc1"><a href="#the_constant_propagation_optimization">18. The Constant Propagation Optimization</a></div>
157 </div>
158 </div>
159 <script>
160 function toggle_toc(){
161 var sub = document.getElementById("toc_sub")
162 var mk = document.getElementById("toc_mk")
163 if( sub.style.display!="block" ){
164 sub.style.display = "block";
165 mk.innerHTML = "&#x25bc;";
166 } else {
167 sub.style.display = "none";
168 mk.innerHTML = "&#x25ba;";
169 }
170 }
171 </script>
172 </div>
173
174
175
176
177
178 <h1 id="introduction"><span>1. </span>Introduction</h1>
179 <p>
180 This document provides an overview of how the query planner and optimizer
181 for SQLite works.
182
183
184 </p><p>
185 Given a single SQL statement, there might be dozens, hundreds, or even
186 thousands of ways to implement that statement, depending on the complexity
187 of the statement itself and of the underlying database schema. The
188 task of the query planner is to select the algorithm that minimizes
189 disk I/O and CPU overhead.
190
191
192 </p><p>
193 Additional background information is available in the
194 <a href="queryplanner.html">indexing tutorial</a> document.
195 The <a href="queryplanner-ng.html">Next Generation Query Planner</a> document provides more detail on
196 how the <a href="optoverview.html#joins">join order</a> is chosen.
197
198
199
200 <a name="where_clause"></a>
201
202 </p><h1 id="where_clause_analysis"><span>2. </span>WHERE Clause Analysis</h1>
203
204 <p>
205 Prior to analysis, the following transformations are made
206 to shift all join constraints into the WHERE clause:
207
208 </p><p>
209 </p><ul>
210 <li>All NATURAL joins are converted into joins with a USING clause.
211 </li><li>All USING clauses (including ones created by the previous step)
212 are converted into equivalent ON clauses.
213 </li><li>All ON clauses (include ones created by the previous step)
214 are added as new conjuncts (AND-connected terms) in the WHERE clause.
215 </li></ul>
216
217
218 <p>
219 SQLite makes no distinction between join constraints that occur in the
220 WHERE clause and constraints in the ON clause of an inner join, since that
221 distinction does not affect the outcome. However, there is
222 a difference between ON clause constraints and WHERE clause constraints for
223 outer joins. Therefore, when SQLite moves an ON clause constraint from an
224 outer join over to the WHERE clause it adds special tags to the Abstract
225 Syntax Tree (AST) to indicate that the constraint came from an outer join
226 and from which outer join it came. There is no way to add those tags in
227 pure SQL text. Hence, the SQL input must use ON clauses on outer joins.
228 But in the internal AST, all constraints are part of the WHERE clause,
229 because having everything in one place simplifies processing.
230
231 </p><p>
232 After all constraints have been shifted into the WHERE clause,
233 The WHERE clause is broken up into conjuncts (hereafter called
234 "terms"). In other words, the WHERE clause is broken up into pieces
235 separated from the others by an AND operator.
236 If the WHERE clause is composed of constraints separated by the OR
237 operator (disjuncts) then the entire clause is considered to be a single "term"
238 to which the <a href="#or_opt">OR-clause optimization</a> is applied.
239
240 </p><p>
241 All terms of the WHERE clause are analyzed to see if they can be
242 satisfied using indexes.
243 To be usable by an index a term must usually be of one of the following
244 forms:
245
246 <blockquote><pre><b>
247 </b><i>column</i><b> = </b><i>expression</i><b>
248 </b><i>column</i><b> IS </b><i>expression</i><b>
249 </b><i>column</i><b> &gt; </b><i>expression</i><b>
250 </b><i>column</i><b> &gt;= </b><i>expression</i><b>
251 </b><i>column</i><b> &lt; </b><i>expression</i><b>
252 </b><i>column</i><b> &lt;= </b><i>expression</i><b>
253 </b><i>expression</i><b> = </b><i>column</i><b>
254 </b><i>expression</i><b> IS </b><i>column</i><b>
255 </b><i>expression</i><b> &gt; </b><i>column</i><b>
256 </b><i>expression</i><b> &gt;= </b><i>column</i><b>
257 </b><i>expression</i><b> &lt; </b><i>column</i><b>
258 </b><i>expression</i><b> &lt;= </b><i>column</i><b>
259 </b><i>column</i><b> IN (</b><i>expression-list</i><b>)
260 </b><i>column</i><b> IN (</b><i>subquery</i><b>)
261 </b><i>column</i><b> IS NULL
262 </b><i>column</i><b> LIKE </b><i>pattern</i><b>
263 </b><i>column</i><b> GLOB </b><i>pattern</i><b>
264 </b></pre></blockquote>
265
266 </p><p>
267 If an index is created using a statement like this:
268
269 </p><div class="codeblock"><pre>CREATE INDEX idx_ex1 ON ex1(a,b,c,d,e,...,y,z);
270 </pre></div>
271
272 <p>
273 Then the index might be used if the initial columns of the index
274 (columns a, b, and so forth) appear in WHERE clause terms.
275 The initial columns of the index must be used with
276 the <b>=</b> or <b>IN</b> or <b>IS</b> operators.
277 The right-most column that is used can employ inequalities.
278 For the right-most
279 column of an index that is used, there can be up to two inequalities
280 that must sandwich the allowed values of the column between two extremes.
281
282 </p><p>
283 It is not necessary for every column of an index to appear in a
284 WHERE clause term in order for that index to be used.
285 However, there cannot be gaps in the columns of the index that are used.
286 Thus for the example index above, if there is no WHERE clause term
287 that constrains column c, then terms that constrain columns a and b can
288 be used with the index but not terms that constrain columns d through z.
289 Similarly, index columns will not normally be used (for indexing purposes)
290 if they are to the right of a
291 column that is constrained only by inequalities.
292 (See the <a href="optoverview.html#skipscan">skip-scan optimization</a> below for the exception.)
293
294 </p><p>
295 In the case of <a href="expridx.html">indexes on expressions</a>, whenever the word "column" is
296 used in the foregoing text, one can substitute "indexed expression"
297 (meaning a copy of the expression that appears in the <a href="lang_createindex.html">CREATE INDEX</a>
298 statement) and everything will work the same.
299
300
301 <a name="idxexamp"></a>
302
303 </p><h2 id="index_term_usage_examples"><span>2.1. </span>Index Term Usage Examples</h2>
304 <p>
305 For the index above and WHERE clause like this:
306
307 </p><div class="codeblock"><pre>... WHERE a=5 AND b IN (1,2,3) AND c IS NULL AND d='hello'
308 </pre></div>
309 <p>
310 The first four columns a, b, c, and d of the index would be usable since
311 those four columns form a prefix of the index and are all bound by
312 equality constraints.
313
314 </p><p>
315 For the index above and WHERE clause like this:
316
317 </p><div class="codeblock"><pre>... WHERE a=5 AND b IN (1,2,3) AND c>12 AND d='hello'
318 </pre></div>
319 <p>
320 Only columns a, b, and c of the index would be usable. The d column
321 would not be usable because it occurs to the right of c and c is
322 constrained only by inequalities.
323
324 </p><p>
325 For the index above and WHERE clause like this:
326
327 </p><div class="codeblock"><pre>... WHERE a=5 AND b IN (1,2,3) AND d='hello'
328 </pre></div>
329 <p>
330 Only columns a and b of the index would be usable. The d column
331 would not be usable because column c is not constrained and there can
332 be no gaps in the set of columns that usable by the index.
333
334 </p><p>
335 For the index above and WHERE clause like this:
336
337 </p><div class="codeblock"><pre>... WHERE b IN (1,2,3) AND c NOT NULL AND d='hello'
338 </pre></div>
339 <p>
340 The index is not usable at all because the left-most column of the
341 index (column "a") is not constrained. Assuming there are no other
342 indexes, the query above would result in a full table scan.
343
344 </p><p>
345 For the index above and WHERE clause like this:
346
347 </p><div class="codeblock"><pre>... WHERE a=5 OR b IN (1,2,3) OR c NOT NULL OR d='hello'
348 </pre></div>
349 <p>
350 The index is not usable because the WHERE clause terms are connected
351 by OR instead of AND. This query would result in a full table scan.
352 However, if three additional indexes where added that contained columns
353 b, c, and d as their left-most columns, then the
354 <a href="#or_opt">OR-clause optimization</a> might apply.
355
356
357 <a name="between_opt"></a>
358
359 </p><h1 id="the_between_optimization"><span>3. </span>The BETWEEN Optimization</h1>
360
361 <p>
362 If a term of the WHERE clause is of the following form:
363
364 <blockquote><pre><b>
365 </b><i>expr1</i><b> BETWEEN </b><i>expr2</i><b> AND </b><i>expr3</i><b>
366 </b></pre></blockquote>
367 </p><p>
368 Then two "virtual" terms are added as follows:
369
370 <blockquote><pre><b>
371 </b><i>expr1</i><b> &gt;= </b><i>expr2</i><b> AND </b><i>expr1</i><b> &lt;= </b><i>expr3</i><b>
372 </b></pre></blockquote>
373 </p><p>
374 Virtual terms are used for analysis only and do not cause any byte-code
375 to be generated.
376 If both virtual terms end up being used as constraints on an index,
377 then the original BETWEEN term is omitted and the corresponding test
378 is not performed on input rows.
379 Thus if the BETWEEN term ends up being used as an index constraint
380 no tests are ever performed on that term.
381 On the other hand, the
382 virtual terms themselves never causes tests to be performed on
383 input rows.
384 Thus if the BETWEEN term is not used as an index constraint and
385 instead must be used to test input rows, the <i>expr1</i> expression is
386 only evaluated once.
387
388 <a name="or_opt"></a>
389
390 </p><h1 id="or_optimizations"><span>4. </span>OR Optimizations</h1>
391
392 <p>
393 WHERE clause constraints that are connected by OR instead of AND can
394 be handled in two different ways.
395
396 </p><h2 id="converting_or_connected_constraint_into_an_in_operator"><span>4.1. </span>Converting OR-connected constraint into an IN operator</h2>
397
398 <p>
399 If a term consists of multiple subterms containing a common column
400 name and separated by OR, like this:
401
402 <blockquote><pre><b>
403 </b><i>column</i><b> = </b><i>expr1</i><b> OR </b><i>column</i><b> = </b><i>expr2</i><b> OR </b><i>column</i><b> = </b><i>expr3</i><b> OR ...
404 </b></pre></blockquote>
405 </p><p>
406 Then that term is rewritten as follows:
407
408 <blockquote><pre><b>
409 </b><i>column</i><b> IN (</b><i>expr1</i><b>,</b><i>expr2</i><b>,</b><i>expr3</i><b>,...)
410 </b></pre></blockquote>
411 </p><p>
412 The rewritten term then might go on to constrain an index using the
413 normal rules for <b>IN</b> operators. Note that <i>column</i> must be
414 the same column in every OR-connected subterm,
415 although the column can occur on either the left or the right side of
416 the <b>=</b> operator.
417
418 </p><h2 id="evaluating_or_constraints_separately_and_taking_the_union_of_the_result"><span>4.2. </span>Evaluating OR constraints separately and taking the UNION of the result</h2>
419
420 <p>
421 If and only if the previously described conversion of OR to an IN operator
422 does not work, the second OR-clause optimization is attempted.
423 Suppose the OR clause consists of multiple subterms as follows:
424
425 <blockquote><pre><b>
426 </b><i>expr1</i><b> OR </b><i>expr2</i><b> OR </b><i>expr3</i><b>
427 </b></pre></blockquote>
428 </p><p>
429 Individual subterms might be a single comparison expression like
430 <b>a=5</b> or <b>x&gt;y</b> or they can be
431 LIKE or BETWEEN expressions, or a subterm
432 can be a parenthesized list of AND-connected sub-subterms.
433 Each subterm is analyzed as if it were itself the entire WHERE clause
434 in order to see if the subterm is indexable by itself.
435 If <u>every</u> subterm of an OR clause is separately indexable
436 then the OR clause might be coded such that a separate index is used
437 to evaluate each term of the OR clause. One way to think about how
438 SQLite uses separate indexes for each OR clause term is to imagine
439 that the WHERE clause where rewritten as follows:
440
441 <blockquote><pre><b>
442 rowid IN (SELECT rowid FROM </b><i>table</i><b> WHERE </b><i>expr1</i><b>
443 UNION SELECT rowid FROM </b><i>table</i><b> WHERE </b><i>expr2</i><b>
444 UNION SELECT rowid FROM </b><i>table</i><b> WHERE </b><i>expr3</i><b>)
445 </b></pre></blockquote>
446 </p><p>
447 The rewritten expression above is conceptual; WHERE clauses containing
448 OR are not really rewritten this way.
449 The actual implementation of the OR clause uses a mechanism that is
450 more efficient and that works even for <a href="withoutrowid.html">WITHOUT ROWID</a> tables or
451 tables in which the "rowid" is inaccessible. Nevertheless,
452 the essence of the implementation is captured by the statement
453 above: Separate indexes are used to find candidate result rows
454 from each OR clause term and the final result is the union of
455 those rows.
456
457 </p><p>
458 Note that in most cases, SQLite will only use a single index for each
459 table in the FROM clause of a query. The second OR-clause optimization
460 described here is the exception to that rule. With an OR-clause,
461 a different index might be used for each subterm in the OR-clause.
462
463 </p><p>
464 For any given query, the fact that the OR-clause optimization described
465 here can be used does not guarantee that it will be used.
466 SQLite uses a cost-based query planner that estimates the CPU and
467 disk I/O costs of various competing query plans and chooses the plan
468 that it thinks will be the fastest. If there are many OR terms in
469 the WHERE clause or if some of the indexes on individual OR-clause
470 subterms are not very selective, then SQLite might decide that it is
471 faster to use a different query algorithm, or even a full-table scan.
472 Application developers can use the
473 <a href="lang_explain.html">EXPLAIN QUERY PLAN</a> prefix on a statement to get a
474 high-level overview of the chosen query strategy.
475
476 <a name="like_opt"></a>
477
478 </p><h1 id="the_like_optimization"><span>5. </span>The LIKE Optimization</h1>
479
480 <p>
481 A WHERE-clause term that uses the <a href="lang_expr.html#like">LIKE</a> or <a href="lang_expr.html#glob">GLOB</a> operator
482 can sometimes be used with an index to do a range search,
483 almost as if the LIKE or GLOB were an alternative to a <a href="lang_expr.html#between">BETWEEN</a>
484 operator.
485 There are many conditions on this optimization:
486
487 </p><p>
488 </p><ol>
489 <li>The right-hand side of the LIKE or GLOB must be either a string literal
490 or a <a href="lang_expr.html#varparam">parameter</a> bound to a string literal
491 that does not begin with a wildcard character.</li>
492 <li>It must not be possible to make the LIKE or GLOB operator true by
493 having a numeric value (instead of a string or blob) on the
494 left-hand side. This means that either:
495 <ol type="A">
496 <li> the left-hand side of the LIKE or GLOB operator is the name
497 of an indexed column with <a href="datatype3.html#affinity">TEXT affinity</a>, or</li>
498 <li> the right-hand side pattern argument does not begin with a
499 minus sign ("-") or a digit.</li>
500 </ol>
501 This constraint arises from the fact that numbers do not sort in
502 lexicographical order. For example: 9&lt;10 but '9'&gt;'10'.</li>
503 <li>The built-in functions used to implement LIKE and GLOB must not
504 have been overloaded using the <a href="c3ref/create_function.html">sqlite3_create_function()</a> API.</li>
505 <li>For the GLOB operator, the column must be indexed using the
506 built-in BINARY collating sequence.</li>
507 <li>For the LIKE operator, if <a href="pragma.html#pragma_case_sensitive_like">case_sensitive_like</a> mode is enabled then
508 the column must indexed using BINARY collating sequence, or if
509 <a href="pragma.html#pragma_case_sensitive_like">case_sensitive_like</a> mode is disabled then the column must indexed
510 using built-in NOCASE collating sequence.</li>
511 <li>If the ESCAPE option is used, the ESCAPE character must be ASCII,
512 or a single-byte character in UTF-8.
513 </li></ol>
514
515 <p>
516 The LIKE operator has two modes that can be set by a
517 <a href="pragma.html#pragma_case_sensitive_like">pragma</a>. The
518 default mode is for LIKE comparisons to be insensitive to differences
519 of case for latin1 characters. Thus, by default, the following
520 expression is true:
521
522 </p><div class="codeblock"><pre>'a' LIKE 'A'
523 </pre></div>
524 <p>
525 If the case_sensitive_like pragma is enabled as follows:
526
527 </p><div class="codeblock"><pre>PRAGMA case_sensitive_like=ON;
528 </pre></div>
529 <p>
530 Then the LIKE operator pays attention to case and the example above would
531 evaluate to false. Note that case insensitivity only applies to
532 latin1 characters - basically the upper and lower case letters of English
533 in the lower 127 byte codes of ASCII. International character sets
534 are case sensitive in SQLite unless an application-defined
535 <a href="datatype3.html#collation">collating sequence</a> and <a href="lang_corefunc.html#like">like() SQL function</a> are provided that
536 take non-ASCII characters into account.
537 If an application-defined collating sequence and/or like() SQL
538 function are provided, the LIKE optimization described here will never
539 be taken.
540
541 </p><p>
542 The LIKE operator is case insensitive by default because this is what
543 the SQL standard requires. You can change the default behavior at
544 compile time by using the <a href="compile.html#case_sensitive_like">SQLITE_CASE_SENSITIVE_LIKE</a> command-line option
545 to the compiler.
546
547 </p><p>
548 The LIKE optimization might occur if the column named on the left of the
549 operator is indexed using the built-in BINARY collating sequence and
550 case_sensitive_like is turned on. Or the optimization might occur if
551 the column is indexed using the built-in NOCASE collating sequence and the
552 case_sensitive_like mode is off. These are the only two combinations
553 under which LIKE operators will be optimized.
554
555 </p><p>
556 The GLOB operator is always case sensitive. The column on the left side
557 of the GLOB operator must always use the built-in BINARY collating sequence
558 or no attempt will be made to optimize that operator with indexes.
559
560 </p><p>
561 The LIKE optimization will only be attempted if
562 the right-hand side of the GLOB or LIKE operator is either
563 literal string or a <a href="lang_expr.html#varparam">parameter</a> that has been <a href="c3ref/bind_blob.html">bound</a>
564 to a string literal. The string literal must not
565 begin with a wildcard; if the right-hand side begins with a wildcard
566 character then this optimization is not attempted. If the right-hand side
567 is a <a href="lang_expr.html#varparam">parameter</a> that is bound to a string, then this optimization is
568 only attempted if the <a href="c3ref/stmt.html">prepared statement</a> containing the expression
569 was compiled with <a href="c3ref/prepare.html">sqlite3_prepare_v2()</a> or <a href="c3ref/prepare.html">sqlite3_prepare16_v2()</a>.
570 The LIKE optimization is not attempted if the
571 right-hand side is a <a href="lang_expr.html#varparam">parameter</a> and the statement was prepared using
572 <a href="c3ref/prepare.html">sqlite3_prepare()</a> or <a href="c3ref/prepare.html">sqlite3_prepare16()</a>.
573
574 </p><p>
575 Suppose the initial sequence of non-wildcard characters on the right-hand
576 side of the LIKE or GLOB operator is <i>x</i>. We are using a single
577 character to denote this non-wildcard prefix but the reader should
578 understand that the prefix can consist of more than 1 character.
579 Let <i>y</i> be the smallest string that is the same length as /x/ but which
580 compares greater than <i>x</i>. For example, if <i>x</i> is
581 <tt>'hello'</tt> then
582 <i>y</i> would be <tt>'hellp'</tt>.
583 The LIKE and GLOB optimizations consist of adding two virtual terms
584 like this:
585
586 <blockquote><pre><b>
587 </b><i>column</i><b> &gt;= </b><i>x</i><b> AND </b><i>column</i><b> &lt; </b><i>y</i><b>
588 </b></pre></blockquote>
589 </p><p>
590 Under most circumstances, the original LIKE or GLOB operator is still
591 tested against each input row even if the virtual terms are used to
592 constrain an index. This is because we do not know what additional
593 constraints may be imposed by characters to the right
594 of the <i>x</i> prefix. However, if there is only a single
595 global wildcard to the right of <i>x</i>, then the original LIKE or
596 GLOB test is disabled.
597 In other words, if the pattern is like this:
598
599 <blockquote><pre><b>
600 </b><i>column</i><b> LIKE </b><i>x</i><b>%
601 </b><i>column</i><b> GLOB </b><i>x</i><b>*
602 </b></pre></blockquote>
603 </p><p>
604 then the original LIKE or GLOB tests are disabled when the virtual
605 terms constrain an index because in that case we know that all of the
606 rows selected by the index will pass the LIKE or GLOB test.
607
608 </p><p>
609 Note that when the right-hand side of a LIKE or GLOB operator is
610 a <a href="lang_expr.html#varparam">parameter</a> and the statement is prepared using <a href="c3ref/prepare.html">sqlite3_prepare_v2()</a>
611 or <a href="c3ref/prepare.html">sqlite3_prepare16_v2()</a> then the statement is automatically reparsed
612 and recompiled on the first <a href="c3ref/step.html">sqlite3_step()</a> call of each run if the binding
613 to the right-hand side parameter has changed since the previous run.
614 This reparse and recompile is essentially the same action that occurs
615 following a schema change. The recompile is necessary so that the query
616 planner can examine the new value bound to the right-hand side of the
617 LIKE or GLOB operator and determine whether or not to employ the
618 optimization described above.
619
620 <a name="skipscan"></a>
621
622 </p><h1 id="the_skip_scan_optimization"><span>6. </span>The Skip-Scan Optimization</h1>
623
624 <p>
625 The general rule is that indexes are only useful if there are
626 WHERE-clause constraints on the left-most columns of the index.
627 However, in some cases,
628 SQLite is able to use an index even if the first few columns of
629 the index are omitted from the WHERE clause but later columns
630 are included.
631
632
633 </p><p>
634 Consider a table such as the following:
635
636 </p><div class="codeblock"><pre>CREATE TABLE people(
637 name TEXT PRIMARY KEY,
638 role TEXT NOT NULL,
639 height INT NOT NULL, -- in cm
640 CHECK( role IN ('student','teacher') )
641 );
642 CREATE INDEX people_idx1 ON people(role, height);
643 </pre></div>
644
645 <p>
646 The people table has one entry for each person in a large
647 organization. Each person is either a "student" or a "teacher",
648 as determined by the "role" field. The table also records the height in
649 centimeters of each person. The role and height are indexed.
650 Notice that the left-most column of the index is not very
651 selective - it only contains two possible values.
652
653
654 </p><p>
655 Now consider a query to find the names of everyone in the
656 organization that is 180cm tall or taller:
657
658
659 </p><div class="codeblock"><pre>SELECT name FROM people WHERE height>=180;
660 </pre></div>
661
662 <p>
663 Because the left-most column of the index does not appear in the
664 WHERE clause of the query, one is tempted to conclude that the
665 index is not usable here. However, SQLite is able to use the index.
666 Conceptually, SQLite uses the index as if the query were more
667 like the following:
668
669
670 </p><div class="codeblock"><pre>SELECT name FROM people
671 WHERE role IN (SELECT DISTINCT role FROM people)
672 AND height>=180;
673 </pre></div>
674
675 <p>
676 Or this:
677
678 </p><div class="codeblock"><pre>SELECT name FROM people WHERE role='teacher' AND height>=180
679 UNION ALL
680 SELECT name FROM people WHERE role='student' AND height>=180;
681 </pre></div>
682
683 <p>
684 The alternative query formulations shown above are conceptual only.
685 SQLite does not really transform the query.
686 The actual query plan is like this:
687 SQLite locates the first possible value for "role", which it
688 can do by rewinding the "people_idx1" index to the beginning and reading
689 the first record. SQLite stores this first "role" value in an
690 internal variable that we will here call "$role". Then SQLite
691 runs a query like: "SELECT name FROM people WHERE role=$role AND height>=180".
692 This query has an equality constraint on the left-most column of the
693 index and so the index can be used to resolve that query. Once
694 that query is finished, SQLite then uses the "people_idx1" index to
695 locate the next value of the "role" column, using code that is logically
696 similar to "SELECT role FROM people WHERE role>$role LIMIT 1".
697 This new "role" value overwrites the $role variable, and the process
698 repeats until all possible values for "role" have been examined.
699
700 </p><p>
701 We call this kind of index usage a "skip-scan" because the database
702 engine is basically doing a full scan of the index but it optimizes the
703 scan (making it less than "full") by occasionally skipping ahead to the
704 next candidate value.
705
706 </p><p>
707 SQLite might use a skip-scan on an index if it knows that the first
708 one or more columns contain many duplication values.
709 If there are too few duplicates
710 in the left-most columns of the index, then it would
711 be faster to simply step ahead to the next value, and thus do
712 a full table scan, than to do a binary search on an index to locate
713 the next left-column value.
714
715 </p><p>
716 The only way that SQLite can know that there are many duplicates
717 in the left-most columns of an index
718 is if the <a href="lang_analyze.html">ANALYZE</a> command has been run
719 on the database.
720 Without the results of ANALYZE, SQLite has to guess at the "shape" of
721 the data in the table, and the default guess is that there are an average
722 of 10 duplicates for every value in the left-most column of the index.
723 Skip-scan only becomes profitable (it only gets to be faster than
724 a full table scan) when the number of duplicates is about 18 or more.
725 Hence, a skip-scan is never used on a database that has not been analyzed.
726
727 <a name="joins"></a>
728
729 </p><h1 id="joins"><span>7. </span>Joins</h1>
730
731 <p>
732 SQLite implements joins as nested loops.
733 The default order of the nested loops in a join is for the left-most
734 table in the FROM clause to form the outer loop and the right-most
735 table to form the inner loop.
736 However, SQLite will nest the loops in a different order if doing so
737 will help it to select better indexes.
738
739 </p><p>
740 Inner joins can be freely reordered. However outer joins are
741 neither commutative nor associative and hence will not be reordered.
742 Inner joins to the left and right of an outer join might be reordered
743 if the optimizer thinks that is advantageous but outer joins are
744 always evaluated in the order in which they occur.
745
746 </p><p>
747 SQLite <a href="lang_select.html#crossjoin">treats the CROSS JOIN operator specially</a>.
748 The CROSS JOIN operator is commutative, in theory. However, SQLite chooses to
749 never reorder tables in a CROSS JOIN. This provides a mechanism
750 by which the programmer can force SQLite to choose a particular loop nesting
751 order.
752
753 </p><p>
754 When selecting the order of tables in a join, SQLite uses an efficient
755 polynomial-time algorithm graph algorithm described in
756 the <a href="queryplanner-ng.html">Next Generation Query Planner</a> document. Because of this,
757 SQLite is able to plan queries with 50- or 60-way joins in a matter of
758 microseconds
759
760 </p><p>
761 Join reordering is automatic and usually works well enough that
762 programmers do not have to think about it, especially if <a href="lang_analyze.html">ANALYZE</a>
763 has been used to gather statistics about the available indexes,
764 though occasionally some hints from the programmer are needed.
765 Consider, for example, the following schema:
766
767 </p><div class="codeblock"><pre>CREATE TABLE node(
768 id INTEGER PRIMARY KEY,
769 name TEXT
770 );
771 CREATE INDEX node_idx ON node(name);
772 CREATE TABLE edge(
773 orig INTEGER REFERENCES node,
774 dest INTEGER REFERENCES node,
775 PRIMARY KEY(orig, dest)
776 );
777 CREATE INDEX edge_idx ON edge(dest,orig);
778 </pre></div>
779 <p>
780 The schema above defines a directed graph with the ability to store a
781 name at each node. Now consider a query against this schema:
782
783 </p><div class="codeblock"><pre>SELECT *
784 FROM edge AS e,
785 node AS n1,
786 node AS n2
787 WHERE n1.name = 'alice'
788 AND n2.name = 'bob'
789 AND e.orig = n1.id
790 AND e.dest = n2.id;
791 </pre></div>
792 <p>
793 This query asks for is all information about edges that go from
794 nodes labeled "alice" to nodes labeled "bob".
795 The query optimizer in SQLite has basically two choices on how to
796 implement this query. (There are actually six different choices, but
797 we will only consider two of them here.)
798 Pseudocode below demonstrating these two choices.
799
800 <a name="option1"></a>
801
802 </p><p>Option 1:
803 </p><div class="codeblock"><pre>foreach n1 where n1.name='alice' do:
804 foreach n2 where n2.name='bob' do:
805 foreach e where e.orig=n1.id and e.dest=n2.id
806 return n1.*, n2.*, e.*
807 end
808 end
809 end
810 </pre></div>
811 <a name="option2"></a>
812
813 <p>Option 2:
814 </p><div class="codeblock"><pre>foreach n1 where n1.name='alice' do:
815 foreach e where e.orig=n1.id do:
816 foreach n2 where n2.id=e.dest and n2.name='bob' do:
817 return n1.*, n2.*, e.*
818 end
819 end
820 end
821 </pre></div>
822 <p>
823 The same indexes are used to speed up every loop in both implementation
824 options.
825 The only difference in these two query plans is the order in which
826 the loops are nested.
827
828 </p><p>
829 So which query plan is better? It turns out that the answer depends on
830 what kind of data is found in the node and edge tables.
831
832 </p><p>
833 Let the number of alice nodes be M and the number of bob nodes be N.
834 Consider two scenarios. In the first scenario, M and N are both 2 but
835 there are thousands of edges on each node. In this case, option 1 is
836 preferred. With option 1, the inner loop checks for the existence of
837 an edge between a pair of nodes and outputs the result if found.
838 Because there are only 2 alice and bob nodes each, the inner loop
839 only has to run four times and the query is very quick. Option 2 would
840 take much longer here. The outer loop of option 2 only executes twice,
841 but because there are a large number of edges leaving each alice node,
842 the middle loop has to iterate many thousands of times. It will be
843 much slower. So in the first scenario, we prefer to use option 1.
844
845 </p><p>
846 Now consider the case where M and N are both 3500. Alice nodes are
847 abundant. This time suppose each of these nodes is connected by only one
848 or two edges. Now option 2 is preferred. With option 2,
849 the outer loop still has to run 3500 times, but the middle loop only
850 runs once or twice for each outer loop and the inner loop will only
851 run once for each middle loop, if at all. So the total number of
852 iterations of the inner loop is around 7000. Option 1, on the other
853 hand, has to run both its outer loop and its middle loop 3500 times
854 each, resulting in 12 million iterations of the middle loop.
855 Thus in the second scenario, option 2 is nearly 2000 times faster
856 than option 1.
857
858 </p><p>
859 So you can see that depending on how the data is structured in the table,
860 either query plan 1 or query plan 2 might be better. Which plan does
861 SQLite choose by default? As of version 3.6.18, without running <a href="lang_analyze.html">ANALYZE</a>,
862 SQLite will choose option 2.
863 If the <a href="lang_analyze.html">ANALYZE</a> command is run in order to gather statistics,
864 a different choice might be made if the statistics indicate that the
865 alternative is likely to run faster.
866
867 </p><h2 id="manual_control_of_join_order"><span>7.1. </span>Manual Control Of Join Order</h2>
868
869 <p>
870 SQLite almost always picks the best join order automatically. It is
871 very rare that a developer needs to intervene to give the query planner
872 hints about the best join order. The best policy is to make use
873 of <a href="pragma.html#pragma_optimize">PRAGMA optimize</a> to ensure that the query planner has access to
874 up-to-date statistics on the shape of the data in the database.
875
876 </p><p>
877 This section describes techniques by which developers can control the
878 join order in SQLite, to work around any performance problems that may
879 arise. However, the use of these techniques is not recommended, except
880 as a last resort.
881
882 </p><p>
883 If you do encounter a situation where SQLite is picking a suboptimal
884 join order even after running <a href="pragma.html#pragma_optimize">PRAGMA optimize</a>, please report your
885 situation on the <a href="https://sqlite.org/forum">SQLite Community Forum</a> so
886 that the SQLite maintainers can make new refinements to the query planner
887 such that manual intervention is not required.
888
889 <a name="manctrl"></a>
890
891 </p><h3 id="manual_control_of_query_plans_using_sqlite_stat_tables"><span>7.1.1. </span>Manual Control Of Query Plans Using SQLITE_STAT Tables</h3>
892
893 <p>
894 SQLite provides the ability for advanced programmers to exercise control
895 over the query plan chosen by the optimizer. One method for doing this
896 is to fudge the <a href="lang_analyze.html">ANALYZE</a> results in the <a href="fileformat2.html#stat1tab">sqlite_stat1</a> table.
897
898 <a name="crossjoin"></a>
899
900 </p><h3 id="manual_control_of_query_plans_using_cross_join"><span>7.1.2. </span>Manual Control of Query Plans using CROSS JOIN</h3>
901
902 <p>
903 Programmers can force SQLite to use a particular loop nesting order
904 for a join by using the CROSS JOIN operator instead of just JOIN,
905 INNER JOIN, NATURAL JOIN, or a "," join. Though CROSS JOINs are
906 commutative in theory, SQLite chooses to never reorder the tables in
907 a CROSS JOIN. Hence, the left table of a CROSS JOIN will always be
908 in an outer loop relative to the right table.
909
910 </p><p>
911 In the following query, the optimizer is free to reorder the
912 tables of FROM clause any way it sees fit:
913
914 </p><div class="codeblock"><pre>SELECT *
915 FROM node AS n1,
916 edge AS e,
917 node AS n2
918 WHERE n1.name = 'alice'
919 AND n2.name = 'bob'
920 AND e.orig = n1.id
921 AND e.dest = n2.id;
922 </pre></div>
923 <p>
924 In the following logically equivalent formulation of the same query,
925 the substitution of "CROSS JOIN" for the "," means that the order
926 of tables must be N1, E, N2.
927
928 </p><div class="codeblock"><pre>SELECT *
929 FROM node AS n1 CROSS JOIN
930 edge AS e CROSS JOIN
931 node AS n2
932 WHERE n1.name = 'alice'
933 AND n2.name = 'bob'
934 AND e.orig = n1.id
935 AND e.dest = n2.id;
936 </pre></div>
937 <p>
938 In the latter query, the query plan must be
939 <a href="#option2">option 2</a>. Note that
940 you must use the keyword "CROSS" in order to disable the table reordering
941 optimization; INNER JOIN, NATURAL JOIN, JOIN, and other similar
942 combinations work just like a comma join in that the optimizer is
943 free to reorder tables as it sees fit. (Table reordering is also
944 disabled on an outer join, but that is because outer joins are not
945 associative or commutative. Reordering tables in OUTER JOIN changes
946 the result.)
947
948 </p><p>
949 See "<a href="queryplanner-ng.html#fossilcasestudy">The Fossil NGQP Upgrade Case Study</a>" for another real-world example
950 of using CROSS JOIN to manually control the nesting order of a join.
951 The <a href="queryplanner-ng.html#howtofix">query planner checklist</a> found later in the same document provides
952 further guidance on manual control of the query planner.
953
954 <a name="multi_index"></a>
955
956 </p><h1 id="choosing_between_multiple_indexes"><span>8. </span>Choosing Between Multiple Indexes</h1>
957
958 <p>
959 Each table in the FROM clause of a query can use at most one index
960 (except when the <a href="#or_opt">OR-clause optimization</a> comes into
961 play)
962 and SQLite strives to use at least one index on each table. Sometimes,
963 two or more indexes might be candidates for use on a single table.
964 For example:
965
966 </p><div class="codeblock"><pre>CREATE TABLE ex2(x,y,z);
967 CREATE INDEX ex2i1 ON ex2(x);
968 CREATE INDEX ex2i2 ON ex2(y);
969 SELECT z FROM ex2 WHERE x=5 AND y=6;
970 </pre></div>
971 <p>
972 For the SELECT statement above, the optimizer can use the ex2i1 index
973 to lookup rows of ex2 that contain x=5 and then test each row against
974 the y=6 term. Or it can use the ex2i2 index to lookup rows
975 of ex2 that contain y=6 then test each of those rows against the
976 x=5 term.
977
978 </p><p>
979 When faced with a choice of two or more indexes, SQLite tries to estimate
980 the total amount of work needed to perform the query using each option.
981 It then selects the option that gives the least estimated work.
982
983 </p><p>
984 To help the optimizer get a more accurate estimate of the work involved
985 in using various indexes, the user may optionally run the <a href="lang_analyze.html">ANALYZE</a> command.
986 The <a href="lang_analyze.html">ANALYZE</a> command scans all indexes of database where there might
987 be a choice between two or more indexes and gathers statistics on the
988 selectiveness of those indexes. The statistics gathered by
989 this scan are stored in special database tables names shows names all
990 begin with "<b>sqlite_stat</b>".
991 The content of these tables is not updated as the database
992 changes so after making significant changes it might be prudent to
993 rerun <a href="lang_analyze.html">ANALYZE</a>.
994 The results of an ANALYZE command are only available to database connections
995 that are opened after the ANALYZE command completes.
996
997 </p><p>
998 The various <b>sqlite_stat</b><i>N</i> tables contain information on how
999 selective the various indexes are. For example, the <a href="fileformat2.html#stat1tab">sqlite_stat1</a>
1000 table might indicate that an equality constraint on column x reduces the
1001 search space to 10 rows on average, whereas an equality constraint on
1002 column y reduces the search space to 3 rows on average. In that case,
1003 SQLite would prefer to use index ex2i2 since that index is more selective.
1004
1005 <a name="uplus"></a>
1006
1007 </p><h2 id="disqualifying_where_clause_terms_using_unary_"><span>8.1. </span>Disqualifying WHERE Clause Terms using Unary-"+"</h2>
1008
1009 <p>
1010 <i>Note: Disqualifying WHERE clause terms this way is not recommended.
1011 This is a work-around.
1012 Only do this as a last resort to get the performance you need. If you
1013 find a situation where this work-around is necessary, please report the
1014 situation on the <a href="https://sqlite.org/forum">SQLite Community Forum</a> so
1015 that the SQLite maintainers can try to improve the query planner such
1016 that the work-around is no longer required for your situation.</i>
1017
1018 </p><p>
1019 Terms of the WHERE clause can be manually disqualified for use with
1020 indexes by prepending a unary <b>+</b> operator to the column name. The
1021 unary <b>+</b> is a no-op and will not generate any byte code in the prepared
1022 statement.
1023 However, the unary <b>+</b> operator will prevent the term from
1024 constraining an index.
1025 So, in the example above, if the query were rewritten as:
1026
1027 </p><div class="codeblock"><pre>SELECT z FROM ex2 WHERE +x=5 AND y=6;
1028 </pre></div>
1029 <p>
1030 The <b>+</b> operator on the <b>x</b> column will prevent that term from
1031 constraining an index. This would force the use of the ex2i2 index.
1032
1033 </p><p>
1034 Note that the unary <b>+</b> operator also removes
1035 <a href="datatype3.html#affinity">type affinity</a> from
1036 an expression, and in some cases this can cause subtle changes in
1037 the meaning of an expression.
1038 In the example above,
1039 if column <b>x</b> has <a href="datatype3.html#affinity">TEXT affinity</a>
1040 then the comparison "x=5" will be done as text. The <b>+</b> operator
1041 removes the affinity. So the comparison "<b>+x=5</b>" will compare the text
1042 in column <b>x</b> with the numeric value 5 and will always be false.
1043
1044 <a name="rangequery"></a>
1045
1046 </p><h2 id="range_queries"><span>8.2. </span>Range Queries</h2>
1047
1048 <p>
1049 Consider a slightly different scenario:
1050
1051 </p><div class="codeblock"><pre>CREATE TABLE ex2(x,y,z);
1052 CREATE INDEX ex2i1 ON ex2(x);
1053 CREATE INDEX ex2i2 ON ex2(y);
1054 SELECT z FROM ex2 WHERE x BETWEEN 1 AND 100 AND y BETWEEN 1 AND 100;
1055 </pre></div>
1056 <p>
1057 Further suppose that column x contains values spread out
1058 between 0 and 1,000,000 and column y contains values
1059 that span between 0 and 1,000. In that scenario,
1060 the range constraint on column x should reduce the search space by
1061 a factor of 10,000 whereas the range constraint on column y should
1062 reduce the search space by a factor of only 10. So the ex2i1 index
1063 should be preferred.
1064
1065 </p><p>
1066 SQLite will make this determination, but only if it has been compiled
1067 with <a href="compile.html#enable_stat3">SQLITE_ENABLE_STAT3</a> or <a href="compile.html#enable_stat4">SQLITE_ENABLE_STAT4</a>.
1068 The <a href="compile.html#enable_stat3">SQLITE_ENABLE_STAT3</a> and <a href="compile.html#enable_stat4">SQLITE_ENABLE_STAT4</a> options causes
1069 the <a href="lang_analyze.html">ANALYZE</a> command to collect a histogram of column content in the
1070 <a href="fileformat2.html#stat3tab">sqlite_stat3</a> or <a href="fileformat2.html#stat4tab">sqlite_stat4</a> tables and to use this histogram to
1071 make a better guess at the best query to use for range constraints
1072 such as the above. The main difference between STAT3 and STAT4 is
1073 that STAT3 records histogram data for only the left-most column of
1074 an index whereas STAT4 records histogram data for all columns of an
1075 index. For single-column indexes, STAT3 and STAT4 work the same.
1076
1077 </p><p>
1078 The histogram data is only useful if the right-hand side of the constraint
1079 is a simple compile-time constant or <a href="lang_expr.html#varparam">parameter</a> and not an expression.
1080
1081 </p><p>
1082 Another limitation of the histogram data is that it only applies to the
1083 left-most column on an index. Consider this scenario:
1084
1085 </p><div class="codeblock"><pre>CREATE TABLE ex3(w,x,y,z);
1086 CREATE INDEX ex3i1 ON ex2(w, x);
1087 CREATE INDEX ex3i2 ON ex2(w, y);
1088 SELECT z FROM ex3 WHERE w=5 AND x BETWEEN 1 AND 100 AND y BETWEEN 1 AND 100;
1089 </pre></div>
1090 <p>
1091 Here the inequalities are on columns x and y which are not the
1092 left-most index columns. Hence, the histogram data which is collected no
1093 left-most column of indexes is useless in helping to choose between the
1094 range constraints on columns x and y.
1095
1096 <a name="covidx"></a>
1097
1098 </p><h1 id="covering_indexes"><span>9. </span>Covering Indexes</h1>
1099
1100 <p>
1101 When doing an indexed lookup of a row, the usual procedure is to
1102 do a binary search on the index to find the index entry, then extract
1103 the <a href="lang_createtable.html#rowid">rowid</a> from the index and use that <a href="lang_createtable.html#rowid">rowid</a> to do a binary search on
1104 the original table. Thus a typical indexed lookup involves two
1105 binary searches.
1106 If, however, all columns that were to be fetched from the table are
1107 already available in the index itself, SQLite will use the values
1108 contained in the index and will never look up the original table
1109 row. This saves one binary search for each row and can make many
1110 queries run twice as fast.
1111
1112 </p><p>
1113 When an index contains all of the data needed for a query and when the
1114 original table never needs to be consulted, we call that index a
1115 "covering index".
1116
1117 <a name="order_by"></a>
1118
1119 </p><h1 id="order_by_optimizations"><span>10. </span>ORDER BY Optimizations</h1>
1120
1121 <p>
1122 SQLite attempts to use an index to satisfy the ORDER BY clause of a
1123 query when possible.
1124 When faced with the choice of using an index to satisfy WHERE clause
1125 constraints or satisfying an ORDER BY clause, SQLite does the same
1126 cost analysis described above
1127 and chooses the index that it believes will result in the fastest answer.
1128
1129 </p><p>
1130 SQLite will also attempt to use indexes to help satisfy GROUP BY clauses
1131 and the DISTINCT keyword. If the nested loops of the join can be arranged
1132 such that rows that are equivalent for the GROUP BY or for the DISTINCT are
1133 consecutive, then the GROUP BY or DISTINCT logic can determine if the
1134 current row is part of the same group or if the current row is distinct
1135 simply by comparing the current row to the previous row.
1136 This can be much faster than the alternative of comparing each row to
1137 all prior rows.
1138
1139 <a name="partsort"></a>
1140
1141 </p><h2 id="partial_order_by_via_index"><span>10.1. </span>Partial ORDER BY via Index</h2>
1142
1143 <p>
1144 If a query contains an ORDER BY clause with multiple terms, it might
1145 be that SQLite can use indexes to cause rows to come out in the order
1146 of some prefix of the terms in the ORDER BY but that later terms in
1147 the ORDER BY are not satisfied. In that case, SQLite does block sorting.
1148 Suppose the ORDER BY clause has four terms and the natural order of the
1149 query results in rows appearing in order of the first two terms. As
1150 each row is output by the query engine and enters the sorter, the
1151 outputs in the current row corresponding to the first two terms of
1152 the ORDER BY are compared against the previous row. If they have
1153 changed, the current sort is finished and output and a new sort is
1154 started. This results in a slightly faster sort. Even bigger
1155 advantages are that many fewer rows need to be held in memory,
1156 reducing memory requirements, and outputs can begin to appear before
1157 the core query has run to completion.
1158
1159 <a name="flattening"></a>
1160
1161 </p><h1 id="subquery_flattening"><span>11. </span>Subquery Flattening</h1>
1162
1163 <p>
1164 When a subquery occurs in the FROM clause of a SELECT, the simplest
1165 behavior is to evaluate the subquery into a transient table, then run
1166 the outer SELECT against the transient table. Such a plan
1167 can be suboptimal since the transient table will not have any indexes
1168 and the outer query (which is likely a join) will be forced to either
1169 do full table scan on the transient table or else construct a
1170 <a href="optoverview.html#autoindex">query-time index</a> on the transient table, neither or which is likely
1171 to be particularly fast.
1172
1173 </p><p>
1174 To overcome this problem, SQLite attempts to flatten subqueries in
1175 the FROM clause of a SELECT.
1176 This involves inserting the FROM clause of the subquery into the
1177 FROM clause of the outer query and rewriting expressions in
1178 the outer query that refer to the result set of the subquery.
1179 For example:
1180
1181 </p><div class="codeblock"><pre>SELECT t1.a, t2.b FROM t2, (SELECT x+y AS a FROM t1 WHERE z&lt;100) WHERE a&gt;5
1182 </pre></div>
1183 <p>
1184 Would be rewritten using query flattening as:
1185
1186 </p><div class="codeblock"><pre>SELECT t1.x+t1.y AS a, t2.b FROM t2, t1 WHERE z&lt;100 AND a&gt;5
1187 </pre></div>
1188 <p>
1189 There is a long list of conditions that must all be met in order for
1190 query flattening to occur. Some of the constraints are marked as
1191 obsolete by italic text. These extra constraints are retained in the
1192 documentation to preserve the numbering of the other constraints.
1193
1194 </p><p>
1195 Casual readers are not expected to understand all of these rules.
1196 The point here is that flattening rules are subtle and complex.
1197 There have been multiple bugs over the years caused by
1198 over-aggressive query flattening. On the other hand, performance
1199 of complex queries and/or queries involving views tends to suffer
1200 if query flattening is more conservative.
1201
1202 </p><p>
1203 </p><ol>
1204 <li value="1"> <i>(Obsolete)</i>
1205 </li><li value="2"> <i>(Obsolete)</i>
1206 </li><li value="3">
1207 If the subquery is the right operand of a LEFT JOIN then
1208 <ol type="a"><li> the subquery may not be a join, and
1209 </li><li> the FROM clause of the subquery may
1210 not contain a virtual table, and
1211 </li><li> the outer query may not be DISTINCT.</li></ol>
1212 </li><li value="4"> The subquery is not DISTINCT.
1213 </li><li value="5"> <i>(Obsolete - subsumed into constraint 4)</i>
1214 </li><li value="6"> <i>(Obsolete)</i>
1215 </li><li value="7"> The subquery has a FROM clause.
1216 </li><li value="8"> The subquery does not use LIMIT or the outer query is
1217 not a join.
1218 </li><li value="9"> The subquery does not use LIMIT or the outer query
1219 does not use aggregates.
1220 </li><li value="10"> <i>(Obsolete)</i>
1221 </li><li value="11">
1222 The subquery and the outer query do not both have ORDER BY clauses.
1223 </li><li value="12"> <i>(Obsolete - subsumed into constraint 3)</i>
1224 </li><li value="13"> The subquery and outer query do not both use LIMIT.
1225 </li><li value="14"> The subquery does not use OFFSET.
1226 </li><li value="15">
1227 If the outer query is part of a compound select, then the
1228 subquery may not have a LIMIT clause.
1229
1230 </li><li value="16">
1231 If the outer query is an aggregate, then the subquery may
1232 not contain ORDER BY.
1233
1234 </li><li value="17">
1235 If the sub-query is a compound SELECT, then
1236 <ol type="a">
1237 <li> all compound operators must be UNION ALL, and
1238 </li><li> no terms with the subquery compound may be aggregate
1239 or DISTINCT, and
1240 </li><li> every term within the subquery must have a FROM clause, and
1241 </li><li> the outer query may not be an aggregateor DISTINCT query.
1242 </li><li> the subquery may not contain window functions.
1243 </li><li> the subquery must not be the right-hand side of a LEFT JOIN.
1244 </li><li> either the subquery is the first element of the outer query
1245 or there are not RIGHT or FULL JOINs in any arm of the subquery.
1246 </li><li> the corresponding result set expressions in all arms of the
1247 compound subquery must have the same <a href="datatype3.html#affinity">affinity</a>.
1248 </li></ol>
1249
1250 The parent and sub-query may contain WHERE clauses. Subject to
1251 rules (11), (12) and (13), they may also contain ORDER BY,
1252 LIMIT and OFFSET clauses.
1253
1254 </li><li value="18">
1255 If the sub-query is a compound select, then all terms of the
1256 ORDER by clause of the parent must be simple references to
1257 columns of the sub-query.
1258
1259 </li><li value="19">
1260 If the subquery uses LIMIT then the outer query may not
1261 have a WHERE clause.
1262
1263 </li><li value="20">
1264 If the sub-query is a compound select, then it must not use
1265 an ORDER BY clause.
1266
1267 </li><li value="21">
1268 If the subquery uses LIMIT, then the outer query may not be
1269 DISTINCT.
1270
1271 </li><li value="22"> The subquery may not be a recursive CTE.
1272
1273 </li><li value="23"> If the outer query is a recursive CTE, then the sub-query
1274 may not be a compound query.
1275
1276 </li><li value="24"> <i>(Obsolete)</i>
1277
1278 </li><li value="25"> Neither the subquery nor the outer query may contain
1279 a <a href="windowfunctions.html">window function</a> in the result set nor the ORDER BY clause.
1280
1281 </li><li value="26"> The subquery may not be the right operand of a RIGHT
1282 or FULL OUTER JOIN.
1283 </li><li value="27"> The subquery may not contain a FULL or RIGHT JOIN unless it
1284 is the first element of the parent query. Two subcases:
1285 <ol type="a">
1286 <li> the subquery is not a compound query.
1287 </li><li> the subquery is a compound query and the RIGHT JOIN occurs
1288 in any arm of the compound query. (See also (17g)).
1289 </li></ol>
1290 </li><li value="28"> The subquery is not a MATERIALIZED CTE.
1291 </li></ol>
1292
1293
1294 <p>
1295 Query flattening is an important optimization when views are used as
1296 each use of a view is translated into a subquery.
1297
1298 <a name="coroutines"></a>
1299
1300 </p><h1 id="subquery_co_routines"><span>12. </span>Subquery Co-routines</h1>
1301
1302 <p>
1303 SQLite implements FROM-clause subqueries in one of three ways:
1304 </p><ol>
1305 <li> <a href="optoverview.html#flattening">Flatten</a> the subquery into its outer query
1306 </li><li> Evaluate the subquery into a transient table that exists for
1307 the duration of the one SQL statement that is being evaluated,
1308 then run the outer query against that transient table.
1309 </li><li> Evaluate the subquery in a co-routine that runs in parallel with
1310 the outer query, providing rows to the outer query as needed.
1311 </li></ol>
1312
1313 <p>
1314 This section describes the third technique: implementing the subquery
1315 as a co-routine.
1316
1317 </p><p>
1318 A co-routine is like a subroutine in that it runs in the same thread
1319 as the caller and eventually returns control back to the caller. The
1320 difference is that a co-routine also has the ability to return
1321 before it has finished, and then resume where it left off the next
1322 time it is called.
1323
1324 </p><p>
1325 When a subquery is implemented as a co-routine, byte-code is generated
1326 to implement the subquery as if it were a standalone query, except
1327 instead of returning rows of results back to the application, the
1328 co-routine yields control back to the caller after each row is computed.
1329 The caller can then use that one computed row as part of its computation,
1330 then invoke the co-routine again when it is ready for the next row.
1331
1332 </p><p>
1333 Co-routines are better than storing the complete result set of the subquery
1334 in a transient table because co-routines use less memory. With a co-routine,
1335 only a single row of the result needs to be remembered, whereas all rows of
1336 the result must be stored for a transient table. Also, because the
1337 co-routine does not need to run to completion before the outer query
1338 begins its work, the first rows of output can appear much sooner, and if
1339 the overall query is abandoned before it has finished, less work is done
1340 overall.
1341
1342 </p><p>
1343 On the other hand, if the result of the subquery must be scanned multiple
1344 times (because, for example, it is just one table in a join) then it
1345 is better to use a transient table to remember the entire result of the
1346 subquery, in order to avoid computing the subquery more than once.
1347
1348 <a name="deferred_work"></a>
1349
1350 </p><h2 id="using_co_routines_to_defer_work_until_after_the_sorting"><span>12.1. </span>Using Co-routines to Defer Work until after the Sorting</h2>
1351
1352 <p>
1353 As of SQLite version 3.21.0 (2017-10-24), the query planner will
1354 always prefer to use a co-routine to implement FROM-clause subqueries
1355 that contains an ORDER BY clause and that are not part of a join when
1356 the result set of the outer query is "complex". This feature allows
1357 applications to shift expensive computations from before the
1358 sorter until after the sorter, which can result in faster operation.
1359 For example, consider this query:
1360
1361 </p><div class="codeblock"><pre>SELECT expensive_function(a) FROM tab ORDER BY date DESC LIMIT 5;
1362 </pre></div>
1363 <p>
1364 The goal of this query is to compute some value for the five most
1365 recent entries in the table. In the query above, the
1366 "expensive_function()" is invoked prior to the sort and thus is
1367 invoked on every row of the table, even
1368 rows that are ultimately omitted due to the LIMIT clause.
1369 A co-routine can be used to work around this:
1370
1371 </p><div class="codeblock"><pre>SELECT expensive_function(a) FROM (
1372 SELECT a FROM tab ORDER BY date DESC LIMIT 5
1373 );
1374 </pre></div>
1375 <p>
1376 In the revised query, the subquery implemented by a co-routine computes
1377 the five most recent values for "a". Those five values are passed from the
1378 co-routine up into the outer query where the "expensive_function()" is
1379 invoked on only the specific rows that the application cares about.
1380
1381 </p><p>
1382 The query planner in future versions of SQLite might grow smart enough
1383 to make transformations such as the above automatically, in both directions.
1384 That is to say, future versions of SQLite might transform queries of the
1385 first form into the second, or queries written the second way into the
1386 first. As of SQLite version 3.22.0 (2018-01-22), the query planner
1387 will flatten the subquery if the outer query does not make use of any
1388 user-defined functions or subqueries in its result set. For the examples
1389 shown above, however, SQLite implements each of the queries as
1390 written.
1391
1392 <a name="minmax"></a>
1393
1394 </p><h1 id="the_min_max_optimization"><span>13. </span>The MIN/MAX Optimization</h1>
1395
1396 <p>
1397 Queries that contain a single MIN() or MAX() aggregate function whose
1398 argument is the left-most column of an index might be satisfied
1399 by doing a single index lookup rather than by scanning the entire table.
1400 Examples:
1401
1402 </p><div class="codeblock"><pre>SELECT MIN(x) FROM table;
1403 SELECT MAX(x)+1 FROM table;
1404 </pre></div>
1405
1406 <a name="autoindex"></a>
1407
1408 <h1 id="automatic_query_time_indexes"><span>14. </span>Automatic Query-Time Indexes</h1>
1409
1410 <p>
1411 When no indexes are available to aid the evaluation of a query, SQLite
1412 might create an automatic index that lasts only for the duration
1413 of a single SQL statement.
1414 Automatic indexes are also sometimes called "Query-time indexes".
1415 Since the cost of constructing the automatic or query-time index is
1416 O(NlogN) (where N is the number of entries in the table) and the cost of
1417 doing a full table scan is only O(N), an automatic index will
1418 only be created if SQLite expects that the lookup will be run more than
1419 logN times during the course of the SQL statement. Consider an example:
1420
1421 </p><div class="codeblock"><pre>CREATE TABLE t1(a,b);
1422 CREATE TABLE t2(c,d);
1423 -- Insert many rows into both t1 and t2
1424 SELECT * FROM t1, t2 WHERE a=c;
1425 </pre></div>
1426 <p>
1427 In the query above, if both t1 and t2 have approximately N rows, then
1428 without any indexes the query will require O(N*N) time. On the other
1429 hand, creating an index on table t2 requires O(NlogN) time and using
1430 that index to evaluate the query requires an additional O(NlogN) time.
1431 In the absence of <a href="lang_analyze.html">ANALYZE</a> information, SQLite guesses that N is one
1432 million and hence it believes that constructing the automatic index will
1433 be the cheaper approach.
1434
1435 </p><p>
1436 An automatic query-time index might also be used for a subquery:
1437
1438 </p><div class="codeblock"><pre>CREATE TABLE t1(a,b);
1439 CREATE TABLE t2(c,d);
1440 -- Insert many rows into both t1 and t2
1441 SELECT a, (SELECT d FROM t2 WHERE c=b) FROM t1;
1442 </pre></div>
1443 <p>
1444 In this example, the t2 table is used in a subquery to translate values
1445 of the t1.b column. If each table contains N rows, SQLite expects that
1446 the subquery will run N times, and hence it will believe it is faster
1447 to construct an automatic, transient index on t2 first and then use
1448 that index to satisfy the N instances of the subquery.
1449
1450 </p><p>
1451 The automatic indexing capability can be disabled at run-time using
1452 the <a href="pragma.html#pragma_automatic_index">automatic_index pragma</a>. Automatic indexing is turned on by
1453 default, but this can be changed so that automatic indexing is off
1454 by default using the <a href="compile.html#default_automatic_index">SQLITE_DEFAULT_AUTOMATIC_INDEX</a> compile-time option.
1455 The ability to create automatic indexes can be completely disabled by
1456 compiling with the <a href="compile.html#omit_automatic_index">SQLITE_OMIT_AUTOMATIC_INDEX</a> compile-time option.
1457
1458 </p><p>
1459 In SQLite <a href="releaselog/3_8_0.html">version 3.8.0</a> (2013-08-26) and later,
1460 an <a href="rescode.html#warning_autoindex">SQLITE_WARNING_AUTOINDEX</a> message is sent
1461 to the <a href="errlog.html">error log</a> every time a statement is prepared that uses an
1462 automatic index. Application developers can and should use these warnings
1463 to identify the need for new persistent indexes in the schema.
1464
1465 </p><p>
1466 Do not confuse automatic indexes with the <a href="fileformat2.html#intschema">internal indexes</a> (having names
1467 like "sqlite_autoindex_<i>table</i>_<i>N</i>") that are sometimes
1468 created to implement a <a href="lang_createtable.html#primkeyconst">PRIMARY KEY constraint</a> or <a href="lang_createtable.html#uniqueconst">UNIQUE constraint</a>.
1469 The automatic indexes described here exist only for the duration of a
1470 single query, are never persisted to disk, and are only visible to a
1471 single database connection. Internal indexes are part of the implementation
1472 of PRIMARY KEY and UNIQUE constraints, are long-lasting and persisted
1473 to disk, and are visible to all database connections. The term "autoindex"
1474 appears in the names of <a href="fileformat2.html#intschema">internal indexes</a> for legacy reasons and does
1475 not indicate that internal indexes and automatic indexes are related.
1476
1477 <a name="hashjoin"></a>
1478
1479 </p><h2 id="hash_joins"><span>14.1. </span>Hash Joins</h2>
1480
1481 <p>
1482 An automatic index is almost the same thing as a
1483 <a href="https://en.wikipedia.org/wiki/Hash_join">hash join</a>. The only difference
1484 is that a B-Tree is used instead of a hash table. If you are willing to
1485 say that the transient B-Tree constructed for an automatic index is
1486 really just a fancy hash table, then a query that uses an automatic
1487 index is just a hash join.
1488
1489 </p><p>
1490 SQLite constructs a transient index instead of a hash table in this
1491 instance because it already has a robust and high performance B-Tree
1492 implementation at hand, whereas a hash-table would need to be added.
1493 Adding a separate hash table implementation to handle this one case
1494 would increase the size of the library (which is designed for use on
1495 low-memory embedded devices) for minimal performance gain. SQLite might
1496 be enhanced with a hash-table implementation someday, but for now it seems
1497 better to continue using automatic indexes in cases where client/server
1498 database engines might use a hash join.
1499
1500 <a name="pushdown"></a>
1501
1502 </p><h1 id="the_predicate_push_down_optimization"><span>15. </span>The Predicate Push-Down Optimization</h1>
1503 <p>
1504 If a subquery cannot be <a href="optoverview.html#flattening">flattened</a> into the outer query, it might
1505 still be possible to enhance performance by "pushing down" WHERE clause
1506 terms from the outer query into the subquery. Consider an example:
1507
1508 </p><div class="codeblock"><pre>CREATE TABLE t1(a INT, b INT);
1509 CREATE TABLE t2(x INT, y INT);
1510 CREATE VIEW v1(a,b) AS SELECT DISTINCT a, b FROM t1;
1511
1512 SELECT x, y, b
1513 FROM t2 JOIN v1 ON (x=a)
1514 WHERE b BETWEEN 10 AND 20;
1515 </pre></div>
1516
1517 <p>
1518 The view v1 cannot be <a href="optoverview.html#flattening">flattened</a> because it is DISTINCT. It must
1519 instead be run as a subquery with the results being stored in a
1520 transient table, then the join is performed between t2 and the
1521 transient table. The push-down optimization pushes down the
1522 "b BETWEEN 10 AND 20" term into the view. This makes the transient
1523 table smaller, and helps the subquery to run faster if there
1524 is an index on t1.b. The resulting evaluation is like this:
1525
1526 </p><div class="codeblock"><pre>SELECT x, y, b
1527 FROM t2
1528 JOIN (SELECT DISTINCT a, b FROM t1 WHERE b BETWEEN 10 AND 20)
1529 WHERE b BETWEEN 10 AND 20;
1530 </pre></div>
1531
1532 <p>
1533 The WHERE-clause push-down optimization cannot always be used. For example,
1534 if the subquery contains a LIMIT, then pushing down any part of
1535 the WHERE clause from the outer query could change the result of
1536 the inner query. There are other restrictions, explained in a
1537 comment in the source code on the pushDownWhereTerms() routine
1538 that implements this optimization.
1539
1540 </p><p>
1541 Do not confuse this optimization with the optimization by a similar name
1542 in MySQL. The MySQL push-down optimization changes the order of evaluation
1543 of WHERE-clause constraints such that those that can be evaluated using
1544 only the index and without having to find the corresponding table row are
1545 evaluated first, thus avoiding an unnecessary table row lookup if the
1546 constraint fails. For disambiguation, SQLite calls this the
1547 "MySQL push-down optimization". SQLite does do the MySQL push-down
1548 optimization too, in addition to the WHERE-clause push-down optimization.
1549 But the focus of this section is the WHERE-clause push-down optimization.
1550
1551 <a name="leftjoinreduction"></a>
1552
1553 </p><h1 id="the_outer_join_strength_reduction_optimization"><span>16. </span>The OUTER JOIN Strength Reduction Optimization</h1>
1554
1555 <p>
1556 An OUTER JOIN (either a LEFT JOIN, a RIGHT JOIN, or a FULL JOIN)
1557 can sometimes be simplified. A LEFT or RIGHT JOIN can be converted
1558 into an ordinary (INNER) JOIN, or a FULL JOIN might be converted into
1559 either a LEFT or a RIGHT JOIN. This can happen if there are terms
1560 in the WHERE clause that guarantee the same result after simplification.
1561 For example, if any
1562 column in the right-hand table of the LEFT JOIN must be non-NULL
1563 in order for the WHERE clause to be true, then the LEFT JOIN is
1564 demoted to an ordinary JOIN.
1565
1566 </p><p>
1567 The theorem prover that determines whether a join can be simplified is
1568 imperfect. It sometimes returns a false negative. In other words,
1569 it sometimes fails to prove that reducing the strength of an OUTER JOIN
1570 is safe when in fact it is safe.
1571 For example, the prover does not know
1572 the <a href="lang_datefunc.html#dttm">datetime() SQL function</a> will always return NULL if its first
1573 argument is NULL, and so it will not recognize that the LEFT JOIN
1574 in the following query could be strength-reduced:
1575
1576 </p><div class="codeblock"><pre>SELECT urls.url
1577 FROM urls
1578 LEFT JOIN
1579 (SELECT *
1580 FROM (SELECT url_id AS uid, max(retrieval_time) AS rtime
1581 FROM lookups GROUP BY 1 ORDER BY 1)
1582 WHERE uid IN (358341,358341,358341)
1583 ) recent
1584 ON u.source_seed_id = recent.xyz OR u.url_id = recent.xyz
1585 WHERE
1586 DATETIME(recent.rtime) > DATETIME('now', '-5 days');
1587 </pre></div>
1588
1589 <p>
1590 It is possible that future enhancements to the prover might enable it
1591 to recognize that NULL inputs to certain built-in functions
1592 always result in a NULL answer. However, not all built-in
1593 functions have that property (for example <a href="lang_corefunc.html#coalesce">coalesce()</a>) and, of
1594 course, the prover will never be able to reason about
1595 <a href="appfunc.html">application-defined SQL functions</a>.
1596
1597 <a name="omitnoopjoin"></a>
1598
1599 </p><h1 id="the_omit_outer_join_optimization"><span>17. </span>The Omit OUTER JOIN Optimization</h1>
1600
1601 <p>
1602 Sometimes a LEFT or RIGHT JOIN can be completely omitted from a query without
1603 changing the result. This can happen if all of the following are
1604 true:
1605
1606 </p><p>
1607 </p><ol>
1608 <li> The query is not an aggregate
1609 </li><li> Either the query is DISTINCT or else the ON or USING clause
1610 on the OUTER JOIN constrains the join such that it matches
1611 only a single row
1612 </li><li> The right-hand table of the LEFT JOIN or the left-hand table of
1613 a RIGHT JOIN is not be used anywhere
1614 in the query outside of its own USING or ON clause.
1615 </li></ol>
1616
1617 <p>
1618 OUTER JOIN elimination often comes up when OUTER JOINs are used
1619 inside of views, and then the view is used in such as way that
1620 none of the columns on the right-hand table of the LEFT JOIN or
1621 on the left-hand table of a RIGHT JOIN are referenced.
1622
1623 </p><p>
1624 Here is a simple example of omitting a LEFT JOIN:
1625
1626 </p><div class="codeblock"><pre>CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
1627 CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
1628 CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
1629
1630 SELECT v1, v3 FROM t1
1631 LEFT JOIN t2 ON (t1.ipk=t2.ipk)
1632 LEFT JOIN t3 ON (t1.ipk=t3.ipk)
1633 </pre></div>
1634
1635 <p>
1636 The t2 table is completely unused in the query above, and so the
1637 query planner is able to implement the query as if it were written:
1638
1639 </p><div class="codeblock"><pre>SELECT v1, v3 FROM t1
1640 LEFT JOIN t3 ON (t1.ipk=t3.ipk)
1641 </pre></div>
1642
1643 <p>
1644 As of this writing, only LEFT JOINs are eliminated. This optimize
1645 has not yet been generalized to work with RIGHT JOINs as RIGHT JOIN
1646 is a relatively new addition to SQLite. That asymmetry will probably
1647 be corrected in a future release.
1648
1649
1650 <a name="constprop"></a>
1651
1652 </p><h1 id="the_constant_propagation_optimization"><span>18. </span>The Constant Propagation Optimization</h1>
1653
1654 <p>
1655 When a WHERE clause contains two or more equality constraints connected
1656 by the AND operator such that all of the <a href="datatype3.html#affinity">affinities</a> of the various
1657 constraints are the same, then SQLite might use the transitive property
1658 of equality to construct new "virtual" constraints that can be used to
1659 simplify expressions and/or improve performance. This is called the
1660 "constant-propagation optimization".
1661
1662 </p><p>
1663 For example, consider the following schema and query:
1664
1665 </p><div class="codeblock"><pre>CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT, c INT);
1666 SELECT * FROM t1 WHERE a=b AND b=5;
1667 </pre></div>
1668
1669 <p>
1670 SQLite looks at the "a=b" and "b=5" constraints and deduces that
1671 if those two constraints are true, then it must also be the case
1672 that "a=5" is true. This means that the desired row can be looked up
1673 quickly using a value of 5 for the INTEGER PRIMARY KEY.
1674 </p><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/optoverview.in?m=f3bc76d394">2024-07-24 12:16:13</a> UTC </small></i></p>
1675