aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl
diff options
context:
space:
mode:
authordan miller2007-10-20 02:49:29 +0000
committerdan miller2007-10-20 02:49:29 +0000
commite36d23a85ebff914d74bb541558c2b6082b78edb (patch)
tree54b58fdf162e78af64055282a6035c8d2443389d /libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl
parent* Fixed an issue whereby avatar chat distances were being calculated against ... (diff)
downloadopensim-SC-e36d23a85ebff914d74bb541558c2b6082b78edb.zip
opensim-SC-e36d23a85ebff914d74bb541558c2b6082b78edb.tar.gz
opensim-SC-e36d23a85ebff914d74bb541558c2b6082b78edb.tar.bz2
opensim-SC-e36d23a85ebff914d74bb541558c2b6082b78edb.tar.xz
sqlite source (unix build) added to libraries
Diffstat (limited to 'libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl')
-rw-r--r--libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl1988
1 files changed, 1988 insertions, 0 deletions
diff --git a/libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl b/libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl
new file mode 100644
index 0000000..ed0b712
--- /dev/null
+++ b/libraries/sqlite/unix/sqlite-3.5.1/www/vdbe.tcl
@@ -0,0 +1,1988 @@
1#
2# Run this Tcl script to generate the vdbe.html file.
3#
4set rcsid {$Id: vdbe.tcl,v 1.14 2005/03/12 15:55:11 drh Exp $}
5source common.tcl
6header {The Virtual Database Engine of SQLite}
7puts {
8<h2>The Virtual Database Engine of SQLite</h2>
9
10<blockquote><b>
11This document describes the virtual machine used in SQLite version 2.8.0.
12The virtual machine in SQLite version 3.0 and 3.1 is very similar in
13concept but many of the opcodes have changed and the algorithms are
14somewhat different. Use this document as a rough guide to the idea
15behind the virtual machine in SQLite version 3, not as a reference on
16how the virtual machine works.
17</b></blockquote>
18}
19
20puts {
21<p>If you want to know how the SQLite library works internally,
22you need to begin with a solid understanding of the Virtual Database
23Engine or VDBE. The VDBE occurs right in the middle of the
24processing stream (see the <a href="arch.html">architecture diagram</a>)
25and so it seems to touch most parts of the library. Even
26parts of the code that do not directly interact with the VDBE
27are usually in a supporting role. The VDBE really is the heart of
28SQLite.</p>
29
30<p>This article is a brief introduction to how the VDBE
31works and in particular how the various VDBE instructions
32(documented <a href="opcode.html">here</a>) work together
33to do useful things with the database. The style is tutorial,
34beginning with simple tasks and working toward solving more
35complex problems. Along the way we will visit most
36submodules in the SQLite library. After completeing this tutorial,
37you should have a pretty good understanding of how SQLite works
38and will be ready to begin studying the actual source code.</p>
39
40<h2>Preliminaries</h2>
41
42<p>The VDBE implements a virtual computer that runs a program in
43its virtual machine language. The goal of each program is to
44interrogate or change the database. Toward this end, the machine
45language that the VDBE implements is specifically designed to
46search, read, and modify databases.</p>
47
48<p>Each instruction of the VDBE language contains an opcode and
49three operands labeled P1, P2, and P3. Operand P1 is an arbitrary
50integer. P2 is a non-negative integer. P3 is a pointer to a data
51structure or null-terminated string, possibly null. Only a few VDBE
52instructions use all three operands. Many instructions use only
53one or two operands. A significant number of instructions use
54no operands at all but instead take their data and store their results
55on the execution stack. The details of what each instruction
56does and which operands it uses are described in the separate
57<a href="opcode.html">opcode description</a> document.</p>
58
59<p>A VDBE program begins
60execution on instruction 0 and continues with successive instructions
61until it either (1) encounters a fatal error, (2) executes a
62Halt instruction, or (3) advances the program counter past the
63last instruction of the program. When the VDBE completes execution,
64all open database cursors are closed, all memory is freed, and
65everything is popped from the stack.
66So there are never any worries about memory leaks or
67undeallocated resources.</p>
68
69<p>If you have done any assembly language programming or have
70worked with any kind of abstract machine before, all of these
71details should be familiar to you. So let's jump right in and
72start looking as some code.</p>
73
74<a name="insert1">
75<h2>Inserting Records Into The Database</h2>
76
77<p>We begin with a problem that can be solved using a VDBE program
78that is only a few instructions long. Suppose we have an SQL
79table that was created like this:</p>
80
81<blockquote><pre>
82CREATE TABLE examp(one text, two int);
83</pre></blockquote>
84
85<p>In words, we have a database table named "examp" that has two
86columns of data named "one" and "two". Now suppose we want to insert a single
87record into this table. Like this:</p>
88
89<blockquote><pre>
90INSERT INTO examp VALUES('Hello, World!',99);
91</pre></blockquote>
92
93<p>We can see the VDBE program that SQLite uses to implement this
94INSERT using the <b>sqlite</b> command-line utility. First start
95up <b>sqlite</b> on a new, empty database, then create the table.
96Next change the output format of <b>sqlite</b> to a form that
97is designed to work with VDBE program dumps by entering the
98".explain" command.
99Finally, enter the INSERT statement shown above, but precede the
100INSERT with the special keyword "EXPLAIN". The EXPLAIN keyword
101will cause <b>sqlite</b> to print the VDBE program rather than
102execute it. We have:</p>
103}
104proc Code {body} {
105 puts {<blockquote><tt>}
106 regsub -all {&} [string trim $body] {\&amp;} body
107 regsub -all {>} $body {\&gt;} body
108 regsub -all {<} $body {\&lt;} body
109 regsub -all {\(\(\(} $body {<b>} body
110 regsub -all {\)\)\)} $body {</b>} body
111 regsub -all { } $body {\&nbsp;} body
112 regsub -all \n $body <br>\n body
113 puts $body
114 puts {</tt></blockquote>}
115}
116
117Code {
118$ (((sqlite test_database_1)))
119sqlite> (((CREATE TABLE examp(one text, two int);)))
120sqlite> (((.explain)))
121sqlite> (((EXPLAIN INSERT INTO examp VALUES('Hello, World!',99);)))
122addr opcode p1 p2 p3
123---- ------------ ----- ----- -----------------------------------
1240 Transaction 0 0
1251 VerifyCookie 0 81
1262 Transaction 1 0
1273 Integer 0 0
1284 OpenWrite 0 3 examp
1295 NewRecno 0 0
1306 String 0 0 Hello, World!
1317 Integer 99 0 99
1328 MakeRecord 2 0
1339 PutIntKey 0 1
13410 Close 0 0
13511 Commit 0 0
13612 Halt 0 0
137}
138
139puts {<p>As you can see above, our simple insert statement is
140implemented in 12 instructions. The first 3 and last 2 instructions are
141a standard prologue and epilogue, so the real work is done in the middle
1427 instructions. There are no jumps, so the program executes once through
143from top to bottom. Let's now look at each instruction in detail.<p>
144}
145
146Code {
1470 Transaction 0 0
1481 VerifyCookie 0 81
1492 Transaction 1 0
150}
151puts {
152<p>The instruction <a href="opcode.html#Transaction">Transaction</a>
153begins a transaction. The transaction ends when a Commit or Rollback
154opcode is encountered. P1 is the index of the database file on which
155the transaction is started. Index 0 is the main database file. A write
156lock is obtained on the database file when a transaction is started.
157No other process can read or write the file while the transaction is
158underway. Starting a transaction also creates a rollback journal. A
159transaction must be started before any changes can be made to the
160database.</p>
161
162<p>The instruction <a href="opcode.html#VerifyCookie">VerifyCookie</a>
163checks cookie 0 (the database schema version) to make sure it is equal
164to P2 (the value obtained when the database schema was last read).
165P1 is the database number (0 for the main database). This is done to
166make sure the database schema hasn't been changed by another thread, in
167which case it has to be reread.</p>
168
169<p> The second <a href="opcode.html#Transaction">Transaction</a>
170instruction begins a transaction and starts a rollback journal for
171database 1, the database used for temporary tables.</p>
172}
173
174proc stack args {
175 puts "<blockquote><table border=2>"
176 foreach elem $args {
177 puts "<tr><td align=left>$elem</td></tr>"
178 }
179 puts "</table></blockquote>"
180}
181
182Code {
1833 Integer 0 0
1844 OpenWrite 0 3 examp
185}
186puts {
187<p> The instruction <a href="opcode.html#Integer">Integer</a> pushes
188the integer value P1 (0) onto the stack. Here 0 is the number of the
189database to use in the following OpenWrite instruction. If P3 is not
190NULL then it is a string representation of the same integer. Afterwards
191the stack looks like this:</p>
192}
193stack {(integer) 0}
194
195puts {
196<p> The instruction <a href="opcode.html#OpenWrite">OpenWrite</a> opens
197a new read/write cursor with handle P1 (0 in this case) on table "examp",
198whose root page is P2 (3, in this database file). Cursor handles can be
199any non-negative integer. But the VDBE allocates cursors in an array
200with the size of the array being one more than the largest cursor. So
201to conserve memory, it is best to use handles beginning with zero and
202working upward consecutively. Here P3 ("examp") is the name of the
203table being opened, but this is unused, and only generated to make the
204code easier to read. This instruction pops the database number to use
205(0, the main database) from the top of the stack, so afterwards the
206stack is empty again.</p>
207}
208
209Code {
2105 NewRecno 0 0
211}
212puts {
213<p> The instruction <a href="opcode.html#NewRecno">NewRecno</a> creates
214a new integer record number for the table pointed to by cursor P1. The
215record number is one not currently used as a key in the table. The new
216record number is pushed onto the stack. Afterwards the stack looks like
217this:</p>
218}
219stack {(integer) new record key}
220
221Code {
2226 String 0 0 Hello, World!
223}
224puts {
225<p> The instruction <a href="opcode.html#String">String</a> pushes its
226P3 operand onto the stack. Afterwards the stack looks like this:</p>
227}
228stack {(string) "Hello, World!"} \
229 {(integer) new record key}
230
231Code {
2327 Integer 99 0 99
233}
234puts {
235<p> The instruction <a href="opcode.html#Integer">Integer</a> pushes
236its P1 operand (99) onto the stack. Afterwards the stack looks like
237this:</p>
238}
239stack {(integer) 99} \
240 {(string) "Hello, World!"} \
241 {(integer) new record key}
242
243Code {
2448 MakeRecord 2 0
245}
246puts {
247<p> The instruction <a href="opcode.html#MakeRecord">MakeRecord</a> pops
248the top P1 elements off the stack (2 in this case) and converts them into
249the binary format used for storing records in a database file.
250(See the <a href="fileformat.html">file format</a> description for
251details.) The new record generated by the MakeRecord instruction is
252pushed back onto the stack. Afterwards the stack looks like this:</p>
253</ul>
254}
255stack {(record) "Hello, World!", 99} \
256 {(integer) new record key}
257
258Code {
2599 PutIntKey 0 1
260}
261puts {
262<p> The instruction <a href="opcode.html#PutIntKey">PutIntKey</a> uses
263the top 2 stack entries to write an entry into the table pointed to by
264cursor P1. A new entry is created if it doesn't already exist or the
265data for an existing entry is overwritten. The record data is the top
266stack entry, and the key is the next entry down. The stack is popped
267twice by this instruction. Because operand P2 is 1 the row change count
268is incremented and the rowid is stored for subsequent return by the
269sqlite_last_insert_rowid() function. If P2 is 0 the row change count is
270unmodified. This instruction is where the insert actually occurs.</p>
271}
272
273Code {
27410 Close 0 0
275}
276puts {
277<p> The instruction <a href="opcode.html#Close">Close</a> closes a
278cursor previously opened as P1 (0, the only open cursor). If P1 is not
279currently open, this instruction is a no-op.</p>
280}
281
282Code {
28311 Commit 0 0
284}
285puts {
286<p> The instruction <a href="opcode.html#Commit">Commit</a> causes all
287modifications to the database that have been made since the last
288Transaction to actually take effect. No additional modifications are
289allowed until another transaction is started. The Commit instruction
290deletes the journal file and releases the write lock on the database.
291A read lock continues to be held if there are still cursors open.</p>
292}
293
294Code {
29512 Halt 0 0
296}
297puts {
298<p> The instruction <a href="opcode.html#Halt">Halt</a> causes the VDBE
299engine to exit immediately. All open cursors, Lists, Sorts, etc are
300closed automatically. P1 is the result code returned by sqlite_exec().
301For a normal halt, this should be SQLITE_OK (0). For errors, it can be
302some other value. The operand P2 is only used when there is an error.
303There is an implied "Halt 0 0 0" instruction at the end of every
304program, which the VDBE appends when it prepares a program to run.</p>
305
306
307<a name="trace">
308<h2>Tracing VDBE Program Execution</h2>
309
310<p>If the SQLite library is compiled without the NDEBUG preprocessor
311macro, then the PRAGMA <a href="pragma.html#pragma_vdbe_trace">vdbe_trace
312</a> causes the VDBE to trace the execution of programs. Though this
313feature was originally intended for testing and debugging, it can also
314be useful in learning about how the VDBE operates.
315Use "<tt>PRAGMA&nbsp;vdbe_trace=ON;</tt>" to turn tracing on and
316"<tt>PRAGMA&nbsp;vdbe_trace=OFF</tt>" to turn tracing back off.
317Like this:</p>
318}
319
320Code {
321sqlite> (((PRAGMA vdbe_trace=ON;)))
322 0 Halt 0 0
323sqlite> (((INSERT INTO examp VALUES('Hello, World!',99);)))
324 0 Transaction 0 0
325 1 VerifyCookie 0 81
326 2 Transaction 1 0
327 3 Integer 0 0
328Stack: i:0
329 4 OpenWrite 0 3 examp
330 5 NewRecno 0 0
331Stack: i:2
332 6 String 0 0 Hello, World!
333Stack: t[Hello,.World!] i:2
334 7 Integer 99 0 99
335Stack: si:99 t[Hello,.World!] i:2
336 8 MakeRecord 2 0
337Stack: s[...Hello,.World!.99] i:2
338 9 PutIntKey 0 1
339 10 Close 0 0
340 11 Commit 0 0
341 12 Halt 0 0
342}
343
344puts {
345<p>With tracing mode on, the VDBE prints each instruction prior
346to executing it. After the instruction is executed, the top few
347entries in the stack are displayed. The stack display is omitted
348if the stack is empty.</p>
349
350<p>On the stack display, most entries are shown with a prefix
351that tells the datatype of that stack entry. Integers begin
352with "<tt>i:</tt>". Floating point values begin with "<tt>r:</tt>".
353(The "r" stands for "real-number".) Strings begin with either
354"<tt>s:</tt>", "<tt>t:</tt>", "<tt>e:</tt>" or "<tt>z:</tt>".
355The difference among the string prefixes is caused by how their
356memory is allocated. The z: strings are stored in memory obtained
357from <b>malloc()</b>. The t: strings are statically allocated.
358The e: strings are ephemeral. All other strings have the s: prefix.
359This doesn't make any difference to you,
360the observer, but it is vitally important to the VDBE since the
361z: strings need to be passed to <b>free()</b> when they are
362popped to avoid a memory leak. Note that only the first 10
363characters of string values are displayed and that binary
364values (such as the result of the MakeRecord instruction) are
365treated as strings. The only other datatype that can be stored
366on the VDBE stack is a NULL, which is display without prefix
367as simply "<tt>NULL</tt>". If an integer has been placed on the
368stack as both an integer and a string, its prefix is "<tt>si:</tt>".
369
370
371<a name="query1">
372<h2>Simple Queries</h2>
373
374<p>At this point, you should understand the basics of how the VDBE
375writes to a database. Now let's look at how it does queries.
376We will use the following simple SELECT statement as our example:</p>
377
378<blockquote><pre>
379SELECT * FROM examp;
380</pre></blockquote>
381
382<p>The VDBE program generated for this SQL statement is as follows:</p>
383}
384
385Code {
386sqlite> (((EXPLAIN SELECT * FROM examp;)))
387addr opcode p1 p2 p3
388---- ------------ ----- ----- -----------------------------------
3890 ColumnName 0 0 one
3901 ColumnName 1 0 two
3912 Integer 0 0
3923 OpenRead 0 3 examp
3934 VerifyCookie 0 81
3945 Rewind 0 10
3956 Column 0 0
3967 Column 0 1
3978 Callback 2 0
3989 Next 0 6
39910 Close 0 0
40011 Halt 0 0
401}
402
403puts {
404<p>Before we begin looking at this problem, let's briefly review
405how queries work in SQLite so that we will know what we are trying
406to accomplish. For each row in the result of a query,
407SQLite will invoke a callback function with the following
408prototype:</p>
409
410<blockquote><pre>
411int Callback(void *pUserData, int nColumn, char *azData[], char *azColumnName[]);
412</pre></blockquote>
413
414<p>The SQLite library supplies the VDBE with a pointer to the callback function
415and the <b>pUserData</b> pointer. (Both the callback and the user data were
416originally passed in as arguments to the <b>sqlite_exec()</b> API function.)
417The job of the VDBE is to
418come up with values for <b>nColumn</b>, <b>azData[]</b>,
419and <b>azColumnName[]</b>.
420<b>nColumn</b> is the number of columns in the results, of course.
421<b>azColumnName[]</b> is an array of strings where each string is the name
422of one of the result columns. <b>azData[]</b> is an array of strings holding
423the actual data.</p>
424}
425
426Code {
4270 ColumnName 0 0 one
4281 ColumnName 1 0 two
429}
430puts {
431<p>The first two instructions in the VDBE program for our query are
432concerned with setting up values for <b>azColumn</b>.
433The <a href="opcode.html#ColumnName">ColumnName</a> instructions tell
434the VDBE what values to fill in for each element of the <b>azColumnName[]</b>
435array. Every query will begin with one ColumnName instruction for each
436column in the result, and there will be a matching Column instruction for
437each one later in the query.
438</p>
439}
440
441Code {
4422 Integer 0 0
4433 OpenRead 0 3 examp
4444 VerifyCookie 0 81
445}
446puts {
447<p>Instructions 2 and 3 open a read cursor on the database table that is
448to be queried. This works the same as the OpenWrite instruction in the
449INSERT example except that the cursor is opened for reading this time
450instead of for writing. Instruction 4 verifies the database schema as
451in the INSERT example.</p>
452}
453
454Code {
4555 Rewind 0 10
456}
457puts {
458<p> The <a href="opcode.html#Rewind">Rewind</a> instruction initializes
459a loop that iterates over the "examp" table. It rewinds the cursor P1
460to the first entry in its table. This is required by the the Column and
461Next instructions, which use the cursor to iterate through the table.
462If the table is empty, then jump to P2 (10), which is the instruction just
463past the loop. If the table is not empty, fall through to the following
464instruction at 6, which is the beginning of the loop body.</p>
465}
466
467Code {
4686 Column 0 0
4697 Column 0 1
4708 Callback 2 0
471}
472puts {
473<p> The instructions 6 through 8 form the body of the loop that will
474execute once for each record in the database file.
475
476The <a href="opcode.html#Column">Column</a> instructions at addresses 6
477and 7 each take the P2-th column from the P1-th cursor and push it onto
478the stack. In this example, the first Column instruction is pushing the
479value for the column "one" onto the stack and the second Column
480instruction is pushing the value for column "two".
481
482The <a href="opcode.html#Callback">Callback</a> instruction at address 8
483invokes the callback() function. The P1 operand to Callback becomes the
484value for <b>nColumn</b>. The Callback instruction pops P1 values from
485the stack and uses them to fill the <b>azData[]</b> array.</p>
486}
487
488Code {
4899 Next 0 6
490}
491puts {
492<p>The instruction at address 9 implements the branching part of the
493loop. Together with the Rewind at address 5 it forms the loop logic.
494This is a key concept that you should pay close attention to.
495The <a href="opcode.html#Next">Next</a> instruction advances the cursor
496P1 to the next record. If the cursor advance was successful, then jump
497immediately to P2 (6, the beginning of the loop body). If the cursor
498was at the end, then fall through to the following instruction, which
499ends the loop.</p>
500}
501
502Code {
50310 Close 0 0
50411 Halt 0 0
505}
506puts {
507<p>The Close instruction at the end of the program closes the
508cursor that points into the table "examp". It is not really necessary
509to call Close here since all cursors will be automatically closed
510by the VDBE when the program halts. But we needed an instruction
511for the Rewind to jump to so we might as well go ahead and have that
512instruction do something useful.
513The Halt instruction ends the VDBE program.</p>
514
515<p>Note that the program for this SELECT query didn't contain the
516Transaction and Commit instructions used in the INSERT example. Because
517the SELECT is a read operation that doesn't alter the database, it
518doesn't require a transaction.</p>
519}
520
521
522puts {
523<a name="query2">
524<h2>A Slightly More Complex Query</h2>
525
526<p>The key points of the previous example were the use of the Callback
527instruction to invoke the callback function, and the use of the Next
528instruction to implement a loop over all records of the database file.
529This example attempts to drive home those ideas by demonstrating a
530slightly more complex query that involves more columns of
531output, some of which are computed values, and a WHERE clause that
532limits which records actually make it to the callback function.
533Consider this query:</p>
534
535<blockquote><pre>
536SELECT one, two, one || two AS 'both'
537FROM examp
538WHERE one LIKE 'H%'
539</pre></blockquote>
540
541<p>This query is perhaps a bit contrived, but it does serve to
542illustrate our points. The result will have three column with
543names "one", "two", and "both". The first two columns are direct
544copies of the two columns in the table and the third result
545column is a string formed by concatenating the first and
546second columns of the table.
547Finally, the
548WHERE clause says that we will only chose rows for the
549results where the "one" column begins with an "H".
550Here is what the VDBE program looks like for this query:</p>
551}
552
553Code {
554addr opcode p1 p2 p3
555---- ------------ ----- ----- -----------------------------------
5560 ColumnName 0 0 one
5571 ColumnName 1 0 two
5582 ColumnName 2 0 both
5593 Integer 0 0
5604 OpenRead 0 3 examp
5615 VerifyCookie 0 81
5626 Rewind 0 18
5637 String 0 0 H%
5648 Column 0 0
5659 Function 2 0 ptr(0x7f1ac0)
56610 IfNot 1 17
56711 Column 0 0
56812 Column 0 1
56913 Column 0 0
57014 Column 0 1
57115 Concat 2 0
57216 Callback 3 0
57317 Next 0 7
57418 Close 0 0
57519 Halt 0 0
576}
577
578puts {
579<p>Except for the WHERE clause, the structure of the program for
580this example is very much like the prior example, just with an
581extra column. There are now 3 columns, instead of 2 as before,
582and there are three ColumnName instructions.
583A cursor is opened using the OpenRead instruction, just like in the
584prior example. The Rewind instruction at address 6 and the
585Next at address 17 form a loop over all records of the table.
586The Close instruction at the end is there to give the
587Rewind instruction something to jump to when it is done. All of
588this is just like in the first query demonstration.</p>
589
590<p>The Callback instruction in this example has to generate
591data for three result columns instead of two, but is otherwise
592the same as in the first query. When the Callback instruction
593is invoked, the left-most column of the result should be
594the lowest in the stack and the right-most result column should
595be the top of the stack. We can see the stack being set up
596this way at addresses 11 through 15. The Column instructions at
59711 and 12 push the values for the first two columns in the result.
598The two Column instructions at 13 and 14 pull in the values needed
599to compute the third result column and the Concat instruction at
60015 joins them together into a single entry on the stack.</p>
601
602<p>The only thing that is really new about the current example
603is the WHERE clause which is implemented by instructions at
604addresses 7 through 10. Instructions at address 7 and 8 push
605onto the stack the value of the "one" column from the table
606and the literal string "H%".
607The <a href="opcode.html#Function">Function</a> instruction at address 9
608pops these two values from the stack and pushes the result of the LIKE()
609function back onto the stack.
610The <a href="opcode.html#IfNot">IfNot</a> instruction pops the top stack
611value and causes an immediate jump forward to the Next instruction if the
612top value was false (<em>not</em> not like the literal string "H%").
613Taking this jump effectively skips the callback, which is the whole point
614of the WHERE clause. If the result
615of the comparison is true, the jump is not taken and control
616falls through to the Callback instruction below.</p>
617
618<p>Notice how the LIKE operator is implemented. It is a user-defined
619function in SQLite, so the address of its function definition is
620specified in P3. The operand P1 is the number of function arguments for
621it to take from the stack. In this case the LIKE() function takes 2
622arguments. The arguments are taken off the stack in reverse order
623(right-to-left), so the pattern to match is the top stack element, and
624the next element is the data to compare. The return value is pushed
625onto the stack.</p>
626
627
628<a name="pattern1">
629<h2>A Template For SELECT Programs</h2>
630
631<p>The first two query examples illustrate a kind of template that
632every SELECT program will follow. Basically, we have:</p>
633
634<p>
635<ol>
636<li>Initialize the <b>azColumnName[]</b> array for the callback.</li>
637<li>Open a cursor into the table to be queried.</li>
638<li>For each record in the table, do:
639 <ol type="a">
640 <li>If the WHERE clause evaluates to FALSE, then skip the steps that
641 follow and continue to the next record.</li>
642 <li>Compute all columns for the current row of the result.</li>
643 <li>Invoke the callback function for the current row of the result.</li>
644 </ol>
645<li>Close the cursor.</li>
646</ol>
647</p>
648
649<p>This template will be expanded considerably as we consider
650additional complications such as joins, compound selects, using
651indices to speed the search, sorting, and aggregate functions
652with and without GROUP BY and HAVING clauses.
653But the same basic ideas will continue to apply.</p>
654
655<h2>UPDATE And DELETE Statements</h2>
656
657<p>The UPDATE and DELETE statements are coded using a template
658that is very similar to the SELECT statement template. The main
659difference, of course, is that the end action is to modify the
660database rather than invoke a callback function. Because it modifies
661the database it will also use transactions. Let's begin
662by looking at a DELETE statement:</p>
663
664<blockquote><pre>
665DELETE FROM examp WHERE two<50;
666</pre></blockquote>
667
668<p>This DELETE statement will remove every record from the "examp"
669table where the "two" column is less than 50.
670The code generated to do this is as follows:</p>
671}
672
673Code {
674addr opcode p1 p2 p3
675---- ------------ ----- ----- -----------------------------------
6760 Transaction 1 0
6771 Transaction 0 0
6782 VerifyCookie 0 178
6793 Integer 0 0
6804 OpenRead 0 3 examp
6815 Rewind 0 12
6826 Column 0 1
6837 Integer 50 0 50
6848 Ge 1 11
6859 Recno 0 0
68610 ListWrite 0 0
68711 Next 0 6
68812 Close 0 0
68913 ListRewind 0 0
69014 Integer 0 0
69115 OpenWrite 0 3
69216 ListRead 0 20
69317 NotExists 0 19
69418 Delete 0 1
69519 Goto 0 16
69620 ListReset 0 0
69721 Close 0 0
69822 Commit 0 0
69923 Halt 0 0
700}
701
702puts {
703<p>Here is what the program must do. First it has to locate all of
704the records in the table "examp" that are to be deleted. This is
705done using a loop very much like the loop used in the SELECT examples
706above. Once all records have been located, then we can go back through
707and delete them one by one. Note that we cannot delete each record
708as soon as we find it. We have to locate all records first, then
709go back and delete them. This is because the SQLite database
710backend might change the scan order after a delete operation.
711And if the scan
712order changes in the middle of the scan, some records might be
713visited more than once and other records might not be visited at all.</p>
714
715<p>So the implemention of DELETE is really in two loops. The first loop
716(instructions 5 through 11) locates the records that are to be deleted
717and saves their keys onto a temporary list, and the second loop
718(instructions 16 through 19) uses the key list to delete the records one
719by one. </p>
720}
721
722
723Code {
7240 Transaction 1 0
7251 Transaction 0 0
7262 VerifyCookie 0 178
7273 Integer 0 0
7284 OpenRead 0 3 examp
729}
730puts {
731<p>Instructions 0 though 4 are as in the INSERT example. They start
732transactions for the main and temporary databases, verify the database
733schema for the main database, and open a read cursor on the table
734"examp". Notice that the cursor is opened for reading, not writing. At
735this stage of the program we are only going to be scanning the table,
736not changing it. We will reopen the same table for writing later, at
737instruction 15.</p>
738}
739
740Code {
7415 Rewind 0 12
742}
743puts {
744<p>As in the SELECT example, the <a href="opcode.html#Rewind">Rewind</a>
745instruction rewinds the cursor to the beginning of the table, readying
746it for use in the loop body.</p>
747}
748
749Code {
7506 Column 0 1
7517 Integer 50 0 50
7528 Ge 1 11
753}
754puts {
755<p>The WHERE clause is implemented by instructions 6 through 8.
756The job of the where clause is to skip the ListWrite if the WHERE
757condition is false. To this end, it jumps ahead to the Next instruction
758if the "two" column (extracted by the Column instruction) is
759greater than or equal to 50.</p>
760
761<p>As before, the Column instruction uses cursor P1 and pushes the data
762record in column P2 (1, column "two") onto the stack. The Integer
763instruction pushes the value 50 onto the top of the stack. After these
764two instructions the stack looks like:</p>
765}
766stack {(integer) 50} \
767 {(record) current record for column "two" }
768
769puts {
770<p>The <a href="opcode.html#Ge">Ge</a> operator compares the top two
771elements on the stack, pops them, and then branches based on the result
772of the comparison. If the second element is >= the top element, then
773jump to address P2 (the Next instruction at the end of the loop).
774Because P1 is true, if either operand is NULL (and thus the result is
775NULL) then take the jump. If we don't jump, just advance to the next
776instruction.</p>
777}
778
779Code {
7809 Recno 0 0
78110 ListWrite 0 0
782}
783puts {
784<p>The <a href="opcode.html#Recno">Recno</a> instruction pushes onto the
785stack an integer which is the first 4 bytes of the the key to the current
786entry in a sequential scan of the table pointed to by cursor P1.
787The <a href="opcode.html#ListWrite">ListWrite</a> instruction writes the
788integer on the top of the stack into a temporary storage list and pops
789the top element. This is the important work of this loop, to store the
790keys of the records to be deleted so we can delete them in the second
791loop. After this ListWrite instruction the stack is empty again.</p>
792}
793
794Code {
79511 Next 0 6
79612 Close 0 0
797}
798puts {
799<p> The Next instruction increments the cursor to point to the next
800element in the table pointed to by cursor P0, and if it was successful
801branches to P2 (6, the beginning of the loop body). The Close
802instruction closes cursor P1. It doesn't affect the temporary storage
803list because it isn't associated with cursor P1; it is instead a global
804working list (which can be saved with ListPush).</p>
805}
806
807Code {
80813 ListRewind 0 0
809}
810puts {
811<p> The <a href="opcode.html#ListRewind">ListRewind</a> instruction
812rewinds the temporary storage list to the beginning. This prepares it
813for use in the second loop.</p>
814}
815
816Code {
81714 Integer 0 0
81815 OpenWrite 0 3
819}
820puts {
821<p> As in the INSERT example, we push the database number P1 (0, the main
822database) onto the stack and use OpenWrite to open the cursor P1 on table
823P2 (base page 3, "examp") for modification.</p>
824}
825
826Code {
82716 ListRead 0 20
82817 NotExists 0 19
82918 Delete 0 1
83019 Goto 0 16
831}
832puts {
833<p>This loop does the actual deleting. It is organized differently from
834the one in the UPDATE example. The ListRead instruction plays the role
835that the Next did in the INSERT loop, but because it jumps to P2 on
836failure, and Next jumps on success, we put it at the start of the loop
837instead of the end. This means that we have to put a Goto at the end of
838the loop to jump back to the the loop test at the beginning. So this
839loop has the form of a C while(){...} loop, while the loop in the INSERT
840example had the form of a do{...}while() loop. The Delete instruction
841fills the role that the callback function did in the preceding examples.
842</p>
843<p>The <a href="opcode.html#ListRead">ListRead</a> instruction reads an
844element from the temporary storage list and pushes it onto the stack.
845If this was successful, it continues to the next instruction. If this
846fails because the list is empty, it branches to P2, which is the
847instruction just after the loop. Afterwards the stack looks like:</p>
848}
849stack {(integer) key for current record}
850
851puts {
852<p>Notice the similarity between the ListRead and Next instructions.
853Both operations work according to this rule:
854</p>
855<blockquote>
856Push the next "thing" onto the stack and fall through OR jump to P2,
857depending on whether or not there is a next "thing" to push.
858</blockquote>
859<p>One difference between Next and ListRead is their idea of a "thing".
860The "things" for the Next instruction are records in a database file.
861"Things" for ListRead are integer keys in a list. Another difference
862is whether to jump or fall through if there is no next "thing". In this
863case, Next falls through, and ListRead jumps. Later on, we will see
864other looping instructions (NextIdx and SortNext) that operate using the
865same principle.</p>
866
867<p>The <a href="opcode.html#NotExists">NotExists</a> instruction pops
868the top stack element and uses it as an integer key. If a record with
869that key does not exist in table P1, then jump to P2. If a record does
870exist, then fall thru to the next instruction. In this case P2 takes
871us to the Goto at the end of the loop, which jumps back to the ListRead
872at the beginning. This could have been coded to have P2 be 16, the
873ListRead at the start of the loop, but the SQLite parser which generated
874this code didn't make that optimization.</p>
875<p>The <a href="opcode.html#Delete">Delete</a> does the work of this
876loop; it pops an integer key off the stack (placed there by the
877preceding ListRead) and deletes the record of cursor P1 that has that key.
878Because P2 is true, the row change counter is incremented.</p>
879<p>The <a href="opcode.html#Goto">Goto</a> jumps back to the beginning
880of the loop. This is the end of the loop.</p>
881}
882
883Code {
88420 ListReset 0 0
88521 Close 0 0
88622 Commit 0 0
88723 Halt 0 0
888}
889puts {
890<p>This block of instruction cleans up the VDBE program. Three of these
891instructions aren't really required, but are generated by the SQLite
892parser from its code templates, which are designed to handle more
893complicated cases.</p>
894<p>The <a href="opcode.html#ListReset">ListReset</a> instruction empties
895the temporary storage list. This list is emptied automatically when the
896VDBE program terminates, so it isn't necessary in this case. The Close
897instruction closes the cursor P1. Again, this is done by the VDBE
898engine when it is finished running this program. The Commit ends the
899current transaction successfully, and causes all changes that occurred
900in this transaction to be saved to the database. The final Halt is also
901unneccessary, since it is added to every VDBE program when it is
902prepared to run.</p>
903
904
905<p>UPDATE statements work very much like DELETE statements except
906that instead of deleting the record they replace it with a new one.
907Consider this example:
908</p>
909
910<blockquote><pre>
911UPDATE examp SET one= '(' || one || ')' WHERE two < 50;
912</pre></blockquote>
913
914<p>Instead of deleting records where the "two" column is less than
91550, this statement just puts the "one" column in parentheses
916The VDBE program to implement this statement follows:</p>
917}
918
919Code {
920addr opcode p1 p2 p3
921---- ------------ ----- ----- -----------------------------------
9220 Transaction 1 0
9231 Transaction 0 0
9242 VerifyCookie 0 178
9253 Integer 0 0
9264 OpenRead 0 3 examp
9275 Rewind 0 12
9286 Column 0 1
9297 Integer 50 0 50
9308 Ge 1 11
9319 Recno 0 0
93210 ListWrite 0 0
93311 Next 0 6
93412 Close 0 0
93513 Integer 0 0
93614 OpenWrite 0 3
93715 ListRewind 0 0
93816 ListRead 0 28
93917 Dup 0 0
94018 NotExists 0 16
94119 String 0 0 (
94220 Column 0 0
94321 Concat 2 0
94422 String 0 0 )
94523 Concat 2 0
94624 Column 0 1
94725 MakeRecord 2 0
94826 PutIntKey 0 1
94927 Goto 0 16
95028 ListReset 0 0
95129 Close 0 0
95230 Commit 0 0
95331 Halt 0 0
954}
955
956puts {
957<p>This program is essentially the same as the DELETE program except
958that the body of the second loop has been replace by a sequence of
959instructions (at addresses 17 through 26) that update the record rather
960than delete it. Most of this instruction sequence should already be
961familiar to you, but there are a couple of minor twists so we will go
962over it briefly. Also note that the order of some of the instructions
963before and after the 2nd loop has changed. This is just the way the
964SQLite parser chose to output the code using a different template.</p>
965
966<p>As we enter the interior of the second loop (at instruction 17)
967the stack contains a single integer which is the key of the
968record we want to modify. We are going to need to use this
969key twice: once to fetch the old value of the record and
970a second time to write back the revised record. So the first instruction
971is a Dup to make a duplicate of the key on the top of the stack. The
972Dup instruction will duplicate any element of the stack, not just the top
973element. You specify which element to duplication using the
974P1 operand. When P1 is 0, the top of the stack is duplicated.
975When P1 is 1, the next element down on the stack duplication.
976And so forth.</p>
977
978<p>After duplicating the key, the next instruction, NotExists,
979pops the stack once and uses the value popped as a key to
980check the existence of a record in the database file. If there is no record
981for this key, it jumps back to the ListRead to get another key.</p>
982
983<p>Instructions 19 through 25 construct a new database record
984that will be used to replace the existing record. This is
985the same kind of code that we saw
986in the description of INSERT and will not be described further.
987After instruction 25 executes, the stack looks like this:</p>
988}
989
990stack {(record) new data record} {(integer) key}
991
992puts {
993<p>The PutIntKey instruction (also described
994during the discussion about INSERT) writes an entry into the
995database file whose data is the top of the stack and whose key
996is the next on the stack, and then pops the stack twice. The
997PutIntKey instruction will overwrite the data of an existing record
998with the same key, which is what we want here. Overwriting was not
999an issue with INSERT because with INSERT the key was generated
1000by the NewRecno instruction which is guaranteed to provide a key
1001that has not been used before.</p>
1002}
1003
1004if 0 {<p>(By the way, since keys must
1005all be unique and each key is a 32-bit integer, a single
1006SQLite database table can have no more than 2<sup>32</sup>
1007rows. Actually, the Key instruction starts to become
1008very inefficient as you approach this upper bound, so it
1009is best to keep the number of entries below 2<sup>31</sup>
1010or so. Surely a couple billion records will be enough for
1011most applications!)</p>
1012}
1013
1014puts {
1015<h2>CREATE and DROP</h2>
1016
1017<p>Using CREATE or DROP to create or destroy a table or index is
1018really the same as doing an INSERT or DELETE from the special
1019"sqlite_master" table, at least from the point of view of the VDBE.
1020The sqlite_master table is a special table that is automatically
1021created for every SQLite database. It looks like this:</p>
1022
1023<blockquote><pre>
1024CREATE TABLE sqlite_master (
1025 type TEXT, -- either "table" or "index"
1026 name TEXT, -- name of this table or index
1027 tbl_name TEXT, -- for indices: name of associated table
1028 sql TEXT -- SQL text of the original CREATE statement
1029)
1030</pre></blockquote>
1031
1032<p>Every table (except the "sqlite_master" table itself)
1033and every named index in an SQLite database has an entry
1034in the sqlite_master table. You can query this table using
1035a SELECT statement just like any other table. But you are
1036not allowed to directly change the table using UPDATE, INSERT,
1037or DELETE. Changes to sqlite_master have to occur using
1038the CREATE and DROP commands because SQLite also has to update
1039some of its internal data structures when tables and indices
1040are added or destroyed.</p>
1041
1042<p>But from the point of view of the VDBE, a CREATE works
1043pretty much like an INSERT and a DROP works like a DELETE.
1044When the SQLite library opens to an existing database,
1045the first thing it does is a SELECT to read the "sql"
1046columns from all entries of the sqlite_master table.
1047The "sql" column contains the complete SQL text of the
1048CREATE statement that originally generated the index or
1049table. This text is fed back into the SQLite parser
1050and used to reconstruct the
1051internal data structures describing the index or table.</p>
1052
1053<h2>Using Indexes To Speed Searching</h2>
1054
1055<p>In the example queries above, every row of the table being
1056queried must be loaded off of the disk and examined, even if only
1057a small percentage of the rows end up in the result. This can
1058take a long time on a big table. To speed things up, SQLite
1059can use an index.</p>
1060
1061<p>An SQLite file associates a key with some data. For an SQLite
1062table, the database file is set up so that the key is an integer
1063and the data is the information for one row of the table.
1064Indices in SQLite reverse this arrangement. The index key
1065is (some of) the information being stored and the index data
1066is an integer.
1067To access a table row that has some particular
1068content, we first look up the content in the index table to find
1069its integer index, then we use that integer to look up the
1070complete record in the table.</p>
1071
1072<p>Note that SQLite uses b-trees, which are a sorted data structure,
1073so indices can be used when the WHERE clause of the SELECT statement
1074contains tests for equality or inequality. Queries like the following
1075can use an index if it is available:</p>
1076
1077<blockquote><pre>
1078SELECT * FROM examp WHERE two==50;
1079SELECT * FROM examp WHERE two<50;
1080SELECT * FROM examp WHERE two IN (50, 100);
1081</pre></blockquote>
1082
1083<p>If there exists an index that maps the "two" column of the "examp"
1084table into integers, then SQLite will use that index to find the integer
1085keys of all rows in examp that have a value of 50 for column two, or
1086all rows that are less than 50, etc.
1087But the following queries cannot use the index:</p>
1088
1089<blockquote><pre>
1090SELECT * FROM examp WHERE two%50 == 10;
1091SELECT * FROM examp WHERE two&127 == 3;
1092</pre></blockquote>
1093
1094<p>Note that the SQLite parser will not always generate code to use an
1095index, even if it is possible to do so. The following queries will not
1096currently use the index:</p>
1097
1098<blockquote><pre>
1099SELECT * FROM examp WHERE two+10 == 50;
1100SELECT * FROM examp WHERE two==50 OR two==100;
1101</pre></blockquote>
1102
1103<p>To understand better how indices work, lets first look at how
1104they are created. Let's go ahead and put an index on the two
1105column of the examp table. We have:</p>
1106
1107<blockquote><pre>
1108CREATE INDEX examp_idx1 ON examp(two);
1109</pre></blockquote>
1110
1111<p>The VDBE code generated by the above statement looks like the
1112following:</p>
1113}
1114
1115Code {
1116addr opcode p1 p2 p3
1117---- ------------ ----- ----- -----------------------------------
11180 Transaction 1 0
11191 Transaction 0 0
11202 VerifyCookie 0 178
11213 Integer 0 0
11224 OpenWrite 0 2
11235 NewRecno 0 0
11246 String 0 0 index
11257 String 0 0 examp_idx1
11268 String 0 0 examp
11279 CreateIndex 0 0 ptr(0x791380)
112810 Dup 0 0
112911 Integer 0 0
113012 OpenWrite 1 0
113113 String 0 0 CREATE INDEX examp_idx1 ON examp(tw
113214 MakeRecord 5 0
113315 PutIntKey 0 0
113416 Integer 0 0
113517 OpenRead 2 3 examp
113618 Rewind 2 24
113719 Recno 2 0
113820 Column 2 1
113921 MakeIdxKey 1 0 n
114022 IdxPut 1 0 indexed columns are not unique
114123 Next 2 19
114224 Close 2 0
114325 Close 1 0
114426 Integer 333 0
114527 SetCookie 0 0
114628 Close 0 0
114729 Commit 0 0
114830 Halt 0 0
1149}
1150
1151puts {
1152<p>Remember that every table (except sqlite_master) and every named
1153index has an entry in the sqlite_master table. Since we are creating
1154a new index, we have to add a new entry to sqlite_master. This is
1155handled by instructions 3 through 15. Adding an entry to sqlite_master
1156works just like any other INSERT statement so we will not say anymore
1157about it here. In this example, we want to focus on populating the
1158new index with valid data, which happens on instructions 16 through
115923.</p>
1160}
1161
1162Code {
116316 Integer 0 0
116417 OpenRead 2 3 examp
1165}
1166puts {
1167<p>The first thing that happens is that we open the table being
1168indexed for reading. In order to construct an index for a table,
1169we have to know what is in that table. The index has already been
1170opened for writing using cursor 0 by instructions 3 and 4.</p>
1171}
1172
1173Code {
117418 Rewind 2 24
117519 Recno 2 0
117620 Column 2 1
117721 MakeIdxKey 1 0 n
117822 IdxPut 1 0 indexed columns are not unique
117923 Next 2 19
1180}
1181puts {
1182<p>Instructions 18 through 23 implement a loop over every row of the
1183table being indexed. For each table row, we first extract the integer
1184key for that row using Recno in instruction 19, then get the value of
1185the "two" column using Column in instruction 20.
1186The <a href="opcode.html#MakeIdxKey">MakeIdxKey</a> instruction at 21
1187converts data from the "two" column (which is on the top of the stack)
1188into a valid index key. For an index on a single column, this is
1189basically a no-op. But if the P1 operand to MakeIdxKey had been
1190greater than one multiple entries would have been popped from the stack
1191and converted into a single index key.
1192The <a href="opcode.html#IdxPut">IdxPut</a> instruction at 22 is what
1193actually creates the index entry. IdxPut pops two elements from the
1194stack. The top of the stack is used as a key to fetch an entry from the
1195index table. Then the integer which was second on stack is added to the
1196set of integers for that index and the new record is written back to the
1197database file. Note
1198that the same index entry can store multiple integers if there
1199are two or more table entries with the same value for the two
1200column.
1201</p>
1202
1203<p>Now let's look at how this index will be used. Consider the
1204following query:</p>
1205
1206<blockquote><pre>
1207SELECT * FROM examp WHERE two==50;
1208</pre></blockquote>
1209
1210<p>SQLite generates the following VDBE code to handle this query:</p>
1211}
1212
1213Code {
1214addr opcode p1 p2 p3
1215---- ------------ ----- ----- -----------------------------------
12160 ColumnName 0 0 one
12171 ColumnName 1 0 two
12182 Integer 0 0
12193 OpenRead 0 3 examp
12204 VerifyCookie 0 256
12215 Integer 0 0
12226 OpenRead 1 4 examp_idx1
12237 Integer 50 0 50
12248 MakeKey 1 0 n
12259 MemStore 0 0
122610 MoveTo 1 19
122711 MemLoad 0 0
122812 IdxGT 1 19
122913 IdxRecno 1 0
123014 MoveTo 0 0
123115 Column 0 0
123216 Column 0 1
123317 Callback 2 0
123418 Next 1 11
123519 Close 0 0
123620 Close 1 0
123721 Halt 0 0
1238}
1239
1240puts {
1241<p>The SELECT begins in a familiar fashion. First the column
1242names are initialized and the table being queried is opened.
1243Things become different beginning with instructions 5 and 6 where
1244the index file is also opened. Instructions 7 and 8 make
1245a key with the value of 50.
1246The <a href="opcode.html#MemStore">MemStore</a> instruction at 9 stores
1247the index key in VDBE memory location 0. The VDBE memory is used to
1248avoid having to fetch a value from deep in the stack, which can be done,
1249but makes the program harder to generate. The following instruction
1250<a href="opcode.html#MoveTo">MoveTo</a> at address 10 pops the key off
1251the stack and moves the index cursor to the first row of the index with
1252that key. This initializes the cursor for use in the following loop.</p>
1253
1254<p>Instructions 11 through 18 implement a loop over all index records
1255with the key that was fetched by instruction 8. All of the index
1256records with this key will be contiguous in the index table, so we walk
1257through them and fetch the corresponding table key from the index.
1258This table key is then used to move the cursor to that row in the table.
1259The rest of the loop is the same as the loop for the non-indexed SELECT
1260query.</p>
1261
1262<p>The loop begins with the <a href="opcode.html#MemLoad">MemLoad</a>
1263instruction at 11 which pushes a copy of the index key back onto the
1264stack. The instruction <a href="opcode.html#IdxGT">IdxGT</a> at 12
1265compares the key to the key in the current index record pointed to by
1266cursor P1. If the index key at the current cursor location is greater
1267than the the index we are looking for, then jump out of the loop.</p>
1268
1269<p>The instruction <a href="opcode.html#IdxRecno">IdxRecno</a> at 13
1270pushes onto the stack the table record number from the index. The
1271following MoveTo pops it and moves the table cursor to that row. The
1272next 3 instructions select the column data the same way as in the non-
1273indexed case. The Column instructions fetch the column data and the
1274callback function is invoked. The final Next instruction advances the
1275index cursor, not the table cursor, to the next row, and then branches
1276back to the start of the loop if there are any index records left.</p>
1277
1278<p>Since the index is used to look up values in the table,
1279it is important that the index and table be kept consistent.
1280Now that there is an index on the examp table, we will have
1281to update that index whenever data is inserted, deleted, or
1282changed in the examp table. Remember the first example above
1283where we were able to insert a new row into the "examp" table using
128412 VDBE instructions. Now that this table is indexed, 19
1285instructions are required. The SQL statement is this:</p>
1286
1287<blockquote><pre>
1288INSERT INTO examp VALUES('Hello, World!',99);
1289</pre></blockquote>
1290
1291<p>And the generated code looks like this:</p>
1292}
1293
1294Code {
1295addr opcode p1 p2 p3
1296---- ------------ ----- ----- -----------------------------------
12970 Transaction 1 0
12981 Transaction 0 0
12992 VerifyCookie 0 256
13003 Integer 0 0
13014 OpenWrite 0 3 examp
13025 Integer 0 0
13036 OpenWrite 1 4 examp_idx1
13047 NewRecno 0 0
13058 String 0 0 Hello, World!
13069 Integer 99 0 99
130710 Dup 2 1
130811 Dup 1 1
130912 MakeIdxKey 1 0 n
131013 IdxPut 1 0
131114 MakeRecord 2 0
131215 PutIntKey 0 1
131316 Close 0 0
131417 Close 1 0
131518 Commit 0 0
131619 Halt 0 0
1317}
1318
1319puts {
1320<p>At this point, you should understand the VDBE well enough to
1321figure out on your own how the above program works. So we will
1322not discuss it further in this text.</p>
1323
1324<h2>Joins</h2>
1325
1326<p>In a join, two or more tables are combined to generate a single
1327result. The result table consists of every possible combination
1328of rows from the tables being joined. The easiest and most natural
1329way to implement this is with nested loops.</p>
1330
1331<p>Recall the query template discussed above where there was a
1332single loop that searched through every record of the table.
1333In a join we have basically the same thing except that there
1334are nested loops. For example, to join two tables, the query
1335template might look something like this:</p>
1336
1337<p>
1338<ol>
1339<li>Initialize the <b>azColumnName[]</b> array for the callback.</li>
1340<li>Open two cursors, one to each of the two tables being queried.</li>
1341<li>For each record in the first table, do:
1342 <ol type="a">
1343 <li>For each record in the second table do:
1344 <ol type="i">
1345 <li>If the WHERE clause evaluates to FALSE, then skip the steps that
1346 follow and continue to the next record.</li>
1347 <li>Compute all columns for the current row of the result.</li>
1348 <li>Invoke the callback function for the current row of the result.</li>
1349 </ol></li>
1350 </ol>
1351<li>Close both cursors.</li>
1352</ol>
1353</p>
1354
1355<p>This template will work, but it is likely to be slow since we
1356are now dealing with an O(N<sup>2</sup>) loop. But it often works
1357out that the WHERE clause can be factored into terms and that one or
1358more of those terms will involve only columns in the first table.
1359When this happens, we can factor part of the WHERE clause test out of
1360the inner loop and gain a lot of efficiency. So a better template
1361would be something like this:</p>
1362
1363<p>
1364<ol>
1365<li>Initialize the <b>azColumnName[]</b> array for the callback.</li>
1366<li>Open two cursors, one to each of the two tables being queried.</li>
1367<li>For each record in the first table, do:
1368 <ol type="a">
1369 <li>Evaluate terms of the WHERE clause that only involve columns from
1370 the first table. If any term is false (meaning that the whole
1371 WHERE clause must be false) then skip the rest of this loop and
1372 continue to the next record.</li>
1373 <li>For each record in the second table do:
1374 <ol type="i">
1375 <li>If the WHERE clause evaluates to FALSE, then skip the steps that
1376 follow and continue to the next record.</li>
1377 <li>Compute all columns for the current row of the result.</li>
1378 <li>Invoke the callback function for the current row of the result.</li>
1379 </ol></li>
1380 </ol>
1381<li>Close both cursors.</li>
1382</ol>
1383</p>
1384
1385<p>Additional speed-up can occur if an index can be used to speed
1386the search of either or the two loops.</p>
1387
1388<p>SQLite always constructs the loops in the same order as the
1389tables appear in the FROM clause of the SELECT statement. The
1390left-most table becomes the outer loop and the right-most table
1391becomes the inner loop. It is possible, in theory, to reorder
1392the loops in some circumstances to speed the evaluation of the
1393join. But SQLite does not attempt this optimization.</p>
1394
1395<p>You can see how SQLite constructs nested loops in the following
1396example:</p>
1397
1398<blockquote><pre>
1399CREATE TABLE examp2(three int, four int);
1400SELECT * FROM examp, examp2 WHERE two<50 AND four==two;
1401</pre></blockquote>
1402}
1403
1404Code {
1405addr opcode p1 p2 p3
1406---- ------------ ----- ----- -----------------------------------
14070 ColumnName 0 0 examp.one
14081 ColumnName 1 0 examp.two
14092 ColumnName 2 0 examp2.three
14103 ColumnName 3 0 examp2.four
14114 Integer 0 0
14125 OpenRead 0 3 examp
14136 VerifyCookie 0 909
14147 Integer 0 0
14158 OpenRead 1 5 examp2
14169 Rewind 0 24
141710 Column 0 1
141811 Integer 50 0 50
141912 Ge 1 23
142013 Rewind 1 23
142114 Column 1 1
142215 Column 0 1
142316 Ne 1 22
142417 Column 0 0
142518 Column 0 1
142619 Column 1 0
142720 Column 1 1
142821 Callback 4 0
142922 Next 1 14
143023 Next 0 10
143124 Close 0 0
143225 Close 1 0
143326 Halt 0 0
1434}
1435
1436puts {
1437<p>The outer loop over table examp is implement by instructions
14387 through 23. The inner loop is instructions 13 through 22.
1439Notice that the "two<50" term of the WHERE expression involves
1440only columns from the first table and can be factored out of
1441the inner loop. SQLite does this and implements the "two<50"
1442test in instructions 10 through 12. The "four==two" test is
1443implement by instructions 14 through 16 in the inner loop.</p>
1444
1445<p>SQLite does not impose any arbitrary limits on the tables in
1446a join. It also allows a table to be joined with itself.</p>
1447
1448<h2>The ORDER BY clause</h2>
1449
1450<p>For historical reasons, and for efficiency, all sorting is currently
1451done in memory.</p>
1452
1453<p>SQLite implements the ORDER BY clause using a special
1454set of instructions to control an object called a sorter. In the
1455inner-most loop of the query, where there would normally be
1456a Callback instruction, instead a record is constructed that
1457contains both callback parameters and a key. This record
1458is added to the sorter (in a linked list). After the query loop
1459finishes, the list of records is sorted and this list is walked. For
1460each record on the list, the callback is invoked. Finally, the sorter
1461is closed and memory is deallocated.</p>
1462
1463<p>We can see the process in action in the following query:</p>
1464
1465<blockquote><pre>
1466SELECT * FROM examp ORDER BY one DESC, two;
1467</pre></blockquote>
1468}
1469
1470Code {
1471addr opcode p1 p2 p3
1472---- ------------ ----- ----- -----------------------------------
14730 ColumnName 0 0 one
14741 ColumnName 1 0 two
14752 Integer 0 0
14763 OpenRead 0 3 examp
14774 VerifyCookie 0 909
14785 Rewind 0 14
14796 Column 0 0
14807 Column 0 1
14818 SortMakeRec 2 0
14829 Column 0 0
148310 Column 0 1
148411 SortMakeKey 2 0 D+
148512 SortPut 0 0
148613 Next 0 6
148714 Close 0 0
148815 Sort 0 0
148916 SortNext 0 19
149017 SortCallback 2 0
149118 Goto 0 16
149219 SortReset 0 0
149320 Halt 0 0
1494}
1495
1496puts {
1497<p>There is only one sorter object, so there are no instructions to open
1498or close it. It is opened automatically when needed, and it is closed
1499when the VDBE program halts.</p>
1500
1501<p>The query loop is built from instructions 5 through 13. Instructions
15026 through 8 build a record that contains the azData[] values for a single
1503invocation of the callback. A sort key is generated by instructions
15049 through 11. Instruction 12 combines the invocation record and the
1505sort key into a single entry and puts that entry on the sort list.<p>
1506
1507<p>The P3 argument of instruction 11 is of particular interest. The
1508sort key is formed by prepending one character from P3 to each string
1509and concatenating all the strings. The sort comparison function will
1510look at this character to determine whether the sort order is
1511ascending or descending, and whether to sort as a string or number.
1512In this example, the first column should be sorted as a string
1513in descending order so its prefix is "D" and the second column should
1514sorted numerically in ascending order so its prefix is "+". Ascending
1515string sorting uses "A", and descending numeric sorting uses "-".</p>
1516
1517<p>After the query loop ends, the table being queried is closed at
1518instruction 14. This is done early in order to allow other processes
1519or threads to access that table, if desired. The list of records
1520that was built up inside the query loop is sorted by the instruction
1521at 15. Instructions 16 through 18 walk through the record list
1522(which is now in sorted order) and invoke the callback once for
1523each record. Finally, the sorter is closed at instruction 19.</p>
1524
1525<h2>Aggregate Functions And The GROUP BY and HAVING Clauses</h2>
1526
1527<p>To compute aggregate functions, the VDBE implements a special
1528data structure and instructions for controlling that data structure.
1529The data structure is an unordered set of buckets, where each bucket
1530has a key and one or more memory locations. Within the query
1531loop, the GROUP BY clause is used to construct a key and the bucket
1532with that key is brought into focus. A new bucket is created with
1533the key if one did not previously exist. Once the bucket is in
1534focus, the memory locations of the bucket are used to accumulate
1535the values of the various aggregate functions. After the query
1536loop terminates, each bucket is visited once to generate a
1537single row of the results.</p>
1538
1539<p>An example will help to clarify this concept. Consider the
1540following query:</p>
1541
1542<blockquote><pre>
1543SELECT three, min(three+four)+avg(four)
1544FROM examp2
1545GROUP BY three;
1546</pre></blockquote>
1547
1548
1549<p>The VDBE code generated for this query is as follows:</p>
1550}
1551
1552Code {
1553addr opcode p1 p2 p3
1554---- ------------ ----- ----- -----------------------------------
15550 ColumnName 0 0 three
15561 ColumnName 1 0 min(three+four)+avg(four)
15572 AggReset 0 3
15583 AggInit 0 1 ptr(0x7903a0)
15594 AggInit 0 2 ptr(0x790700)
15605 Integer 0 0
15616 OpenRead 0 5 examp2
15627 VerifyCookie 0 909
15638 Rewind 0 23
15649 Column 0 0
156510 MakeKey 1 0 n
156611 AggFocus 0 14
156712 Column 0 0
156813 AggSet 0 0
156914 Column 0 0
157015 Column 0 1
157116 Add 0 0
157217 Integer 1 0
157318 AggFunc 0 1 ptr(0x7903a0)
157419 Column 0 1
157520 Integer 2 0
157621 AggFunc 0 1 ptr(0x790700)
157722 Next 0 9
157823 Close 0 0
157924 AggNext 0 31
158025 AggGet 0 0
158126 AggGet 0 1
158227 AggGet 0 2
158328 Add 0 0
158429 Callback 2 0
158530 Goto 0 24
158631 Noop 0 0
158732 Halt 0 0
1588}
1589
1590puts {
1591<p>The first instruction of interest is the
1592<a href="opcode.html#AggReset">AggReset</a> at 2.
1593The AggReset instruction initializes the set of buckets to be the
1594empty set and specifies the number of memory slots available in each
1595bucket as P2. In this example, each bucket will hold 3 memory slots.
1596It is not obvious, but if you look closely at the rest of the program
1597you can figure out what each of these slots is intended for.</p>
1598
1599<blockquote><table border="2" cellpadding="5">
1600<tr><th>Memory Slot</th><th>Intended Use Of This Memory Slot</th></tr>
1601<tr><td>0</td><td>The "three" column -- the key to the bucket</td></tr>
1602<tr><td>1</td><td>The minimum "three+four" value</td></tr>
1603<tr><td>2</td><td>The sum of all "four" values. This is used to compute
1604 "avg(four)".</td></tr>
1605</table></blockquote>
1606
1607<p>The query loop is implemented by instructions 8 through 22.
1608The aggregate key specified by the GROUP BY clause is computed
1609by instructions 9 and 10. Instruction 11 causes the appropriate
1610bucket to come into focus. If a bucket with the given key does
1611not already exists, a new bucket is created and control falls
1612through to instructions 12 and 13 which initialize the bucket.
1613If the bucket does already exist, then a jump is made to instruction
161414. The values of aggregate functions are updated by the instructions
1615between 11 and 21. Instructions 14 through 18 update memory
1616slot 1 to hold the next value "min(three+four)". Then the sum of the
1617"four" column is updated by instructions 19 through 21.</p>
1618
1619<p>After the query loop is finished, the table "examp2" is closed at
1620instruction 23 so that its lock will be released and it can be
1621used by other threads or processes. The next step is to loop
1622over all aggregate buckets and output one row of the result for
1623each bucket. This is done by the loop at instructions 24
1624through 30. The AggNext instruction at 24 brings the next bucket
1625into focus, or jumps to the end of the loop if all buckets have
1626been examined already. The 3 columns of the result are fetched from
1627the aggregator bucket in order at instructions 25 through 27.
1628Finally, the callback is invoked at instruction 29.</p>
1629
1630<p>In summary then, any query with aggregate functions is implemented
1631by two loops. The first loop scans the input table and computes
1632aggregate information into buckets and the second loop scans through
1633all the buckets to compute the final result.</p>
1634
1635<p>The realization that an aggregate query is really two consequtive
1636loops makes it much easier to understand the difference between
1637a WHERE clause and a HAVING clause in SQL query statement. The
1638WHERE clause is a restriction on the first loop and the HAVING
1639clause is a restriction on the second loop. You can see this
1640by adding both a WHERE and a HAVING clause to our example query:</p>
1641
1642
1643<blockquote><pre>
1644SELECT three, min(three+four)+avg(four)
1645FROM examp2
1646WHERE three>four
1647GROUP BY three
1648HAVING avg(four)<10;
1649</pre></blockquote>
1650}
1651
1652Code {
1653addr opcode p1 p2 p3
1654---- ------------ ----- ----- -----------------------------------
16550 ColumnName 0 0 three
16561 ColumnName 1 0 min(three+four)+avg(four)
16572 AggReset 0 3
16583 AggInit 0 1 ptr(0x7903a0)
16594 AggInit 0 2 ptr(0x790700)
16605 Integer 0 0
16616 OpenRead 0 5 examp2
16627 VerifyCookie 0 909
16638 Rewind 0 26
16649 Column 0 0
166510 Column 0 1
166611 Le 1 25
166712 Column 0 0
166813 MakeKey 1 0 n
166914 AggFocus 0 17
167015 Column 0 0
167116 AggSet 0 0
167217 Column 0 0
167318 Column 0 1
167419 Add 0 0
167520 Integer 1 0
167621 AggFunc 0 1 ptr(0x7903a0)
167722 Column 0 1
167823 Integer 2 0
167924 AggFunc 0 1 ptr(0x790700)
168025 Next 0 9
168126 Close 0 0
168227 AggNext 0 37
168328 AggGet 0 2
168429 Integer 10 0 10
168530 Ge 1 27
168631 AggGet 0 0
168732 AggGet 0 1
168833 AggGet 0 2
168934 Add 0 0
169035 Callback 2 0
169136 Goto 0 27
169237 Noop 0 0
169338 Halt 0 0
1694}
1695
1696puts {
1697<p>The code generated in this last example is the same as the
1698previous except for the addition of two conditional jumps used
1699to implement the extra WHERE and HAVING clauses. The WHERE
1700clause is implemented by instructions 9 through 11 in the query
1701loop. The HAVING clause is implemented by instruction 28 through
170230 in the output loop.</p>
1703
1704<h2>Using SELECT Statements As Terms In An Expression</h2>
1705
1706<p>The very name "Structured Query Language" tells us that SQL should
1707support nested queries. And, in fact, two different kinds of nesting
1708are supported. Any SELECT statement that returns a single-row, single-column
1709result can be used as a term in an expression of another SELECT statement.
1710And, a SELECT statement that returns a single-column, multi-row result
1711can be used as the right-hand operand of the IN and NOT IN operators.
1712We will begin this section with an example of the first kind of nesting,
1713where a single-row, single-column SELECT is used as a term in an expression
1714of another SELECT. Here is our example:</p>
1715
1716<blockquote><pre>
1717SELECT * FROM examp
1718WHERE two!=(SELECT three FROM examp2
1719 WHERE four=5);
1720</pre></blockquote>
1721
1722<p>The way SQLite deals with this is to first run the inner SELECT
1723(the one against examp2) and store its result in a private memory
1724cell. SQLite then substitutes the value of this private memory
1725cell for the inner SELECT when it evaluates the outer SELECT.
1726The code looks like this:</p>
1727}
1728
1729Code {
1730addr opcode p1 p2 p3
1731---- ------------ ----- ----- -----------------------------------
17320 String 0 0
17331 MemStore 0 1
17342 Integer 0 0
17353 OpenRead 1 5 examp2
17364 VerifyCookie 0 909
17375 Rewind 1 13
17386 Column 1 1
17397 Integer 5 0 5
17408 Ne 1 12
17419 Column 1 0
174210 MemStore 0 1
174311 Goto 0 13
174412 Next 1 6
174513 Close 1 0
174614 ColumnName 0 0 one
174715 ColumnName 1 0 two
174816 Integer 0 0
174917 OpenRead 0 3 examp
175018 Rewind 0 26
175119 Column 0 1
175220 MemLoad 0 0
175321 Eq 1 25
175422 Column 0 0
175523 Column 0 1
175624 Callback 2 0
175725 Next 0 19
175826 Close 0 0
175927 Halt 0 0
1760}
1761
1762puts {
1763<p>The private memory cell is initialized to NULL by the first
1764two instructions. Instructions 2 through 13 implement the inner
1765SELECT statement against the examp2 table. Notice that instead of
1766sending the result to a callback or storing the result on a sorter,
1767the result of the query is pushed into the memory cell by instruction
176810 and the loop is abandoned by the jump at instruction 11.
1769The jump at instruction at 11 is vestigial and never executes.</p>
1770
1771<p>The outer SELECT is implemented by instructions 14 through 25.
1772In particular, the WHERE clause that contains the nested select
1773is implemented by instructions 19 through 21. You can see that
1774the result of the inner select is loaded onto the stack by instruction
177520 and used by the conditional jump at 21.</p>
1776
1777<p>When the result of a sub-select is a scalar, a single private memory
1778cell can be used, as shown in the previous
1779example. But when the result of a sub-select is a vector, such
1780as when the sub-select is the right-hand operand of IN or NOT IN,
1781a different approach is needed. In this case,
1782the result of the sub-select is
1783stored in a transient table and the contents of that table
1784are tested using the Found or NotFound operators. Consider this
1785example:</p>
1786
1787<blockquote><pre>
1788SELECT * FROM examp
1789WHERE two IN (SELECT three FROM examp2);
1790</pre></blockquote>
1791
1792<p>The code generated to implement this last query is as follows:</p>
1793}
1794
1795Code {
1796addr opcode p1 p2 p3
1797---- ------------ ----- ----- -----------------------------------
17980 OpenTemp 1 1
17991 Integer 0 0
18002 OpenRead 2 5 examp2
18013 VerifyCookie 0 909
18024 Rewind 2 10
18035 Column 2 0
18046 IsNull -1 9
18057 String 0 0
18068 PutStrKey 1 0
18079 Next 2 5
180810 Close 2 0
180911 ColumnName 0 0 one
181012 ColumnName 1 0 two
181113 Integer 0 0
181214 OpenRead 0 3 examp
181315 Rewind 0 25
181416 Column 0 1
181517 NotNull -1 20
181618 Pop 1 0
181719 Goto 0 24
181820 NotFound 1 24
181921 Column 0 0
182022 Column 0 1
182123 Callback 2 0
182224 Next 0 16
182325 Close 0 0
182426 Halt 0 0
1825}
1826
1827puts {
1828<p>The transient table in which the results of the inner SELECT are
1829stored is created by the <a href="opcode.html#OpenTemp">OpenTemp</a>
1830instruction at 0. This opcode is used for tables that exist for the
1831duration of a single SQL statement only. The transient cursor is always
1832opened read/write even if the main database is read-only. The transient
1833table is deleted automatically when the cursor is closed. The P2 value
1834of 1 means the cursor points to a BTree index, which has no data but can
1835have an arbitrary key.</p>
1836
1837<p>The inner SELECT statement is implemented by instructions 1 through 10.
1838All this code does is make an entry in the temporary table for each
1839row of the examp2 table with a non-NULL value for the "three" column.
1840The key for each temporary table entry is the "three" column of examp2
1841and the data is an empty string since it is never used.</p>
1842
1843<p>The outer SELECT is implemented by instructions 11 through 25. In
1844particular, the WHERE clause containing the IN operator is implemented
1845by instructions at 16, 17, and 20. Instruction 16 pushes the value of
1846the "two" column for the current row onto the stack and instruction 17
1847checks to see that it is non-NULL. If this is successful, execution
1848jumps to 20, where it tests to see if top of the stack matches any key
1849in the temporary table. The rest of the code is the same as what has
1850been shown before.</p>
1851
1852<h2>Compound SELECT Statements</h2>
1853
1854<p>SQLite also allows two or more SELECT statements to be joined as
1855peers using operators UNION, UNION ALL, INTERSECT, and EXCEPT. These
1856compound select statements are implemented using transient tables.
1857The implementation is slightly different for each operator, but the
1858basic ideas are the same. For an example we will use the EXCEPT
1859operator.</p>
1860
1861<blockquote><pre>
1862SELECT two FROM examp
1863EXCEPT
1864SELECT four FROM examp2;
1865</pre></blockquote>
1866
1867<p>The result of this last example should be every unique value
1868of the "two" column in the examp table, except any value that is
1869in the "four" column of examp2 is removed. The code to implement
1870this query is as follows:</p>
1871}
1872
1873Code {
1874addr opcode p1 p2 p3
1875---- ------------ ----- ----- -----------------------------------
18760 OpenTemp 0 1
18771 KeyAsData 0 1
18782 Integer 0 0
18793 OpenRead 1 3 examp
18804 VerifyCookie 0 909
18815 Rewind 1 11
18826 Column 1 1
18837 MakeRecord 1 0
18848 String 0 0
18859 PutStrKey 0 0
188610 Next 1 6
188711 Close 1 0
188812 Integer 0 0
188913 OpenRead 2 5 examp2
189014 Rewind 2 20
189115 Column 2 1
189216 MakeRecord 1 0
189317 NotFound 0 19
189418 Delete 0 0
189519 Next 2 15
189620 Close 2 0
189721 ColumnName 0 0 four
189822 Rewind 0 26
189923 Column 0 0
190024 Callback 1 0
190125 Next 0 23
190226 Close 0 0
190327 Halt 0 0
1904}
1905
1906puts {
1907<p>The transient table in which the result is built is created by
1908instruction 0. Three loops then follow. The loop at instructions
19095 through 10 implements the first SELECT statement. The second
1910SELECT statement is implemented by the loop at instructions 14 through
191119. Finally, a loop at instructions 22 through 25 reads the transient
1912table and invokes the callback once for each row in the result.</p>
1913
1914<p>Instruction 1 is of particular importance in this example. Normally,
1915the Column instruction extracts the value of a column from a larger
1916record in the data of an SQLite file entry. Instruction 1 sets a flag on
1917the transient table so that Column will instead treat the key of the
1918SQLite file entry as if it were data and extract column information from
1919the key.</p>
1920
1921<p>Here is what is going to happen: The first SELECT statement
1922will construct rows of the result and save each row as the key of
1923an entry in the transient table. The data for each entry in the
1924transient table is a never used so we fill it in with an empty string.
1925The second SELECT statement also constructs rows, but the rows
1926constructed by the second SELECT are removed from the transient table.
1927That is why we want the rows to be stored in the key of the SQLite file
1928instead of in the data -- so they can be easily located and deleted.</p>
1929
1930<p>Let's look more closely at what is happening here. The first
1931SELECT is implemented by the loop at instructions 5 through 10.
1932Instruction 5 intializes the loop by rewinding its cursor.
1933Instruction 6 extracts the value of the "two" column from "examp"
1934and instruction 7 converts this into a row. Instruction 8 pushes
1935an empty string onto the stack. Finally, instruction 9 writes the
1936row into the temporary table. But remember, the PutStrKey opcode uses
1937the top of the stack as the record data and the next on stack as the
1938key. For an INSERT statement, the row generated by the
1939MakeRecord opcode is the record data and the record key is an integer
1940created by the NewRecno opcode. But here the roles are reversed and
1941the row created by MakeRecord is the record key and the record data is
1942just an empty string.</p>
1943
1944<p>The second SELECT is implemented by instructions 14 through 19.
1945Instruction 14 intializes the loop by rewinding its cursor.
1946A new result row is created from the "four" column of table "examp2"
1947by instructions 15 and 16. But instead of using PutStrKey to write this
1948new row into the temporary table, we instead call Delete to remove
1949it from the temporary table if it exists.</p>
1950
1951<p>The result of the compound select is sent to the callback routine
1952by the loop at instructions 22 through 25. There is nothing new
1953or remarkable about this loop, except for the fact that the Column
1954instruction at 23 will be extracting a column out of the record key
1955rather than the record data.</p>
1956
1957<h2>Summary</h2>
1958
1959<p>This article has reviewed all of the major techniques used by
1960SQLite's VDBE to implement SQL statements. What has not been shown
1961is that most of these techniques can be used in combination to
1962generate code for an appropriately complex query statement. For
1963example, we have shown how sorting is accomplished on a simple query
1964and we have shown how to implement a compound query. But we did
1965not give an example of sorting in a compound query. This is because
1966sorting a compound query does not introduce any new concepts: it
1967merely combines two previous ideas (sorting and compounding)
1968in the same VDBE program.</p>
1969
1970<p>For additional information on how the SQLite library
1971functions, the reader is directed to look at the SQLite source
1972code directly. If you understand the material in this article,
1973you should not have much difficulty in following the sources.
1974Serious students of the internals of SQLite will probably
1975also what to make a careful study of the VDBE opcodes
1976as documented <a href="opcode.html">here</a>. Most of the
1977opcode documentation is extracted from comments in the source
1978code using a script so you can also get information about the
1979various opcodes directly from the <b>vdbe.c</b> source file.
1980If you have successfully read this far, you should have little
1981difficulty understanding the rest.</p>
1982
1983<p>If you find errors in either the documentation or the code,
1984feel free to fix them and/or contact the author at
1985<a href="mailto:drh@hwaci.com">drh@hwaci.com</a>. Your bug fixes or
1986suggestions are always welcomed.</p>
1987}
1988footer $rcsid