# page_content

c2: Compile-time Options
c3: 10. Analysis and Debugging Options
c5: compile.html#_analysis_and_debugging_options
c4:
SQLITE_DEBUG
  The SQLite source code contains literally thousands of assert() statements
  used to verify internal assumptions and subroutine preconditions and
  postconditions.  These assert() statements are normally turned off
  (they generate no code) since turning them on makes SQLite run approximately
  three times slower.  But for testing and analysis, it is useful to turn
  the assert() statements on.  The SQLITE_DEBUG compile-time option does this.
  SQLITE_DEBUG also enables some other debugging features, such as
  special PRAGMA statements that turn on tracing and listing features
  used for troubleshooting and analysis of the VDBE and code generator.

SQLITE_MEMDEBUG
  The SQLITE_MEMDEBUG option causes an instrumented 
  debugging memory allocator
  to be used as the default memory allocator within SQLite.  The
  instrumented memory allocator checks for misuse of dynamically allocated
  memory.  Examples of misuse include using memory after it is freed,
  writing off the ends of a memory allocation, freeing memory not previously
  obtained from the memory allocator, or failing to initialize newly
  allocated memory.


c2: Compile-time Options
c3: 11. Windows-Specific Options
c5: compile.html#_windows_specific_options
c4:
SQLITE_WIN32_HEAP_CREATE
  This option forces the Win32 native memory allocator, when enabled, to
  create a private heap to hold all memory allocations.

SQLITE_WIN32_MALLOC_VALIDATE
  This option forces the Win32 native memory allocator, when enabled, to
  make strategic calls into the HeapValidate() function if assert() is also
  enabled.


c2: Compile-time Options
c3: 12. Compiler Linkage and Calling Convention Control
c5: compile.html#compiler_linkage_and_calling_convention_control
c4:
The following macros specify interface details
for certain kinds of SQLite builds.  The Makefiles will normally
handle setting these macros automatically.  Application developers should
not need to worry with these macros.  The following documentation about these 
macros is included for completeness.


SQLITE_API
  This macro identifies an externally visible interface for SQLite.
  This macro is sometimes set to "extern".  But the definition is
  compiler-specific.

SQLITE_APICALL
  This macro identifies the calling convention used by public interface
  routines in SQLite which accept a fixed number of arguments.
  This macro is normally defined to be nothing,
  though on Windows builds it can sometimes be set to "__cdecl" or "__stdcall".
  The "__cdecl" setting is the default, but "__stdcall" is used when SQLite
  is intended to be compiled as a Windows system library.
  
  A single function declaration should contain no more than one of
  the following:  SQLITE_APICALL, SQLITE_CDECL, or SQLITE_SYSAPI.

SQLITE_CALLBACK
  This macro specifies the calling convention used with callback pointers
  in SQLite.  This macro is normally defined to be nothing, though on Windows
  builds it can sometimes be set to "__cdecl" or "__stdcall".  The
  "__cdecl" setting is the default, but "__stdcall" is used when SQLite
  is intended to be compiled as a Windows system library.

SQLITE_CDECL
  This macro specifies the calling convention used by varargs interface
  routines in SQLite.  This macro is normally defined to be nothing,
  though on Windows builds it can sometimes be set to "__cdecl".  This
  macro is used on varargs routines and so cannot be set to "__stdcall"
  since the __stdcall calling convention does not support varargs functions.
  
  A single function declaration should contain no more than one of
  the following:  SQLITE_APICALL, SQLITE_CDECL, or SQLITE_SYSAPI.

SQLITE_EXTERN
  This macro specifies linkage for public interface variables in SQLite.
  It should normally be allowed to default to "extern".

SQLITE_STDCALL
  This macro is no longer used and is now deprecated.

SQLITE_SYSAPI
  This macro identifies the calling convention used by operating system
  interfaces for the target platform for an SQLite build.
  This macro is normally defined to be nothing,
  though on Windows builds it can sometimes be set to "__stdcall".
  
  A single function declaration should contain no more than one of
  the following:  SQLITE_APICALL, SQLITE_CDECL, or SQLITE_SYSAPI.

SQLITE_TCLAPI
  This macro specifies the calling convention used by the 
  TCL library interface routines.
  This macro is not used by the SQLite core, but only by the TCL Interface
  and TCL test suite.
  This macro is normally defined to be nothing,
  though on Windows builds it can sometimes be set to "__cdecl".  This
  macro is used on TCL library interface routines which are always compiled
  as __cdecl, even on platforms that prefer to use __stdcall, so this
  macro should not be set to __stdcall unless the platform has a custom
  TCL library build that supports __stdcall.
  
  This macro may not be used in combination with any of SQLITE_APICALL,
  SQLITE_CALLBACK, SQLITE_CDECL or SQLITE_SYSAPI.


c2: Indexes On Expressions
c5: expridx.html#
c4:
Normally, an SQL index references columns of a table.  But an index
can also be formed on expressions involving table columns.


As an example, consider the following table that tracks
dollar-amount changes on various "accounts":

CREATE TABLE account_change(
  chng_id INTEGER PRIMARY KEY,
  acct_no INTEGER REFERENCES account,
  location INTEGER REFERENCES locations,
  amt INTEGER,  -- in cents
  authority TEXT,
  comment TEXT
);
CREATE INDEX acctchng_magnitude ON account_change(acct_no, abs(amt));



Each entry in the account_change table records a deposit or a withdrawal
into an account.  Deposits have a positive "amt" and withdrawals have
a negative "amt".


The acctchng_magnitude index is over the account number ("acct_no") and
on the absolute value of the amount.  This index allows one to do 
efficient queries over the magnitude of a change to the account.
For example, to list all changes to account number $xyz that are
more than $100.00, one can say:


SELECT * FROM account_change WHERE acct_no=$xyz AND abs(amt)>=10000;



Or, to list all changes to one particular account ($xyz) in order of
decreasing magnitude, one can write:

SELECT * FROM account_change WHERE acct_no=$xyz
 ORDER BY abs(amt) DESC;



Both of the above example queries would work fine without the
acctchng_magnitude index.
The acctchng_magnitude index merely helps the queries to run
faster, especially on databases where there are many entries in
the table for each account.


c2: Indexes On Expressions
c3: 1. How To Use Indexes On Expressions
c5: expridx.html#how_to_use_indexes_on_expressions
c4:
Use a CREATE INDEX statement to create a new index on one or more
expressions just like you would to create an index on columns.  The only
difference is that expressions are listed as the elements to be indexed
rather than column names.


The SQLite query planner will consider using an index on an expression
when the expression that is indexed appears in the WHERE clause or in
the ORDER BY clause of a query, exactly as it is written in the
CREATE INDEX statement.  The query planner does not do algebra.  In order
to match WHERE clause constraints and ORDER BY terms to indexes, SQLite
requires that the expressions be the same, except for minor syntactic
differences such as white-space changes.  So if you have:

CREATE TABLE t2(x,y,z);
CREATE INDEX t2xy ON t2(x+y);



And then you run the query:

SELECT * FROM t2 WHERE y+x=22;



Then the index will not be used because 
the expression on the CREATE INDEX
statement (x+y) is not the same as the expression as it appears in the 
query (y+x).  The two expressions might be mathematically equivalent, but
the SQLite query planner insists that they be the same, not merely
equivalent.  Consider rewriting the query thusly:

SELECT * FROM t2 WHERE x+y=22;



This second query will likely use the index because now the expression
in the WHERE clause (x+y) matches the expression in the index exactly.


c2: Indexes On Expressions
c3: 2. Restrictions
c5: expridx.html#restrictions
c4:
There are certain reasonable restrictions on expressions that appear in
CREATE INDEX statements:



Expressions in CREATE INDEX statements
may only refer to columns of the table being indexed, not to
columns in other tables.


Expressions in CREATE INDEX statements
may contain function calls, but only to functions whose output
is always determined completely by its input parameters (a.k.a.:
deterministic functions).  Obviously, functions like random() will not
work well in an index.  But also functions like sqlite_version(), though
they are constant across any one database connection, are not constant
across the life of the underlying database file, and hence may not be
used in a CREATE INDEX statement.


Note that application-defined SQL functions are by default considered
non-deterministic and may not be used in a CREATE INDEX statement unless
the SQLITE_DETERMINISTIC flag is used when the function is registered.


Expressions in CREATE INDEX statements may not use subqueries.


Expressions may only be used in CREATE INDEX statements, not within
UNIQUE or PRIMARY KEY constraints within the CREATE TABLE statement.


c2: Indexes On Expressions
c3: 3. Compatibility
c5: expridx.html#compatibility
c4:
The ability to index expressions was added to SQLite with 
version 3.9.0 (2015-10-14).  A database that uses an index on
expressions will not be usable by earlier versions of SQLite.


c2: Using SQLite In Multi-Threaded Applications
c3: 1. Overview
c5: threadsafe.html#overview
c4:
SQLite supports three different threading modes:


Single-thread.
In this mode, all mutexes are disabled and SQLite is unsafe to use in
more than a single thread at once.

Multi-thread.
In this mode, SQLite can be safely used by multiple threads provided that
no single database connection is used simultaneously in two or more threads.


Serialized.
In serialized mode, SQLite can be safely used by multiple threads with no
restriction.



The threading mode can be selected at compile-time (when the SQLite
library is being compiled from source code) or at start-time (when the
application that intends to use SQLite is initializing) or at
run-time (when a new SQLite database connection is being created).
Generally speaking, run-time overrides start-time and start-time
overrides compile-time.  Except, single-thread mode cannot be 
overridden once selected.



The default mode is serialized.


c2: Using SQLite In Multi-Threaded Applications
c3: 2. Compile-time selection of threading mode
c5: threadsafe.html#compile_time_selection_of_threading_mode
c4:
Use the SQLITE_THREADSAFE compile-time parameter to select the
threading mode.  If no SQLITE_THREADSAFE compile-time parameter is
present, then serialized mode is used.
This can be made explicit with 
-DSQLITE_THREADSAFE=1.
With
-DSQLITE_THREADSAFE=0 the threading mode is
single-thread.  With
-DSQLITE_THREADSAFE=2 the threading mode is
multi-thread.



The return value of the sqlite3_threadsafe() interface is the value
of SQLITE_THREADSAFE set at compile-time. It does not reflect changes
to the threading mode made at runtime via the sqlite3_config()
interface or by flags given as the third argument to sqlite3_open_v2().



If single-thread mode is selected at compile-time, then critical
mutexing logic is omitted from the build and it is impossible to
enable either multi-thread or serialized modes at start-time or
run-time.


c2: Using SQLite In Multi-Threaded Applications
c3: 3. Start-time selection of threading mode
c5: threadsafe.html#start_time_selection_of_threading_mode
c4:
Assuming that the compile-time threading mode is not single-thread, then
the threading mode can be changed during initialization using the
sqlite3_config() interface.  The SQLITE_CONFIG_SINGLETHREAD verb
puts SQLite into single-thread mode, the SQLITE_CONFIG_MULTITHREAD
verb sets multi-thread mode, and the SQLITE_CONFIG_SERIALIZED verb
sets serialized mode.


c2: Using SQLite In Multi-Threaded Applications
c3: 4. Run-time selection of threading mode
c5: threadsafe.html#run_time_selection_of_threading_mode
c4:
If single-thread mode has not been selected at compile-time or start-time,
then individual database connections can be created as either multi-thread
or serialized.  It is not possible to downgrade an individual database
connection to single-thread mode.  Nor is it possible to escalate an
individual database connection if the compile-time or start-time mode
is single-thread.

The threading mode for an individual database connection is determined
by flags given as the third argument to sqlite3_open_v2().  The
SQLITE_OPEN_NOMUTEX flag causes the database connection to be in the
multi-thread mode and the SQLITE_OPEN_FULLMUTEX flag causes the connection
to be in serialized mode.  If neither flag is specified or if
sqlite3_open() or sqlite3_open16() are used instead of 
sqlite3_open_v2(), then the default
mode determined by the compile-time and start-time settings is used.


c2: The SQLite R*Tree Module
c3: 1. Overview
c5: rtree.html#overview
c4:
An R-Tree is a special
index that is designed for doing range queries.  R-Trees are most commonly
used in geospatial systems where each entry is a rectangle with minimum and
maximum X and Y coordinates.  Given a query rectangle, an R-Tree is able
to quickly find all entries that are contained within the query rectangle
or which overlap the query rectangle.  This idea is easily extended to
three dimensions for use in CAD systems.  R-Trees also find use in time-domain
range look-ups.  For example, suppose a database records the starting and
ending times for a large number of events.  A R-Tree is able to quickly
find all events that were active at any time during a given
time interval, or all events that started during a particular time interval,
or all events that both started and ended within a given time interval.
And so forth.



The R-Tree concept originated with 
Toni Guttman: 
R-Trees: A Dynamic Index Structure for Spatial Searching,
Proc. 1984 ACM SIGMOD International Conference on Management of Data,
pp. 47-57.
The implementation found in SQLite is a refinement of Guttman's original
idea, commonly called "R*Trees", that was described by
Norbert Beckmann, Hans-Peter Kriegel, Ralf Schneider, Bernhard Seeger:
The R*-Tree: An Efficient and Robust Access Method for Points
and Rectangles. SIGMOD Conference 1990: 322-331.


c2: The SQLite R*Tree Module
c3: 2. Compiling The R*Tree Module
c5: rtree.html#compiling_the_r_tree_module
c4:
The source code to the SQLite R*Tree module is included as part
of the amalgamation but is disabled by default.  To enable the
R*Tree module, simply compile with the SQLITE_ENABLE_RTREE 
C-preprocessor macro defined.  With many compilers, this is accomplished
by adding the option "-DSQLITE_ENABLE_RTREE=1" to the compiler
command-line.


c2: The SQLite R*Tree Module
c3: 3. Using the R*Tree Module
c5: rtree.html#using_the_r_tree_module
c4:
The SQLite R*Tree module is implemented as a
virtual table.  Each R*Tree index is a
virtual table with an odd number of columns between 3 and 11.
The first column is always a 64-bit signed integer primary key.
The other columns are pairs, one pair per dimension, containing the
minimum and maximum values for that dimension, respectively.
A 1-dimensional R*Tree thus has 3 columns.  
A 2-dimensional R*Tree has 5 columns.
A 3-dimensional R*Tree has 7 columns.
A 4-dimensional R*Tree has 9 columns.
And a 5-dimensional R*Tree has 11 columns.  The SQLite R*Tree implementation
does not support R*Trees wider than 5 dimensions.



The first column of an SQLite R*Tree is similar to an integer primary 
key column of a normal SQLite table. It may only store a 64-bit signed
integer value. Inserting a NULL value into this column causes SQLite
to automatically generate a new unique primary key value. If an attempt
is made to insert any other non-integer value into this column,
the r-tree module silently converts it to an integer before writing it
into the database.

The min/max-value pair columns are stored as 32-bit floating point values for
"rtree" virtual tables or as 32-bit signed integers in "rtree_i32" virtual
tables.  Unlike regular SQLite tables which can store data in a variety of
datatypes and formats, the R*Tree rigidly enforce these storage types. 
If any other type of value is inserted into such a column, the r-tree
module silently converts it to the required type before writing the
new record to the database.


c2: The SQLite R*Tree Module
c3: 3.1. Creating An R*Tree Index
c5: rtree.html#creating_an_r_tree_index
c4:
A new R*Tree index is created as follows:


CREATE VIRTUAL TABLE &lt;name&gt; USING rtree(&lt;column-names&gt;);



The &lt;name&gt; is the name your application chooses for the
R*Tree index and &lt;column-names&gt; is a comma separated list
of between 3 and 11 columns.
The virtual &lt;name&gt; table creates three shadow tables to actually
store its content.  The names of these shadow tables are:


&lt;name&gt;_node
&lt;name&gt;_rowid
&lt;name&gt;_parent




The shadow tables are ordinary SQLite data tables.  You can query them 
directly if you like, though this unlikely to reveal anything particularly
useful. 
And you can UPDATE, DELETE, INSERT or even DROP 
the shadow tables, though doing so will corrupt your R*Tree index.
So it is best to simply ignore the shadow tables.  Recognize that they
hold your R*Tree index information and let it go as that.



As an example, consider creating a two-dimensional R*Tree index for use in 
spatial queries:


CREATE VIRTUAL TABLE demo_index USING rtree(
   id,              -- Integer primary key
   minX, maxX,      -- Minimum and maximum X coordinate
   minY, maxY       -- Minimum and maximum Y coordinate
);


c2: The SQLite R*Tree Module
c3: 3.1.1. Column naming details
c5: rtree.html#column_naming_details
c4:
In the argments to "rtree" in the CREATE VIRTUAL TABLE statement, the
names of the columns are taken from the first token of each argument.
All subsequent tokens within each argument are silently ignored.
This means, for example, that if you try to give a column a
type affinity or add a constraint such as UNIQUE or NOT NULL or DEFAULT to
a column, those extra tokens are accepted as valid, but they do not change
the behavior of the rtree.
In an RTREE virtual table, the first column always has a
type affinity of INTEGER and all other data columns have a
type affinity of REAL.
In an RTREE_I32 virtual table, all columns have type affinity of INTEGER.


Recommended practice is to omit any extra tokens in the rtree specification.
Let each argument to "rtree" be a single ordinary label that is the name of
the corresponding column, and omit all other tokens from the argument list.


c2: The SQLite R*Tree Module
c3: 3.2. Populating An R*Tree Index
c5: rtree.html#populating_an_r_tree_index
c4:
The usual INSERT, UPDATE, and DELETE commands work on an R*Tree
index just like on regular tables.  So to insert some data into our sample
R*Tree index, we can do something like this:


INSERT INTO demo_index VALUES
  (28215, -80.781227, -80.604706, 35.208813, 35.297367),
  (28216, -80.957283, -80.840599, 35.235920, 35.367825),
  (28217, -80.960869, -80.869431, 35.133682, 35.208233),
  (28226, -80.878983, -80.778275, 35.060287, 35.154446),
  (28227, -80.745544, -80.555382, 35.130215, 35.236916),
  (28244, -80.844208, -80.841988, 35.223728, 35.225471),
  (28262, -80.809074, -80.682938, 35.276207, 35.377747),
  (28269, -80.851471, -80.735718, 35.272560, 35.407925),
  (28270, -80.794983, -80.728966, 35.059872, 35.161823),
  (28273, -80.994766, -80.875259, 35.074734, 35.172836),
  (28277, -80.876793, -80.767586, 35.001709, 35.101063),
  (28278, -81.058029, -80.956375, 35.044701, 35.223812),
  (28280, -80.844208, -80.841972, 35.225468, 35.227203),
  (28282, -80.846382, -80.844193, 35.223972, 35.225655);




The entries above are bounding boxes (longitude and latitude) for 14
zipcodes near Charlotte, NC.  A real database would have many thousands,
millions, or billions of such entries, but this small 14-row sample will
be sufficient to illustrate the ideas.


c2: The SQLite R*Tree Module
c3: 3.3. Querying An R*Tree Index
c5: rtree.html#querying_an_r_tree_index
c4:
Any valid query will work against an R*Tree index.  The R*Tree
implementation just makes some kinds of queries especially
efficient.  Queries against the primary key are efficient:


SELECT * FROM demo_index WHERE id=28269;




Of course, an ordinary SQLite table will also do a query against its
integer primary key efficiently, so the previous is not important.
The big reason for using an R*Tree is so that
you can efficiently do range queries against the coordinate
ranges.  For example, the main office of the SQLite project is
located at 35.37785, -80.77470. 
To find which zipcodes might service that office, one could right:


SELECT id FROM demo_index
 WHERE minX&lt;=-80.77470 AND maxX&gt;=-80.77470
   AND minY&lt;=35.37785  AND maxY&gt;=35.37785;




The query above will quickly locate all zipcodes that contain
the SQLite main office in their bounding box, even if the
R*Tree contains many entries.  The previous is an example
of a "contained-within" query.  The R*Tree also supports "overlapping"
queries.  For example, to find all zipcode bounding boxes that overlap
with the 28269 zipcode:


SELECT A.id FROM demo_index AS A, demo_index AS B
 WHERE A.maxX&gt;=B.minX AND A.minX&lt;=B.maxX
   AND A.maxY&gt;=B.minY AND A.minY&lt;=B.maxY
   AND B.id=28269;




This second query will find both 28269 entry (since every bounding box
overlaps with itself) and also other zipcode that is close enough to
28269 that their bounding boxes overlap.



Note that it is not necessary for all coordinates in an R*Tree index
to be constrained in order for the index search to be efficient.
One might, for example, want to query all objects that overlap with
the 35th parallel:


SELECT id FROM demo_index
 WHERE maxY&gt;=35.0  AND minY&lt;=35.0;




But, generally speaking, the more constraints that the R*Tree module
has to work with, and the smaller the bounding box, the faster the
results will come back.


c2: The SQLite R*Tree Module
c3: 3.4. Roundoff Error
c5: rtree.html#roundoff_error
c4:
By default, coordinates are stored in an R*Tree using 32-bit floating
point values.  When a coordinate cannot be exactly represented by a
32-bit floating point number, the lower-bound coordinates are rounded down
and the upper-bound coordinates are rounded up.  Thus, bounding boxes might
be slightly larger than specified, but will never be any smaller.  This
is exactly what is desired for doing the more common "overlapping" queries
where the application wants to find every entry in the R*Tree that overlaps
a query bounding box.  Rounding the entry bounding boxes outward might cause a
few extra entries to appears in an overlapping query if the edge of the
entry bounding box corresponds to an edge of the query bounding box.  But
the overlapping query will never miss a valid table entry.  

However, for a "contained-within" style query, rounding the bounding
boxes outward might cause some entries to be excluded from the result set
if the edge of the entry bounding box corresponds to the edge of the query
bounding box.  To guard against this, applications should expand their
contained-within query boxes slightly (by 0.000012%) by rounding down the
lower coordinates and rounding up the top coordinates, in each dimension.


c2: The SQLite R*Tree Module
c3: 3.5. Reading And Writing At The Same Time
c5: rtree.html#reading_and_writing_at_the_same_time
c4:
It is the nature of the Guttman R-Tree algorithm that any write might
radically restructure the tree, and in the process change the scan order
of the nodes.  For this reason, it is not generally possible to modify
the R-Tree in the middle of a query of the R-Tree.  Attempts to do so
will fail with a SQLITE_LOCKED "database table is locked" error.


So, for example, suppose an application runs one query against an R-Tree like
this:

SELECT id FROM demo_index
 WHERE maxY&gt;=35.0  AND minY&lt;=35.0;



Then for each "id" value returned, suppose the application creates an 
UPDATE statement like the following and binds the "id" value returned against
the "?1" parameter:

UPDATE demo_index SET maxY=maxY+0.5 WHERE id=?1;



Then the UPDATE might fail with an SQLITE_LOCKED error.  The reason is that
the initial query has not run to completion.  It is remembering its place
in the middle of a scan of the R-Tree.  So an update to the R-Tree cannot
be tolerated as this would disrupt the scan.


This is a limitation of the R-Tree extension only.  Ordinary tables in
SQLite are able to read and write at the same time.  Other virtual tables
might (or might not) also that capability.  And R-Tree can appear to read
and write at the same time in some circumstances, if it can figure out how
to reliably run the query to completion before starting the update.  But
you shouldn't count on that for every query.  Generally speaking, it is
best to avoid running queries and updates to the same R-Tree at the same
time.


If you really need to update an R-Tree based on complex queries against
the same R-Tree, it is best to run the complex queries first and store
the results in a temporary table, then update the R-Tree based on the values
stored in the temporary table.


c2: The SQLite R*Tree Module
c3: 4. Using R*Trees Effectively
c5: rtree.html#using_r_trees_effectively
c4:
For SQLite versions prior to 3.24.0 (2018-06-04),
the only information that an R*Tree index stores about an object is
its integer ID and its bounding box.  Additional information needs to
be stored in separate tables and related to the R*Tree index using
the primary key.  For the example above, one might create an auxiliary
table as follows:


CREATE TABLE demo_data(
  id INTEGER PRIMARY KEY,  -- primary key
  objname TEXT,            -- name of the object
  objtype TEXT,            -- object type
  boundary BLOB            -- detailed boundary of object
);



In this example, the demo_data.boundary field is intended to hold some
kind of binary representation of the precise boundaries of the object.
The R*Tree index only holds an axis-aligned rectangular boundary for the
object.  The R*Tree boundary is just an approximation of the true object
boundary.  So what typically happens is that the R*Tree index is used to
narrow a search down to a list of candidate objects and then more detailed
and expensive computations are done on each candidate to find if the
candidate truly meets the search criteria.



Key Point:
An R*Tree index does not normally provide the exact answer but merely
reduces the set of potential answers from millions to dozens.



Suppose the demo_data.boundary field holds some proprietary data description
of a complex two-dimensional boundary for a zipcode and suppose that the
application has used the sqlite3_create_function() interface to
created an application-defined function "contained_in(boundary,lat,long)"
that accepts the demo_data.boundary object and a latitute and longitude
and returns return true or false if the lat/long is contained within
the boundary.
One may assume that "contained_in()" is a relatively slow
functions that we do not want to invoke too frequently.
Then an efficient way to find the specific ZIP code for the main
SQLite office would be to run a query like this:



SELECT objname FROM demo_data, demo_index
 WHERE demo_data.id=demo_index.id
   AND contained_in(demo_data.boundary, 35.37785, -80.77470)
   AND minX&lt;=-80.77470 AND maxX&gt;=-80.77470
   AND minY&lt;=35.37785  AND maxY&gt;=35.37785;


Notice how the query above works:  The R*Tree index runs in the outer
loop to find entries that contain the SQLite main office in their
boundary box.
For each row found, SQLite looks up
the corresponding entry in the demo_data table.  It then uses the boundary
field from the demo_data table as a parameter to the contained_in()
function and if that function returns true, then we know the sought after
coordinate is in that ZIP code boundary.

One would get the same answer without the use of the R*Tree index
using the following simpler query:

SELECT objname FROM demo_data
 WHERE contained_in(demo_data.boundary, 35.37785, -80.77470);


The problem with this latter query is that it must apply the
contained_in() function to all entries in the demo_data table.
The use of the R*Tree in the penultimate query reduces the number of
calls to contained_in() function to a small subset of the entire table.
The R*Tree index did not find the exact answer itself, it merely
limited the search space.


c2: The SQLite R*Tree Module
c3: 4.1. Auxiliary Columns
c5: rtree.html#auxiliary_columns
c4:
Beginning with SQLite version 3.24.0 (2018-06-04), r-tree tables
can have auxiliary columns that store arbitrary data.
Auxiliary columns can be used in place of
secondary tables such as "demo_data".


Auxiliary columns are marked with a "+" symbol before the column name.
Auxiliary columns must come after all of the coordinate boundary columns.
An RTREE table can have no more than 100 columns total.  In other words,
the count of columns including the integer primary key column, 
the coordinate boundary columns, and all auxiliary columns must be 100 or less.
The following example shows an r-tree table with auxiliary columns that
is equivalent to the two tables "demo_index" and "demo_data" above:

CREATE VIRTUAL TABLE demo_index2 USING rtree(
   id,              -- Integer primary key
   minX, maxX,      -- Minimum and maximum X coordinate
   minY, maxY,      -- Minimum and maximum Y coordinate
   +objname TEXT,   -- name of the object
   +objtype TEXT,   -- object type
   +boundary BLOB   -- detailed boundary of object
);



By combining location data and related information into the same
table, auxiliary columns can provide a cleaner model
and reduce the need to joins.
For example, the earlier
join between demo_index and demo_data can now
be written as a simple query, like this:

SELECT objname FROM demo_index2
 WHERE contained_in(boundary, 35.37785, -80.77470)
   AND minX&lt;=-80.77470 AND maxX&gt;=-80.77470
   AND minY&lt;=35.37785  AND maxY&gt;=35.37785;


c2: The SQLite R*Tree Module
c3: 4.1.1. Limitations
c5: rtree.html#limitations
c4:
For auxiliary columns, only the name of the column matters.
The type affinity is ignored.
Constraints such as NOT NULL, UNIQUE, REFERENCES, or CHECK
are also ignored.  However, future versions
of SQLite might start paying attention to the type affinity and
constraints, so users of auxiliary columns are advised to leave
both blank, to avoid future compatibility problems.


c2: The SQLite R*Tree Module
c3: 5. Integer-Valued R-Trees
c5: rtree.html#integer_valued_r_trees
c4:
The default virtual table ("rtree") stores coordinates as
single-precision (4-byte) floating point numbers.  If integer coordinates
are desired, declare the table using "rtree_i32" instead:

CREATE VIRTUAL TABLE intrtree USING rtree_i32(id,x0,x1,y0,y1,z0,z1);



An rtree_i32 stores coordinates as 32-bit signed integers.  
Even though it stores values using integer, the rtree_i32 virtual
table still uses floating point computations internally as part of
the r-tree algorithm.


c2: The SQLite R*Tree Module
c3: 6. Custom R-Tree Queries
c5: rtree.html#custom_r_tree_queries
c4:
By using standard SQL expressions in the WHERE clause of a SELECT query,
a programmer can query for all R*Tree entries that 
intersect with or are contained within a particular bounding-box.
Custom R*Tree queries, using the MATCH
operator in the WHERE clause of a SELECT, allow the programmer to query for 
the set of R*Tree entries that intersect any arbitrary region or shape, not 
just a box.  This capability is useful, for example, in computing the 
subset of objects in the R*Tree that are visible from a camera positioned 
in 3-D space.

Regions for custom R*Tree queries are defined by R*Tree geometry callbacks
implemented by the application and registered with SQLite via a call to one
of the following two APIs:

int sqlite3_rtree_query_callback(
  sqlite3 *db,
  const char *zQueryFunc,
  int (*xQueryFunc)(sqlite3_rtree_query_info*),
  void *pContext,
  void (*xDestructor)(void*)
);
int sqlite3_rtree_geometry_callback(
  sqlite3 *db,
  const char *zGeom,
  int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
  void *pContext
);


The sqlite3_rtree_query_callback() became available with SQLite
version 3.8.5 (2014-06-04) and is the preferred interface.
The sqlite3_rtree_geometry_callback() is an older and less flexible
interface that is supported for backwards compatibility.

A call to one of the above APIs creates a new SQL function named by the
second parameter (zQueryFunc or zGeom).  When that SQL function appears
on the right-hand side of the MATCH operator and the left-hand side of the
MATCH operator is any column in the R*Tree virtual table, then the callback 
defined by the third argument (xQueryFunc or xGeom) is invoked to determine
if a particular object or subtree overlaps the desired region.

For example, a query like the following might be used to find all
R*Tree entries that overlap with a circle centered a 45.3,22.9 with a
radius of 5.0:

SELECT id FROM demo_index WHERE id MATCH circle(45.3, 22.9, 5.0)


The SQL syntax for custom queries is the same regardless of which
interface, sqlite3_rtree_geometry_callback() or sqlite3_rtree_query_callback(),
is used to register the SQL function.  However, the newer query-style
callbacks give the application greater control over how the query proceeds.


c2: The SQLite R*Tree Module
c3: 6.1. The Legacy xGeom Callback
c5: rtree.html#the_legacy_xgeom_callback
c4:
The legacy xGeom callback is invoked with four arguments.  The first
argument is a pointer to an sqlite3_rtree_geometry structure which provides
information about how the SQL function was invoked.  The second argument
is the number of coordinates in each r-tree entry, and is always the same
for any given R*Tree.  The number of coordinates is 2 for a 1-dimensional R*Tree,
4 for a 2-dimensional R*Tree, 6 for a 3-dimensional R*Tree, and so forth.
The third argument, aCoord[], is an array of nCoord coordinates that defines
a bounding box to be tested.  The last argument is a pointer into which 
the callback result should be written.  The result is zero
if the bounding-box defined by aCoord[] is completely outside
the region defined by the xGeom callback and the result is non-zero if
the bounding-box is inside or overlaps with the xGeom region.  The xGeom
callback should normally return SQLITE_OK.  If xGeom returns anything other
than SQLITE_OK, then the r-tree query will abort with an error.

The sqlite3_rtree_geometry structure that the first argument to the
xGeom callback points to has a structure shown below.  The exact same
sqlite3_rtree_geometry
structure is used for every callback for same MATCH operator in the same
query.  The contents of the sqlite3_rtree_geometry
structure are initialized by SQLite but are
not subsequently modified.  The callback is free to make changes to the
pUser and xDelUser elements of the structure if desired.

typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
struct sqlite3_rtree_geometry {
  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
  int nParam;                     /* Size of array aParam */
  double *aParam;                 /* Parameters passed to SQL geom function */
  void *pUser;                    /* Callback implementation user data */
  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
};


The pContext member of the sqlite3_rtree_geometry
structure is always set to a copy of the pContext
argument passed to sqlite3_rtree_geometry_callback() when the
callback is registered. The aParam[] array (size nParam) contains the parameter
values passed to the SQL function on the right-hand side of the MATCH operator.
In the example "circle" query above, nParam would be set to 3 and the aParam[]
array would contain the three values 45.3, 22.9 and 5.0.

The pUser and xDelUser members of the sqlite3_rtree_geometry structure are
initially set to NULL. The pUser variable may be set by the callback
implementation to any arbitrary value that may be useful to subsequent
invocations of the callback within the same query (for example, a
pointer to a complicated data structure used to test for region intersection).
If the xDelUser variable is set to a non-NULL value, then after the
query has finished running SQLite automatically invokes it with the
value of the pUser variable as the only argument. In other words, xDelUser
may be set to a destructor function for the pUser value.

The xGeom callback always does a depth-first search of the r-tree.


c2: The SQLite R*Tree Module
c3: 6.2. The New xQueryFunc Callback
c5: rtree.html#the_new_xqueryfunc_callback
c4:
The newer xQueryFunc callback receives more information from the r-tree
query engine on each call, and it sends more information back to the query engine
before it returns.
To help keep the interface manageable, the xQueryFunc callback sends and receives
information from the query engine as fields in the
sqlite3_rtree_query_info structure:

struct sqlite3_rtree_query_info {
  void *pContext;                   /* pContext from when function registered */
  int nParam;                       /* Number of function parameters */
  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
  void *pUser;                      /* callback can use this, if desired */
  void (*xDelUser)(void*);          /* function to free pUser */
  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
  unsigned int *anQueue;            /* Number of pending entries in the queue */
  int nCoord;                       /* Number of coordinates */
  int iLevel;                       /* Level of current node or entry */
  int mxLevel;                      /* The largest iLevel value in the tree */
  sqlite3_int64 iRowid;             /* Rowid for current entry */
  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
  int eParentWithin;                /* Visibility of parent node */
  int eWithin;                      /* OUT: Visiblity */
  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
  /* The following fields are only available in 3.8.11 and later */
  sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
};


The first five fields of the sqlite3_rtree_query_info structure are identical
to the sqlite3_rtree_geometry structure, and have exactly the same meaning.
The sqlite3_rtree_query_info structure also contains nCoord and aCoord fields 
which have the same meaning as the parameter of the same name in the xGeom callback.

The xQueryFunc must set the eWithin field of sqlite3_rtree_query_info to
one of the values NOT_WITHIN, PARTLY_WITHIN, or FULLY_WITHIN depending on whether
or not the bounding box defined by aCoord[] is completely outside the region,
overlaps the region, or is completely inside the region, respectively.  In
addition, the xQueryFunc must set the rScore field to a non-negative value that
indicates the order in which subtrees and entries of the query should be analyzed
and returned.  Smaller scores are processed first.

As its name implies, an R*Tree is organized as a tree.  Each node of the
tree is a bounding box.  The root of the tree is a bounding box that encapsulates
all elements of the tree.  Beneath the root are a number of subtrees (typically
20 or more) each with their own smaller bounding boxes and each containing some
subset of the R*Tree entries.  The subtrees may have sub-subtrees, and so forth
until finally one reaches the leaves of the tree which are the actual R*Tree
entries.

An R*Tree query is initialized by making the root node the only entry
in a priority queue sorted by rScore.
The query proceeds by extracting the entry from the priority queue that has
the lowest score.  If that entry is a leaf (meaning that it is an actual
R*Tree entry and not a subtree) then that entry
is returned as one row of the query result.  
If the extracted priority queue entry is a node (a subtree),
then the next child of that node is passed to the xQueryFunc callback.
If the node has more children then it is returned to the priority queue.
Otherwise it is discarded. Those subelements for which the xQueryFunc
callback sets eWithin to PARTLY_WITHIN or FULLY_WITHIN are added to the
priority queue using the score supplied by the callback.  Subelements that
return NOT_WITHIN are discarded.  The query runs until the priority queue is
empty.

Every leaf entry and node (subtree) within the R*Tree has an integer "level".
The leaves have a level of 0.  The first containing subtree of the leaves has
a level of 1.  The root of the R*Tree has the largest level value.  The
mxLevel entry in the sqlite3_rtree_query_info structure is the level value for
the root of the R*Tree.  The iLevel entry in sqlite3_rtree_query_info gives the
level for the object being interrogated.

Most R*Tree queries use a depth-first search.  This is accomplished by setting
the rScore equal to iLevel.  A depth-first search is usually preferred since it
minimizes the number of elements in the priority queue, which reduces memory
requirements and speeds processing.  However, some application may prefer a
breadth-first search, which can be accomplished by setting rScore to mxLevel-iLevel.
By creating more complex formulas for rScore, applications can exercise
detailed control over the order in which subtree are searched and leaf
R*Tree entries are returned.  For example, in an application with many
millions of R*Tree entries, the rScore might be arranged so that the
largest or most significant entries are returned first, allowing the
application to display the most important information quickly, and
filling in smaller and less important details as they become available.

Other information fields of the sqlite3_rtree_query_info structure are
available for use by the xQueryFunc callback, if desired.  The iRowid field
is the rowid (the first of the 3 to 11 columns in the R*Tree) for the element
being considered.  iRowid is only valid for leaves.  The eParentWithin and
rParentScore values are copies of the eWithin and rScore values from the
containing subtree of the current row.  The anQueue field is an array
of mxLevel+1 unsigned integers that tell the current number of elements in
the priority queue at each level.


c2: The SQLite R*Tree Module
c3: 6.3. Additional Considerations for Custom Queries
c5: rtree.html#additional_considerations_for_custom_queries
c4:
The MATCH operator of a custom R*Tree query function must be a top-level
AND-connected term of the WHERE clause, or else it will not be usable
by the R*Tree query optimizer and the query will not be runnable.
If the MATCH operator is connected to other terms of the WHERE clause 
via an OR operator, for example, the query will fail with an error.


Two or more MATCH operators are allowed in the same WHERE clause, as long
as they are connected by AND operators.  However,
the R*Tree query engine only contains a single priority queue.  The priority
assigned to each node in the search is the lowest priority returned by any
of the MATCH operators.


c2: The SQLite R*Tree Module
c3: 7. Implementation Details
c5: rtree.html#implementation_details
c4:
The following sections describe some low-level details of the R*Tree implementation,
that might be useful for trouble-shooting or performance analysis.


c2: The SQLite R*Tree Module
c3: 7.1. Shadow Tables
c5: rtree.html#shadow_tables
c4:
The content of an R*Tree index is actually stored in three ordinary
SQLite tables with names derived from the name of the R*Tree.  These
three tables are called "shadow tables".  This is their schema:

CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data)
CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode)
CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno)


The "%" in the name of each shadow table is replaced by the name of the
R*Tree virtual table.  So, if the name of the R*Tree table is "xyz" then
the three shadow tables would be "xyz_node", "xyz_parent", and "xyz_rowid".

There is one entry in the %_node table for each R*Tree node.  An
R*Tree node consists of one or more entries that are proximate to one another.
The nodes of an R*Tree for a tree.  All nodes other than the root have an
entry in the %_parent shadow table that identifies the parent node.
Each entry in an R*Tree has a rowid.  The %_rowid shadow table maps entry
rowids to the node that contains that entry.

Extra columns appended to the %_rowid table hold the 
content of auxiliary columns.  The names of these extra
%_rowid columns are probably not the same as the
actual auxiliary column names.


c2: The SQLite R*Tree Module
c3: 7.2. Integrity Check using the rtreecheck() SQL function
c5: rtree.html#integrity_check_using_the_rtreecheck_sql_function
c4:
The scalar SQL function rtreecheck(R) or rtreecheck(S,R) runs an
integrity check on the rtree table named R contained within database S.
The function returns a human-language description of any problems found,
or the string 'ok' if everything is ok.  Running rtreecheck() on an R*Tree
virtual table is similar to running PRAGMA integrity_check on a
database.

Example: To verify that an R*Tree named "demo_index" is well-formed
and internally consistent, run:

SELECT rtreecheck('demo_index');


The rtreecheck() function performs the following checks:



For each cell in the r-tree structure (%_node table), that:

 for each dimension, (coord1 &lt;= coord2).
 unless the cell is on the root node, that the cell is bounded
        by the parent cell on the parent node.
 for leaf nodes, that there is an entry in the %_rowid 
        table corresponding to the cell's rowid value that 
        points to the correct node.
 for cells on non-leaf nodes, that there is an entry in the 
        %_parent table mapping from the cell's child node to the
        node that it resides on.


That there are the same number of entries in the %_rowid table
as there are leaf cells in the r-tree structure, and that there
is a leaf cell that corresponds to each entry in the %_rowid table.

That there are the same number of entries in the %_parent table
as there are non-leaf cells in the r-tree structure, and that 
there is a non-leaf cell that corresponds to each entry in the 
%_parent table.


c2: How To Corrupt An SQLite Database File
c3: Overview
c5: howtocorrupt.html#overview
c4:
An SQLite database is highly resistant to corruption.
If an application crash, or an operating-system crash, or even
a power failure occurs in the middle of a transaction, the partially
written transaction should be automatically rolled back the next time
the database file is accessed.  The recovery process is fully
automatic and does not require any action on the part of the user
or the application.


Though SQLite is resistant to database corruption, it is not immune.
This document describes the various ways that an SQLite database might
go corrupt.


c2: How To Corrupt An SQLite Database File
c3: 1. File overwrite by a rogue thread or process
c5: howtocorrupt.html#_file_overwrite_by_a_rogue_thread_or_process
c4:
SQLite database files are ordinary disk files.
That means that any process can open the file and 
overwrite it with garbage.  There is nothing that the SQLite
library can do to defend against this.


c2: How To Corrupt An SQLite Database File
c3: 1.1. Continuing to use a file descriptor after it has been closed
c5: howtocorrupt.html#_continuing_to_use_a_file_descriptor_after_it_has_been_closed
c4:
We have seen multiple cases where a file descriptor was open on a file,
then that file descriptor was closed and reopened on an SQLite database.
Later, some other thread continued to write into the
old file descriptor, not realizing that the original file had been closed
already.  But because the file descriptor had been reopened by SQLite,
the information that was intended to go into the original file ended up
overwriting parts of the SQLite database, leading to corruption of the
database.

One example of this occurred circa 2013-08-30 on the canonical repository
for the Fossil DVCS.  In that event,
file descriptor 2 (standard error) was being erroneously closed (by
stunnel, we suspect) prior to 
sqlite3_open_v2() so that the file descriptor used for the
repository database file was 2.  Later, an application 
bug caused an assert() statement to emit
an error message by invoking write(2,...).  But since file descriptor 2 was 
now connected to a database file, the error message
overwrote part of the database.  To guard against this kind of problem,
SQLite version 3.8.1 (2013-10-17)
and later refuse to use low-numbered file descriptors
for database files. 
(See SQLITE_MINIMUM_FILE_DESCRIPTOR for additional information.)

Another example of corruption caused by using a closed file
descriptor was 
reported by facebook engineers in a blog post on 2014-08-12.

Another example of this error was reported against
Fossil on 2019-07-11.  A file descriptor would
be opened for debugging output, but then closed and reopened by SQLite.
But the debugging logic continued to write into the original file
descriptor. See the
forum discussion
for the bug report and a link to the fix.


c2: How To Corrupt An SQLite Database File
c3: 1.2. Backup or restore while a transaction is active
c5: howtocorrupt.html#_backup_or_restore_while_a_transaction_is_active
c4:
Systems that run automatic backups in the background might try to
make a backup copy of an SQLite database file while it is in the middle
of a transaction.  The backup copy then might contain some old and some
new content, and thus be corrupt.

The best approach to make reliable backup copies of an SQLite database
is to make use of the backup API that is part of the SQLite library.
Failing that, it is safe to make a copy of an SQLite database file as long
as there are no transactions in progress by any process.  If the previous
transaction failed, then it is important that any rollback journal
(the *-journal file) or write-ahead log (the *-wal file)
be copied together with the database file itself.


c2: How To Corrupt An SQLite Database File
c3: 1.3. Deleting a hot journal
c5: howtocorrupt.html#_deleting_a_hot_journal
c4:
SQLite normally stores all content in a single disk file.  However,
while performing a transaction, information necessary to recover the
database following a crash or power failure is stored in auxiliary
journal files.  Such journal files are described as "hot".
The journal files have the same name as the
original database file with the addition
of -journal or -wal suffix.

SQLite must see the journal files in order to recover from a crash
or power failure.  If the hot journal files are moved, deleted, or renamed
after a crash or power failure, then automatic recovery will not work
and the database may go corrupt.

Another manifestation of this problem is
database corruption caused by inconsistent use of 8+3 filenames.


c2: How To Corrupt An SQLite Database File
c3: 1.4. Mispairing database files and hot journals
c5: howtocorrupt.html#_mispairing_database_files_and_hot_journals_
c4:
The previous example is a specific case of a more general problem:
The state of an SQLite database is controlled by both the
database file and the journal file.  In a quiescent state, the journal
file does not exist and only the database file matters.
But if the journal file does exist, it must be
kept together with the database to avoid corruption.  The following
actions are all likely to lead to corruption:

 Swapping journal files between two different databases.
 Overwritting a journal file with a different journal file.
 Moving a journal file from one database to another.
 Copying a database file without also copying its journal.
 Overwriting a database file with another without also
     deleting any hot journal associated with the original database.


c2: How To Corrupt An SQLite Database File
c3: 2. File locking problems
c5: howtocorrupt.html#_file_locking_problems
c4:
SQLite uses file locks on the database file, and on the 
write-ahead log or WAL file, to coordinate access between concurrent
processes.  Without coordination, two threads or processes might try
to make incompatible changes to a database file at the same time,
resulting in database corruption.


c2: How To Corrupt An SQLite Database File
c3: 2.1. Filesystems with broken or missing lock implementations
c5: howtocorrupt.html#_filesystems_with_broken_or_missing_lock_implementations
c4:
SQLite depends on the underlying filesystem to do locking as the
documentation says it will.  But some filesystems contain bugs in their
locking logic such that the locks do not always behave as advertised.
This is especially true of network filesystems and NFS in particular.
If SQLite is used on a filesystem where the locking primitives contain
bugs, and if two or more threads or processes try to access the same
database at the same time, then database corruption might result.


c2: How To Corrupt An SQLite Database File
c3: 2.2. Posix advisory locks canceled by a separate thread doing close()
c5: howtocorrupt.html#_posix_advisory_locks_canceled_by_a_separate_thread_doing_close_
c4:
The default locking mechanism used by SQLite on unix platforms is
POSIX advisory locking.  Unfortunately, POSIX advisory locking has design
quirks that make it prone to misuse and failure. In particular, any
thread in the same process with a file descriptor that is holding a POSIX
advisory lock can override that lock using a different file descriptor.
One particularly pernicious problem is that the close() system
call will cancel all POSIX advisory locks on the same file for all
threads and all file descriptors in the process.

So, for example, suppose a multi-thread process has
two or more threads with separate SQLite database connections to the
same database file.  Then a third thread comes along and wants to read
something out of that same database file on its own, without using the 
SQLite library.
The third thread does an open(), a read() and then
a close().
One would think this would be harmless.
But the close() system call caused the
locks held on the database by all the other threads to be dropped.  Those
other threads have no way of knowing that their locks have just been
trashed (POSIX does not provide any mechanism to determine this) and so
they keep on running under the assumption that their locks are still valid.
This can lead to two or more threads or processes trying to write to the
database at the same time, resulting in database corruption.

Note that it is perfectly safe for two or more threads to access the
same SQLite database file using the SQLite library.  The unix drivers for
SQLite know about the POSIX advisory locking quirks and work around them.
This problem only arises when a thread tries to bypass the SQLite library
and read the database file directly.


c2: How To Corrupt An SQLite Database File
c3: 2.2.1. Multiple copies of SQLite linked into the same application
c5: howtocorrupt.html#multiple_copies_of_sqlite_linked_into_the_same_application
c4:
As pointed out in the previous paragraph, SQLite takes steps to work
around the quirks of POSIX advisory locking.  Part of that work-around involves
keeping a global list (mutex protected) of open SQLite database files.
But, if multiple copies of SQLite are linked into the same application,
then there will be multiple instances of this global list.
Database connections opened using one copy of the SQLite library
will be unaware of database connections opened using the other copy,
and will be unable to work around the POSIX advisory locking quirks.
A close() operation on one connection might unknowingly 
clear the locks on a different database connection, leading to database
corruption.

The scenario above sounds far-fetched.
But the SQLite developers are aware of at 
least one commercial product that was released
with exactly this bug.  The vendor came to the SQLite developers seeking
help in tracking down some infrequent database corruption issues they were
seeing on Linux and Mac.  The problem was eventually traced to the
fact that the application was linking against two separate copies of SQLite.
The solution was to change the application build procedures to link against
just one copy of SQLite instead of two.


c2: How To Corrupt An SQLite Database File
c3: 2.3. Two processes using different locking protocols
c5: howtocorrupt.html#_two_processes_using_different_locking_protocols
c4:
The default locking mechanism used by SQLite on unix platforms is
POSIX advisory locking, but there are other options.  By selecting an
alternative sqlite3_vfs using the sqlite3_open_v2() interface, an
application can make use of other locking protocols that might be more
appropriate to certain filesystems.  For example, dot-file locking might
be select for use in an application that has to run on an NFS filesystem
that does not support POSIX advisory locking.

It is important that all connections to the same database file use 
the same locking protocol.
If one application is using POSIX advisory locks and another application
is using dot-file locking, then the two applications will not see each
other's locks and will not be able to coordinate database access, possibly
leading to database corruption.


c2: How To Corrupt An SQLite Database File
c3: 2.4. Unlinking or renaming a database file while in use
c5: howtocorrupt.html#_unlinking_or_renaming_a_database_file_while_in_use
c4:
If two processes have open connections to the same database file and
one process closes its connection, unlinks the file, then creates a new
database file in its place with the same name and reopens the new file,
then the two processes will be talking to different database files with 
the same name.  (Note that this is only possible on Posix and Posix-like
systems that permit a file to be unlinked while it is still open for
reading and writing.  Windows does not allow this to occur.)
Since rollback journals and WAL files are based on the name of the database
file, the two different database files will share the same rollback
journal or WAL file.  A rollback or recovery for one of the databases
might use content from the other database, resulting in corruption.
A similar problem occurs if a database file is renamed while it is
opened and a new file is created with the old name.

In other words, unlinking or renaming an open database file 
results in behavior that is undefined and probably undesirable.

Beginning with SQLite version 3.7.17 (2013-05-20),
the unix OS interface will
send SQLITE_WARNING messages to the error log if a database file is unlinked
while it is still in use.


c2: How To Corrupt An SQLite Database File
c3: 2.5. Multiple links to the same file
c5: howtocorrupt.html#_multiple_links_to_the_same_file
c4:
If a single database file has multiple links (either hard or soft links)
then that is just another way of saying that the file has multiple names.
If two or more processes open the database using different names, then
they will use different rollback journals and WAL files.  That means that
if one process crashes, the other process will be unable to recover the
transaction in progress because it will be looking in the wrong place
for the appropriate journal.

In other words, opening and using a database file that has two or
more names results in behavior that is undefined and probably undesirable.

Beginning with SQLite version 3.7.17 (2013-05-20),
the unix OS interface will
send SQLITE_WARNING messages to the error log if a database file has 
multiple hard links.

Beginning with SQLite version 3.10.0 (2016-01-06), 
the unix OS interface will
attempt to resolve symbolic links and open the database file by its
canonical name.  Prior to version 3.10.0, opening a database file 
through a symbolic link was similar to opening a database file
that had multiple hard links and resulted in undefined behavior.


c2: How To Corrupt An SQLite Database File
c3: 2.6. Carrying an open database connection across a fork()
c5: howtocorrupt.html#_carrying_an_open_database_connection_across_a_fork_
c4:
Do not open an SQLite database connection, then fork(), then try
to use that database connection in the child process.  All kinds of
locking problems will result and you can easily end up with a corrupt
database.  SQLite is not designed to support that kind of behavior.
Any database connection that is used in a child process must be opened
in the child process, not inherited from the parent.

 Do not even call sqlite3_close() on a database connection from a
child process if the connection was opened in the parent.  It is safe
to close the underlying file descriptor, but the sqlite3_close()
interface might invoke cleanup activities that will delete content out
from under the parent, leading to errors and perhaps even database
corruption.


c2: How To Corrupt An SQLite Database File
c3: 3. Failure to sync
c5: howtocorrupt.html#_failure_to_sync
c4:
In order to guarantee that database files are always consistent, SQLite
will occasionally ask the operating system to flush all pending writes to
persistent storage then wait for that flush to complete.  This is 
accomplished using the fsync() system call under unix and
FlushFileBuffers() under Windows.  We call this flush of
pending writes a "sync".

Actually, if one is only concerned with atomic and consistent writes and
is willing to forego durable writes, the sync operation does not need
to wait until the content is completely stored on persistent media.  Instead,
the sync operation can be thought of as an I/O barrier.  As long as all
writes that occur before the sync are completed before any write that happens
after the sync, no database corruption will occur.  If sync is operating as
an I/O barrier and not as a true sync, then a power failure or system crash
might cause one or more previously committed transactions to roll back
(in violation of the "durable" property of "ACID") but the database will at
least continue to be consistent, and that is what most people care about.


c2: How To Corrupt An SQLite Database File
c3: 3.1. Disk drives that do not honor sync requests
c5: howtocorrupt.html#_disk_drives_that_do_not_honor_sync_requests
c4:
Unfortunately, most consumer-grade mass storage devices lie about
syncing.  Disk drives will report that content is safely on persistent
media as soon as it reaches the track buffer and before actually being
written to oxide.  This makes the disk drives seem to operate faster
(which is vitally important to the manufacturer so that they can show
good benchmark numbers in trade magazines).  And in fairness, the lie
normally causes no harm, as long as there is no power loss or hard reset
prior to the track buffer actually being written to oxide.  But if a
power loss or hard reset does occur, and if that results in content that
was written after a sync reaching oxide while content written before
the sync is still in a track buffer, then database corruption can occur.

USB flash memory sticks seem to be especially pernicious liars 
regarding sync requests.  One can easily see this by committing a large
transaction to an SQLite database on a USB memory stick.  The COMMIT
command will return relatively quickly, indicating that the memory stick
has told the operating system and the operating system has told SQLite that
all content is safely in persistent storage, and yet the LED on the end
of the memory stick will continue flashing for several more seconds. 
Pulling out the memory stick while the LED is still flashing will frequently
result in database corruption.

Note that SQLite must believe whatever the operating system and hardware
tell it about the status of sync requests.  There is no way for SQLite to
detect that either is lying and that writes might be occurring out-of-order.
However, SQLite in WAL mode is far more forgiving of
out-of-order writes than in the default rollback journal modes.  In WAL
mode, the only time that a failed sync operation can cause database corruption
is during a checkpoint operation.  A sync failure during a COMMIT might
result in loss of durability but not in a corrupt database file.  Hence,
one line of defense against database corruption due to failed sync operations
is to use SQLite in WAL mode and to checkpoint as infrequently as possible.


c2: How To Corrupt An SQLite Database File
c3: 3.2. Disabling sync using PRAGMAs
c5: howtocorrupt.html#_disabling_sync_using_pragmas
c4:
The sync operations that SQLite performs to help ensure integrity
can be disabled at run-time using the synchronous pragma.  By setting
PRAGMA synchronous=OFF, all sync operations are omitted.  This makes
SQLite seem to run faster, but it also allows the operating system to freely
reorder writes, which could result in database corruption if a power failure
or hard reset occurs prior to all content reaching persistent storage.

For maximum reliability and for robustness against database corruption,
SQLite should always be run with its default synchronous setting of FULL.


c2: How To Corrupt An SQLite Database File
c3: 4. Disk Drive and Flash Memory Failures
c5: howtocorrupt.html#_disk_drive_and_flash_memory_failures
c4:
An SQLite database can become corrupt if the file content changes 
due to a disk drive or flash memory failure.  It is very rare, but disks 
will occasionally flip a bit in the middle of a sector.


c2: How To Corrupt An SQLite Database File
c3: 4.1. Non-powersafe flash memory controllers
c5: howtocorrupt.html#_non_powersafe_flash_memory_controllers
c4:
We are told that in some flash memory controllers the wear-leveling logic
can cause random filesystem damage if power is interrupted during a write.
This can manifest, for example, as random changes in the middle of a file
that was not even open at the time of the power loss.  So, for example,
a device would be writing content into an MP3 file in flash memory when a
power loss occurs, and that could result in an SQLite database being
corrupted even though the database was not even in use at the time of the
power loss.


c2: How To Corrupt An SQLite Database File
c3: 4.2. Fake capacity USB sticks
c5: howtocorrupt.html#_fake_capacity_usb_sticks
c4:
There are many fraudulent USB sticks in circulation that report to have
a high capacity (ex: 8GB) but are really only capable of storing a much
smaller amount (ex: 1GB).   Attempts to write on these devices will
often result in unrelated files being overwritten.  Any use of a fraudulent
flash memory device can easily lead to database corruption, therefore.
Internet searches such as "fake capacity usb" will turn up lots of
disturbing information about this problem.


c2: How To Corrupt An SQLite Database File
c3: 5. Memory corruption
c5: howtocorrupt.html#_memory_corruption
c4:
SQLite is a C-library that runs in the same address space as the 
application that it serves.  That means that stray pointers, buffer
overruns, heap corruption, or other malfunctions in the application can
corrupt internal SQLite data structure and ultimately result in a
corrupt database file.  Normally these kinds of problems manifest themselves
as segfaults prior to any database corruption occurring, but there have
been instances where application code errors have caused SQLite to
malfunction subtly so as to corrupt the database file rather than
panicking.

The memory corruption problem becomes more acute when
using memory-mapped I/O.
When all or part of the database file is mapped into the application's
address space, then a stray pointer that overwrites any part of that
mapped space will immediately corrupt the database file, without
requiring the application to do a subsequent write() system call.


c2: How To Corrupt An SQLite Database File
c3: 6. Other operating system problems
c5: howtocorrupt.html#_other_operating_system_problems
c4:
Sometimes operating systems will exhibit non-standard behavior which
can lead to problems.  Sometimes this non-standard behavior is deliberate,
and sometimes it is a mistake in the implementation.  But in any event,
if the operating performs differently from they way SQLite expects it to
perform, the possibility of database corruption exists.


c2: How To Corrupt An SQLite Database File
c3: 6.1. Linux Threads
c5: howtocorrupt.html#_linux_threads
c4:
Some older versions of Linux used the LinuxThreads library for thread
support.  LinuxThreads is similar to Pthreads, but is subtly different
with respect to handling of POSIX advisory locks.  SQLite versions
2.2.3 through 3.6.23 recognized that LinuxThreads were being used at
runtime and took appropriate action to work around the non-standard
behavior of LinuxThreads.  But most modern Linux implementations make
use of the newer, and correct, NPTL implementation of Pthreads.  Beginning
with SQLite version 3.7.0 (2010-07-21), the use of NPTL is assumed.
No checks are 
made.  Hence, recent versions of SQLite will subtly malfunction and may 
corrupt database files if used in multi-threaded application that run
on older linux systems that make use of LinuxThreads.


c2: How To Corrupt An SQLite Database File
c3: 6.2. Failures of mmap() on QNX
c5: howtocorrupt.html#_failures_of_mmap_on_qnx
c4:
There exists some subtle problem with mmap() on QNX such that making
a second mmap() call against a single file descriptor can cause
the memory obtained from the first mmap() call to be zeroed.  SQLite on
unix uses mmap() to create a shared memory region for transaction 
coordination in WAL mode, and it will call mmap() multiple times
for large transactions.  The QNX mmap() has been demonstrated to corrupt
database file under that scenario.  QNX engineers are aware of this problem
and are working on a solution; the problem may have already been fixed by
the time you read this.

When running on QNX, it is recommended that memory-mapped I/O never
be used.  Furthermore, to use WAL mode, it is recommended that applications
employ the exclusive locking mode in order to 
use WAL without shared memory.


c2: How To Corrupt An SQLite Database File
c3: 6.3. Filesystem Corruption
c5: howtocorrupt.html#_filesystem_corruption
c4:
Since SQLite databases are ordinary disk files, any malfunction in the
filesystem can corrupt the database.  Filesystems in modern operating systems
are very reliable, but errors do still occur.  For example, on 2013-10-01
the SQLite database that holds the
Wiki for Tcl/Tk went corrupt a few days
after the host computer was moved to a dodgy build of the (linux) kernel
that had issues in the filesystem layer.  In that event, the filesystem
eventually became so badly corrupted that the machine was unusable, but
the earliest symptom of trouble was the corrupted SQLite database.


c2: How To Corrupt An SQLite Database File
c3: 7. SQLite Configuration Errors
c5: howtocorrupt.html#sqlite_configuration_errors
c4:
SQLite has many built-in protections against database corruption.
But many of these protections can be disabled by configuration options.
If protections are disabled, database corruption may occur.

The following are examples of disabling the built-in protection
mechanisms of SQLite:


Setting PRAGMA synchronous=OFF can cause the database to
go corrupt if there is an operating-system crash or power failure,
though this setting is safe from damage due to application crashes.

Changing the PRAGMA schema_version while other database
connections are open.

Using PRAGMA journal_mode=OFF or PRAGMA journal_mode=MEMORY
and taking an application crash in the middle of a write transaction.

Setting PRAGMA writable_schema=ON and then changing the
database schema using DML statements can render the database completely
unreadable, if not done carefully.


c2: How To Corrupt An SQLite Database File
c3: 8. Bugs in SQLite
c5: howtocorrupt.html#_bugs_in_sqlite
c4:
SQLite is very carefully tested to help ensure that it is
as bug-free as possible.  Among the many tests that are carried out for
every SQLite version are tests that simulate power failures, I/O errors,
and out-of-memory (OOM) errors and verify that no database corruption occurs
during any of these events.  SQLite is also field-proven with approximately
two billion active deployments with no serious problems.

Nevertheless, no software is 100% perfect.  There have been a few
historical bugs in SQLite (now fixed) that could cause database corruption.
And there may be yet a few more that remain undiscovered.  Because of the
extensive testing and widespread use of SQLite, bugs that result in
database corruption tend to be very obscure.  The likelihood
of an application encountering an SQLite bug is small.  To illustrate this,
an account is given below 
of all database-corruption bugs found in SQLite during the
four-year period from 2009-04-01 to 2013-04-15.
This account should give the reader an intuitive sense of the
kinds of bugs in SQLite that manage to slip through testing procedures
and make it into a release.


c2: How To Corrupt An SQLite Database File
c3: 8.1. False corruption reports due to database shrinkage
c5: howtocorrupt.html#_false_corruption_reports_due_to_database_shrinkage
c4:
If a database is written by SQLite version 3.7.0 or later and then
written again by SQLite version 3.6.23 or earlier in such a way as to
make the size of the database file decrease, then the next time that
SQLite version 3.7.0 access the database file, it might report that the
database file is corrupt.  The database file is not really corrupt, however.
Version 3.7.0 was simply being overly zealous in its corruption detection.

The problem was fixed on 2011-02-20.  The fix first appears in
SQLite version 3.7.6 (2011-04-12).


c2: How To Corrupt An SQLite Database File
c3: 8.2. Corruption following switches between rollback and WAL modes
c5: howtocorrupt.html#_corruption_following_switches_between_rollback_and_wal_modes
c4:
Repeatedly switching an SQLite database in and out of WAL mode
and running the VACUUM command in between switches, in one process or
thread, can cause another process or thread that has the database file
open to miss the fact that the database has changed.  That second process
or thread might then try to modify the database using a stale cache and
cause database corruption.

This problem was discovered during internal testing and has never been
observed in the wild.  The problem was fixed on 2011-01-27 and in version
3.7.5.


c2: How To Corrupt An SQLite Database File
c3: 8.3. I/O error while obtaining a lock leads to corruption
c5: howtocorrupt.html#_i_o_error_while_obtaining_a_lock_leads_to_corruption
c4:
If the operating system returns an I/O error while attempting to obtain
a certain lock on shared memory in WAL mode then SQLite might fail 
to reset its cache,
which could lead to database corruption if subsequent writes are attempted.

Note that this problem only occurs if the attempt to acquire the lock
resulted in an I/O error.  If the lock is simply not granted (because some
other thread or process is already holding a conflicting lock) then no
corruption will ever occur.  We are not aware of any operating systems that
will fail with an I/O error while attempting to get a file lock on shared
memory.  So this is a theoretical problem rather than a real problem.
Needless to say, this problem has never been observed in the wild.  The
problem was discovered while doing stress testing of SQLite in a test
harness that simulates I/O errors.

This problem was fixed on 2010-09-20 for SQLite version 3.7.3.


c2: How To Corrupt An SQLite Database File
c3: 8.4. Database pages leak from the free page list
c5: howtocorrupt.html#_database_pages_leak_from_the_free_page_list
c4:
When content is deleted from an SQLite database, pages that are no
longer used are added to a free list and are reused to hold content
added by subsequent inserts.  A bug in SQLite that was present in
version 3.6.16 through 3.7.2 might cause pages to go missing out of
the free list when incremental_vacuum was used.  This would not cause
data loss.  But it would result in the database file being larger than
necessary.  And it would cause the integrity_check pragma to report
pages missing from the free list.

This problem was fixed on 2010-08-23 for SQLite version 3.7.2.


c2: How To Corrupt An SQLite Database File
c3: 8.5. Corruption following alternating writes from 3.6 and 3.7.
c5: howtocorrupt.html#_corruption_following_alternating_writes_from_3_6_and_3_7_
c4:
SQLite version 3.7.0 introduced a number of new enhancements to
the SQLite database file format (such as but not limited to WAL).
The 3.7.0 release was a shake-out release for these new features. 
We expected to find problems and were not disappointed.

If a database were originally created using SQLite version 3.7.0,
then written by SQLite version 3.6.23.1 such that the size of the database
file increased, then written again by SQLite version 3.7.0, the database
file could go corrupt.

This problem was fixed on 2010-08-04 for SQLite version 3.7.1.


c2: How To Corrupt An SQLite Database File
c3: 8.6. Race condition in recovery on windows system.
c5: howtocorrupt.html#_race_condition_in_recovery_on_windows_system_
c4:
SQLite version 3.7.16.2 fixes a subtle race condition in the locking
logic on Windows systems.  When a database file is in need
of recovery because the previous process writing to it crashed in the
middle of a transaction and two or more processes try to open the 
that database at the same time, then the race condition might cause
one of those processes to get a false indication that the recovery 
has already completed, allowing that process to continue using the
database file without running recovery first.  If that process writes
to the file, then the file might go corrupt.  This race condition
had apparently existed in all prior versions of SQLite for Windows going
back to 2004.  But the race was very tight.  Practically speaking, you
need a fast multi-core machine in which you launch two processes to run
recovery at the same moment on two separate cores.  This defect was
on Windows systems only and did not affect the posix OS interface.


c2: How To Corrupt An SQLite Database File
c3: 8.7. Boundary value error in the secondary journals used by nested transactions.
c5: howtocorrupt.html#_boundary_value_error_in_the_secondary_journals_used_by_nested_transactions_
c4:
When a nested transaction is started using SAVEPOINT, SQLite uses
a secondary rollback journal to track the changes for the nested
transaction, in case the inner transaction needs to be rolled back.  Secondary
journals are not involved in protecting the database from corruption due
to program crashes or power outages.  The secondary journals only come into
play when rolling back an inner transaction of a nested transaction.

These secondary journals can be held either in memory or as temporary
files on disk.  The default behavior is to store them on disk.  But that 
can be changed using the -DSQLITE_TEMP_STORE compile-time option,
or at run-time using the PRAGMA temp_store statement.  The bug
only arises when secondary journals are held in memory.

In SQLite version 3.35.0 (2021-03-12), a new optimization was
added so that when SQLite is holding secondary journals in memory,
less memory will be used. Unfortunately, an boundary check in
the new logic was coded incorrectly.
What should have been a "&lt;" operator was coded as "&lt;=".  This
error might cause the secondary journal to enter an inconsistent state
if it is ever rolled back.  If additional changes are made and the
outer transaction eventually commits, the database might be left in
an inconsistent state.

This problem was discovered by an 
independent researcher
who was attempting to find bugs in SQLite using a fuzzer.  The fuzzer found a
failure in an assert() statement that is used
to help verify the internal state of the secondary journal.  The bug was a
sufficiently obscure corner-case that it might have gone unnoticed for many
years, had it not been for the intensive use of assert() statements in SQLite,
the persistence and tenacity of the security researchers, and their
customized state-of-the-art fuzzer.

This problem was fixed
in version 3.37.2 (2022-01-06).


c2: Atomic Commit In SQLite
c3: 1. Introduction
c5: atomiccommit.html#_introduction
c4:
An important feature of transactional databases like SQLite
is "atomic commit".  
Atomic commit means that either all database changes within a single 
transaction occur or none of them occur.  With atomic commit, it
is as if many different writes to different sections of the database
file occur instantaneously and simultaneously.
Real hardware serializes writes to mass storage, and writing
a single sector takes a finite amount of time.
So it is impossible to truly write many different sectors of a 
database file simultaneously and/or instantaneously.
But the atomic commit logic within
SQLite makes it appear as if the changes for a transaction
are all written instantaneously and simultaneously.

SQLite has the important property that transactions appear
to be atomic even if the transaction is interrupted by an
operating system crash or power failure.

This article describes the techniques used by SQLite to create the
illusion of atomic commit.

The information in this article applies only when SQLite is operating
in "rollback mode", or in other words when SQLite is not 
using a write-ahead log.  SQLite still supports atomic commit when
write-ahead logging is enabled, but it accomplishes atomic commit by
a different mechanism from the one described in this article.  See
the write-ahead log documentation for additional information on how
SQLite supports atomic commit in that context.


c2: Atomic Commit In SQLite
c3: 2. Hardware Assumptions
c5: atomiccommit.html#_hardware_assumptions
c4:
Throughout this article, we will call the mass storage device "disk"
even though the mass storage device might really be flash memory.

We assume that disk is written in chunks which we call a "sector".
It is not possible to modify any part of the disk smaller than a sector.
To change a part of the disk smaller than a sector, you have to read in
the full sector that contains the part you want to change, make the
change, then write back out the complete sector.

On a traditional spinning disk, a sector is the minimum unit of transfer
in both directions, both reading and writing.  On flash memory, however,
the minimum size of a read is typically much smaller than a minimum write.
SQLite is only concerned with the minimum write amount and so for the
purposes of this article, when we say "sector" we mean the minimum amount
of data that can be written to mass storage in a single go.


  Prior to SQLite version 3.3.14, a sector size of 512 bytes was
  assumed in all cases.  There was a compile-time option to change
  this but the code had never been tested with a larger value.  The
  512 byte sector assumption seemed reasonable since until very recently
  all disk drives used a 512 byte sector internally.  However, there
  has recently been a push to increase the sector size of disks to
  4096 bytes.  Also the sector size
  for flash memory is usually larger than 512 bytes.  For these reasons,
  versions of SQLite beginning with 3.3.14 have a method in the OS
  interface layer that interrogates the underlying filesystem to find
  the true sector size.  As currently implemented (version 3.5.0) this
  method still returns a hard-coded value of 512 bytes, since there
  is no standard way of discovering the true sector size on either
  Unix or Windows.  But the method is available for embedded device
  manufacturers to tweak according to their own needs.  And we have
  left open the possibility of filling in a more meaningful implementation
  on Unix and Windows in the future.

SQLite has traditionally assumed that a sector write is not atomic.
However, SQLite does always assume that a sector write is linear.  By "linear"
we mean that SQLite assumes that when writing a sector, the hardware begins
at one end of the data and writes byte by byte until it gets to
the other end.  The write might go from beginning to end or from
end to beginning.  If a power failure occurs in the middle of a
sector write it might be that part of the sector was modified
and another part was left unchanged.  The key assumption by SQLite
is that if any part of the sector gets changed, then either the
first or the last bytes will be changed.  So the hardware will
never start writing a sector in the middle and work towards the
ends.  We do not know if this assumption is always true but it
seems reasonable.

The previous paragraph states that SQLite does not assume that
sector writes are atomic.  This is true by default.  But as of
SQLite version 3.5.0, there is a new interface called the
Virtual File System (VFS) interface.  The VFS is the only means
by which SQLite communicates to the underlying filesystem.  The
code comes with default VFS implementations for Unix and Windows
and there is a mechanism for creating new custom VFS implementations
at runtime.  In this new VFS interface there is a method called
xDeviceCharacteristics.  This method interrogates the underlying
filesystem to discover various properties and behaviors that the
filesystem may or may not exhibit.  The xDeviceCharacteristics
method might indicate that sector writes are atomic, and if it does
so indicate, SQLite will try to take advantage of that fact.  But
the default xDeviceCharacteristics method for both Unix and Windows
does not indicate atomic sector writes and so these optimizations
are normally omitted.

SQLite assumes that the operating system will buffer writes and
that a write request will return before data has actually been stored
in the mass storage device.
SQLite further assumes that write operations will be reordered by
the operating system.
For this reason, SQLite does a "flush" or "fsync" operation at key
points.  SQLite assumes that the flush or fsync will not return until
all pending write operations for the file that is being flushed have
completed.  We are told that the flush and fsync primitives
are broken on some versions of Windows and Linux.  This is unfortunate.
It opens SQLite up to the possibility of database corruption following
a power loss in the middle of a commit.  However, there is nothing 
that SQLite can do to test for or remedy the situation.  SQLite
assumes that the operating system that it is running on works as
advertised.  If that is not quite the case, well then hopefully you
will not lose power too often.

SQLite assumes that when a file grows in length that the new
file space originally contains garbage and then later is filled in
with the data actually written.  In other words, SQLite assumes that
the file size is updated before the file content.  This is a 
pessimistic assumption and SQLite has to do some extra work to make
sure that it does not cause database corruption if power is lost
between the time when the file size is increased and when the
new content is written.  The xDeviceCharacteristics method of
the VFS might indicate that the filesystem will always write the
data before updating the file size.  (This is the 
SQLITE_IOCAP_SAFE_APPEND property for those readers who are looking
at the code.)  When the xDeviceCharacteristics method indicates
that files content is written before the file size is increased,
SQLite can forego some of its pedantic database protection steps
and thereby decrease the amount of disk I/O needed to perform a
commit.  The current implementation, however, makes no such assumptions
for the default VFSes for Windows and Unix.

SQLite assumes that a file deletion is atomic from the
point of view of a user process.  By this we mean that if SQLite
requests that a file be deleted and the power is lost during the
delete operation, once power is restored either the file will
exist completely with all if its original content unaltered, or
else the file will not be seen in the filesystem at all.  If
after power is restored the file is only partially deleted,
if some of its data has been altered or erased,
or the file has been truncated but not completely removed, then
database corruption will likely result.

SQLite assumes that the detection and/or correction of 
bit errors caused by cosmic rays, thermal noise, quantum
fluctuations, device driver bugs, or other mechanisms, is the 
responsibility of the underlying hardware and operating system.  
SQLite does not add any redundancy to the database file for
the purpose of detecting corruption or I/O errors.
SQLite assumes that the data it reads is exactly the same data 
that it previously wrote.

By default, SQLite assumes that an operating system call to write
a range of bytes will not damage or alter any bytes outside of that range
even if a power loss or OS crash occurs during that write.  We
call this the "powersafe overwrite" property.  
Prior to version 3.7.9 (2011-11-01),
SQLite did not assume powersafe overwrite.  But with the standard
sector size increasing from 512 to 4096 bytes on most disk drives, it
has become necessary to assume powersafe overwrite in order to maintain
historical performance levels and so powersafe overwrite is assumed by
default in recent versions of SQLite.  The assumption of powersafe 
overwrite property can be disabled at compile-time or a run-time if
desired.  See the powersafe overwrite documentation for further
details.


c2: Atomic Commit In SQLite
c3: 3. Single File Commit
c5: atomiccommit.html#_single_file_commit
c4:
We begin with an overview of the steps SQLite takes in order to
perform an atomic commit of a transaction against a single database
file.  The details of file formats used to guard against damage from
power failures and techniques for performing an atomic commit across
multiple databases are discussed in later sections.


c2: Atomic Commit In SQLite
c3: 3.1. Initial State
c5: atomiccommit.html#_initial_state
c4:
The state of the computer when a database connection is
first opened is shown conceptually by the diagram at the
right.
The area of the diagram on the extreme right (labeled "Disk") represents
information stored on the mass storage device.  Each rectangle is
a sector.  The blue color represents that the sectors contain
original data.
The middle area is the operating systems disk cache.  At the
onset of our example, the cache is cold and this is represented
by leaving the rectangles of the disk cache empty.
The left area of the diagram shows the content of memory for
the process that is using SQLite.  The database connection has
just been opened and no information has been read yet, so the
user space is empty.


c2: Atomic Commit In SQLite
c3: 3.2. Acquiring A Read Lock
c5: atomiccommit.html#_acquiring_a_read_lock
c4:
Before SQLite can write to a database, it must first read
the database to see what is there already.  Even if it is just
appending new data, SQLite still has to read in the database
schema from the "sqlite_schema" table so that it can know
how to parse the INSERT statements and discover where in the
database file the new information should be stored.

The first step toward reading from the database file
is obtaining a shared lock on the database file.  A "shared"
lock allows two or more database connections to read from the
database file at the same time.  But a shared lock prevents
another database connection from writing to the database file
while we are reading it.  This is necessary because if another
database connection were writing to the database file at the
same time we are reading from the database file, we might read
some data before the change and other data after the change.
This would make it appear as if the change made by the other
process is not atomic.

Notice that the shared lock is on the operating system
disk cache, not on the disk itself.  File locks
really are just flags within the operating system kernel,
usually.  (The details depend on the specific OS layer
interface.)  Hence, the lock will instantly vanish if the
operating system crashes or if there is a power loss.  It
is usually also the case that the lock will vanish if the
process that created the lock exits.


c2: Atomic Commit In SQLite
c3: 3.3. Reading Information Out Of The Database
c5: atomiccommit.html#_reading_information_out_of_the_database
c4:
After the shared lock is acquired, we can begin reading
information from the database file.  In this scenario, we
are assuming a cold cache, so information must first be
read from mass storage into the operating system cache then
transferred from operating system cache into user space.
On subsequent reads, some or all of the information might
already be found in the operating system cache and so only
the transfer to user space would be required.

Usually only a subset of the pages in the database file
are read.  In this example we are showing three
pages out of eight being read.  In a typical application, a
database will have thousands of pages and a query will normally
only touch a small percentage of those pages.


c2: Atomic Commit In SQLite
c3: 3.4. Obtaining A Reserved Lock
c5: atomiccommit.html#_obtaining_a_reserved_lock
c4:
Before making changes to the database, SQLite first
obtains a "reserved" lock on the database file.  A reserved
lock is similar to a shared lock in that both a reserved lock
and shared lock allow other processes to read from the database
file.  A single reserve lock can coexist with multiple shared
locks from other processes.  However, there can only be a
single reserved lock on the database file.  Hence only a
single process can be attempting to write to the database
at one time.

The idea behind a reserved lock is that it signals that
a process intends to modify the database file in the near
future but has not yet started to make the modifications.
And because the modifications have not yet started, other
processes can continue to read from the database.  However,
no other process should also begin trying to write to the
database.


c2: Atomic Commit In SQLite
c3: 3.5. Creating A Rollback Journal File
c5: atomiccommit.html#_creating_a_rollback_journal_file
c4:
Prior to making any changes to the database file, SQLite first
creates a separate rollback journal file and writes into the 
rollback journal the original
content of the database pages that are to be altered.
The idea behind the rollback journal is that it contains
all information needed to restore the database back to 
its original state.

The rollback journal contains a small header (shown in green
in the diagram) that records the original size of the database
file.  So if a change causes the database file to grow, we
will still know the original size of the database.  The page
number is stored together with each database page that is 
written into the rollback journal.


  When a new file is created, most desktop operating systems
  (Windows, Linux, Mac OS X) will not actually write anything to
  disk.  The new file is created in the operating systems disk
  cache only.  The file is not created on mass storage until sometime
  later, when the operating system has a spare moment.  This creates
  the impression to users that I/O is happening much faster than
  is possible when doing real disk I/O.  We illustrate this idea in
  the diagram to the right by showing that the new rollback journal
  appears in the operating system disk cache only and not on the
  disk itself.


c2: Atomic Commit In SQLite
c3: 3.6. Changing Database Pages In User Space
c5: atomiccommit.html#_changing_database_pages_in_user_space
c4:
After the original page content has been saved in the rollback
journal, the pages can be modified in user memory.  Each database
connection has its own private copy of user space, so the changes
that are made in user space are only visible to the database connection
that is making the changes.  Other database connections still see
the information in operating system disk cache buffers which have
not yet been changed.  And so even though one process is busy
modifying the database, other processes can continue to read their
own copies of the original database content.


c2: Atomic Commit In SQLite
c3: 3.7. Flushing The Rollback Journal File To Mass Storage
c5: atomiccommit.html#_flushing_the_rollback_journal_file_to_mass_storage
c4:
The next step is to flush the content of the rollback journal
file to nonvolatile storage.
As we will see later, 
this is a critical step in insuring that the database can survive
an unexpected power loss.
This step also takes a lot of time, since writing to nonvolatile
storage is normally a slow operation.

This step is usually more complicated than simply flushing
the rollback journal to the disk.  On most platforms two separate
flush (or fsync()) operations are required.  The first flush writes
out the base rollback journal content.  Then the header of the
rollback journal is modified to show the number of pages in the 
rollback journal.  Then the header is flushed to disk.  The details
on why we do this header modification and extra flush are provided
in a later section of this paper.


c2: Atomic Commit In SQLite
c3: 3.8. Obtaining An Exclusive Lock
c5: atomiccommit.html#_obtaining_an_exclusive_lock
c4:
Prior to making changes to the database file itself, we must
obtain an exclusive lock on the database file.  Obtaining an
exclusive lock is really a two-step process.  First SQLite obtains
a "pending" lock.  Then it escalates the pending lock to an
exclusive lock.

A pending lock allows other processes that already have a
shared lock to continue reading the database file.  But it
prevents new shared locks from being established.  The idea
behind a pending lock is to prevent writer starvation caused
by a large pool of readers.  There might be dozens, even hundreds,
of other processes trying to read the database file.  Each process
acquires a shared lock before it starts reading, reads what it
needs, then releases the shared lock.  If, however, there are
many different processes all reading from the same database, it
might happen that a new process always acquires its shared lock before
the previous process releases its shared lock.  And so there is
never an instant when there are no shared locks on the database
file and hence there is never an opportunity for the writer to
seize the exclusive lock.  A pending lock is designed to prevent
that cycle by allowing existing shared locks to proceed but
blocking new shared locks from being established.  Eventually
all shared locks will clear and the pending lock will then be
able to escalate into an exclusive lock.


c2: Atomic Commit In SQLite
c3: 3.9. Writing Changes To The Database File
c5: atomiccommit.html#_writing_changes_to_the_database_file
c4:
Once an exclusive lock is held, we know that no other
processes are reading from the database file and it is
safe to write changes into the database file.  Usually
those changes only go as far as the operating systems disk
cache and do not make it all the way to mass storage.


c2: Atomic Commit In SQLite
c3: 3.10. 0 Flushing Changes To Mass Storage
c5: atomiccommit.html#0_flushing_changes_to_mass_storage
c4:
Another flush must occur to make sure that all the
database changes are written into nonvolatile storage.
This is a critical step to ensure that the database will
survive a power loss without damage.  However, because
of the inherent slowness of writing to disk or flash memory, 
this step together with the rollback journal file flush in section
3.7 above takes up most of the time required to complete a
transaction commit in SQLite.


c2: Atomic Commit In SQLite
c3: 3.11. 1 Deleting The Rollback Journal
c5: atomiccommit.html#1_deleting_the_rollback_journal
c4:
After the database changes are all safely on the mass
storage device, the rollback journal file is deleted.
This is the instant where the transaction commits.
If a power failure or system crash occurs prior to this
point, then recovery processes to be described later make
it appear as if no changes were ever made to the database
file.  If a power failure or system crash occurs after
the rollback journal is deleted, then it appears as if
all changes have been written to disk.  Thus, SQLite gives
the appearance of having made no changes to the database
file or having made the complete set of changes to the
database file depending on whether or not the rollback
journal file exists.

Deleting a file is not really an atomic operation, but
it appears to be from the point of view of a user process.
A process is always able to ask the operating system "does
this file exist?" and the process will get back a yes or no
answer.  After a power failure that occurs during a 
transaction commit, SQLite will ask the operating system
whether or not the rollback journal file exists.  If the
answer is "yes" then the transaction is incomplete and is
rolled back.  If the answer is "no" then it means the transaction
did commit.

The existence of a transaction depends on whether or
not the rollback journal file exists and the deletion
of a file appears to be an atomic operation from the point of
view of a user-space process.  Therefore, 
a transaction appears to be an atomic operation.

The act of deleting a file is expensive on many systems.
As an optimization, SQLite can be configured to truncate
the journal file to zero bytes in length
or overwrite the journal file header with zeros.  In either
case, the resulting journal file is no longer capable of rolling
back and so the transaction still commits.  Truncating a file
to zero length, like deleting a file, is assumed to be an atomic
operation from the point of view of a user process.  Overwriting
the header of the journal with zeros is not atomic, but if any
part of the header is malformed the journal will not roll back.
Hence, one can say that the commit occurs as soon as the header
is sufficiently changed to make it invalid.  Typically this happens
as soon as the first byte of the header is zeroed.


c2: Atomic Commit In SQLite
c3: 3.12. 2 Releasing The Lock
c5: atomiccommit.html#2_releasing_the_lock
c4:
The last step in the commit process is to release the
exclusive lock so that other processes can once again
start accessing the database file.

In the diagram at the right, we show that the information
that was held in user space is cleared when the lock is released.
This used to be literally true for older versions of SQLite.  But
more recent versions of SQLite keep the user space information
in memory in case it might be needed again at the start of the
next transaction.  It is cheaper to reuse information that is
already in local memory than to transfer the information back
from the operating system disk cache or to read it off of the
disk drive again.  Prior to reusing the information in user space,
we must first reacquire the shared lock and then we have to check
to make sure that no other process modified the database file while
we were not holding a lock.  There is a counter in the first page
of the database that is incremented every time the database file
is modified.  We can find out if another process has modified the
database by checking that counter.  If the database was modified,
then the user space cache must be cleared and reread.  But it is
commonly the case that no changes have been made and the user
space cache can be reused for a significant performance savings.


c2: Atomic Commit In SQLite
c3: 4. Rollback
c5: atomiccommit.html#_rollback
c4:
An atomic commit is supposed to happen instantaneously.  But the processing
described above clearly takes a finite amount of time.
Suppose the power to the computer were cut
part way through the commit operation described above.  In order
to maintain the illusion that the changes were instantaneous, we
have to "rollback" any partial changes and restore the database to
the state it was in prior to the beginning of the transaction.


c2: Atomic Commit In SQLite
c3: 4.1. When Something Goes Wrong...
c5: atomiccommit.html#_when_something_goes_wrong_
c4:
Suppose the power loss occurred
during step 3.10 above,
while the database changes were being written to disk.
After power is restored, the situation might be something
like what is shown to the right.  We were trying to change
three pages of the database file but only one page was
successfully written.  Another page was partially written
and a third page was not written at all.

The rollback journal is complete and intact on disk when
the power is restored.  This is a key point.  The reason for
the flush operation in step 3.7
is to make absolutely sure that
all of the rollback journal is safely on nonvolatile storage
prior to making any changes to the database file itself.


c2: Atomic Commit In SQLite
c3: 4.2. Hot Rollback Journals
c5: atomiccommit.html#_hot_rollback_journals
c4:
The first time that any SQLite process attempts to access
the database file, it obtains a shared lock as described in
section 3.2 above.
But then it notices that there is a 
rollback journal file present.  SQLite then checks to see if
the rollback journal is a "hot journal".   A hot journal is
a rollback journal that needs to be played back in order to
restore the database to a sane state.  A hot journal only
exists when an earlier process was in the middle of committing
a transaction when it crashed or lost power.

A rollback journal is a "hot" journal if all of the following
are true:


The rollback journal exists.
The rollback journal is not an empty file.
There is no reserved lock on the main database file.
The header of the rollback journal is well-formed and in particular
    has not been zeroed out.
The rollback journal does not
contain the name of a super-journal file (see
section 5.5 below) or if does
contain the name of a super-journal, then that super-journal
file exists.


The presence of a hot journal is our indication
that a previous process was trying to commit a transaction but
it aborted for some reason prior to the completion of the
commit.  A hot journal means that
the database file is in an inconsistent state and needs to
be repaired (by rollback) prior to being used.


c2: Atomic Commit In SQLite
c3: 4.3. Obtaining An Exclusive Lock On The Database
c5: atomiccommit.html#_obtaining_an_exclusive_lock_on_the_database
c4:
The first step toward dealing with a hot journal is to
obtain an exclusive lock on the database file.  This prevents two
or more processes from trying to rollback the same hot journal
at the same time.


c2: Atomic Commit In SQLite
c3: 4.4. Rolling Back Incomplete Changes
c5: atomiccommit.html#_rolling_back_incomplete_changes
c4:
Once a process obtains an exclusive lock, it is permitted
to write to the database file.  It then proceeds to read the
original content of pages out of the rollback journal and write
that content back to where it came from in the database file.
Recall that the header of the rollback journal records the original
size of the database file prior to the start of the aborted
transaction.  SQLite uses this information to truncate the
database file back to its original size in cases where the
incomplete transaction caused the database to grow.  At the
end of this step, the database should be the same size and
contain the same information as it did before the start of
the aborted transaction.


c2: Atomic Commit In SQLite
c3: 4.5. Deleting The Hot Journal
c5: atomiccommit.html#_deleting_the_hot_journal
c4:
After all information in the rollback journal has been
played back into the database file (and flushed to disk in case
we encounter yet another power failure), the hot rollback journal
can be deleted.

As in section 3.11, the journal
file might be truncated to zero length or its header might
be overwritten with zeros as an optimization on systems where
deleting a file is expensive.  Either way, the journal is no 
longer hot after this step.


c2: Atomic Commit In SQLite
c3: 4.6. Continue As If The Uncompleted Writes Had Never Happened
c5: atomiccommit.html#_continue_as_if_the_uncompleted_writes_had_never_happened
c4:
The final recovery step is to reduce the exclusive lock back
to a shared lock.  Once this happens, the database is back in the
state that it would have been if the aborted transaction had never
started.  Since all of this recovery activity happens completely
automatically and transparently, it appears to the program using
SQLite as if the aborted transaction had never begun.


c2: Atomic Commit In SQLite
c3: 5. Multi-file Commit
c5: atomiccommit.html#_multi_file_commit
c4:
SQLite allows a single 
database connection to talk to
two or more database files simultaneously through the use of
the ATTACH DATABASE command.
When multiple database files are modified within a single
transaction, all files are updated atomically.  
In other words, either all of the database files are updated or
else none of them are.
Achieving an atomic commit across multiple database files is
more complex that doing so for a single file.  This section
describes how SQLite works that bit of magic.


c2: Atomic Commit In SQLite
c3: 5.1. Separate Rollback Journals For Each Database
c5: atomiccommit.html#_separate_rollback_journals_for_each_database
c4:
When multiple database files are involved in a transaction,
each database has its own rollback journal and each database
is locked separately.  The diagram at the right shows a scenario
where three different database files have been modified within
one transaction.  The situation at this step is analogous to 
the single-file transaction scenario at 
step 3.6.  Each database file has
a reserved lock.  For each database, the original content of pages 
that are being changed have been written into the rollback journal
for that database, but the content of the journals have not yet
been flushed to disk.  No changes have been made to the database
file itself yet, though presumably there are changes being held
in user memory.

For brevity, the diagrams in this section are simplified from
those that came before.  Blue color still signifies original content
and pink still signifies new content.  But the individual pages
in the rollback journal and the database file are not shown and
we are not making the distinction between information in the
operating system cache and information that is on disk.  All of
these factors still apply in a multi-file commit scenario.  They
just take up a lot of space in the diagrams and they do not add
any new information, so they are omitted here.


c2: Atomic Commit In SQLite
c3: 5.2. The Super-Journal File
c5: atomiccommit.html#_the_super_journal_file
c4:
The next step in a multi-file commit is the creation of a
"super-journal" file.  The name of the super-journal file is
the same name as the original database filename (the database
that was opened using the 
sqlite3_open() interface,
not one of the ATTACHed auxiliary
databases) with the text "-mjHHHHHHHH" appended where
HHHHHHHH is a random 32-bit hexadecimal number.  The
random HHHHHHHH suffix changes for every new super-journal.

(Nota bene: The formula for computing the super-journal filename
given in the previous paragraph corresponds to the implementation as
of SQLite version 3.5.0.  But this formula is not part of the SQLite
specification and is subject to change in future releases.)

Unlike the rollback journals, the super-journal does not contain
any original database page content.  Instead, the super-journal contains
the full pathnames for rollback journals for every database that is
participating in the transaction.

After the super-journal is constructed, its content is flushed
to disk before any further actions are taken.  On Unix, the directory
that contains the super-journal is also synced in order to make sure
the super-journal file will appear in the directory following a
power failure.

The purpose of the super-journal is to ensure that multi-file
transactions are atomic across a power-loss.  But if the database files
have other settings that compromise integrity across a power-loss event
(such as PRAGMA synchronous=OFF or PRAGMA journal_mode=MEMORY) then
the creation of the super-journal is omitted, as an optimization.


c2: Atomic Commit In SQLite
c3: 5.3. Updating Rollback Journal Headers
c5: atomiccommit.html#_updating_rollback_journal_headers
c4:
The next step is to record the full pathname of the super-journal file
in the header of every rollback journal.  Space to hold the 
super-journal filename was reserved at the beginning of each rollback journal
as the rollback journals were created.

The content of each rollback journal is flushed to disk both before
and after the super-journal filename is written into the rollback
journal header.  It is important to do both of these flushes.  Fortunately,
the second flush is usually inexpensive since typically only a single
page of the journal file (the first page) has changed.

This step is analogous to 
step 3.7 in the single-file commit
scenario described above.


c2: Atomic Commit In SQLite
c3: 5.4. Updating The Database Files
c5: atomiccommit.html#_updating_the_database_files
c4:
Once all rollback journal files have been flushed to disk, it
is safe to begin updating database files.  We have to obtain an
exclusive lock on all database files before writing the changes.
After all the changes are written, it is important to flush the
changes to disk so that they will be preserved in the event of
a power failure or operating system crash.

This step corresponds to steps
3.8,
3.9, and
3.10 in the single-file commit
scenario described previously.


c2: Atomic Commit In SQLite
c3: 5.5. Delete The Super-Journal File
c5: atomiccommit.html#_delete_the_super_journal_file
c4:
The next step is to delete the super-journal file.
This is the point where the multi-file transaction commits.
This step corresponds to 
step 3.11 in the single-file
commit scenario where the rollback journal is deleted.

If a power failure or operating system crash occurs at this
point, the transaction will not rollback when the system reboots
even though there are rollback journals present.  The
difference is the super-journal pathname in the header of the
rollback journal.  Upon restart, SQLite only considers a journal
to be hot and will only playback the journal if there is no
super-journal filename in the header (which is the case for
a single-file commit) or if the super-journal file still
exists on disk.


c2: Atomic Commit In SQLite
c3: 5.6. Clean Up The Rollback Journals
c5: atomiccommit.html#_clean_up_the_rollback_journals
c4:
The final step in a multi-file commit is to delete the
individual rollback journals and drop the exclusive locks on
the database files so that other processes can see the changes.
This corresponds to 
step 3.12 in the single-file
commit sequence.

The transaction has already committed at this point so timing
is not critical in the deletion of the rollback journals.
The current implementation deletes a single rollback journal
then unlocks the corresponding database file before proceeding
to the next rollback journal.  But in the future we might change
this so that all rollback journals are deleted before any database
files are unlocked.  As long as the rollback journal is deleted before
its corresponding database file is unlocked it does not matter in what
order the rollback journals are deleted or the database files are
unlocked.


c2: Atomic Commit In SQLite
c3: 6. Additional Details Of The Commit Process
c5: atomiccommit.html#_additional_details_of_the_commit_process
c4:
Section 3.0 above provides an overview of
how atomic commit works in SQLite.  But it glosses over a number of
important details.  The following subsections will attempt to fill
in the gaps.


c2: Atomic Commit In SQLite
c3: 6.1. Always Journal Complete Sectors
c5: atomiccommit.html#_always_journal_complete_sectors
c4:
When the original content of a database page is written into
the rollback journal (as shown in section 3.5),
SQLite always writes a complete sector of data, even if the
page size of the database is smaller than the sector size.  
Historically, the sector size in SQLite has been hard coded to 512
bytes and since the minimum page size is also 512 bytes, this has never
been an issue.  But beginning with SQLite version 3.3.14, it is possible
for SQLite to use mass storage devices with a sector size larger than 512
bytes.  So, beginning with version 3.3.14, whenever any page within a
sector is written into the journal file, all pages in that same sector
are stored with it.

It is important to store all pages of a sector in the rollback
journal in order to prevent database corruption following a power
loss while writing the sector.  Suppose that pages 1, 2, 3, and 4 are
all stored in sector 1 and that page 2 is modified.  In order to write
the changes to page 2, the underlying hardware must also rewrite the
content of pages 1, 3, and 4 since the hardware must write the complete
sector.  If this write operation is interrupted by a power outage,
one or more of the pages 1, 3, or 4 might be left with incorrect data.
Hence, to avoid lasting corruption to the database, the original content
of all of those pages must be contained in the rollback journal.


c2: Atomic Commit In SQLite
c3: 6.2. Dealing With Garbage Written Into Journal Files
c5: atomiccommit.html#_dealing_with_garbage_written_into_journal_files
c4:
When data is appended to the end of the rollback journal,
SQLite normally makes the pessimistic assumption that the file
is first extended with invalid "garbage" data and that afterwards
the correct data replaces the garbage.  In other words, SQLite assumes
that the file size is increased first and then afterwards the content
is written into the file.  If a power failure occurs after the file
size has been increased but before the file content has been written,
the rollback journal can be left containing garbage data.  If after
power is restored, another SQLite process sees the rollback journal
containing the garbage data and tries to roll it back into the original
database file, it might copy some of the garbage into the database file
and thus corrupt the database file.

SQLite uses two defenses against this problem.  In the first place,
SQLite records the number of pages in the rollback journal in the header
of the rollback journal.  This number is initially zero.  So during an
attempt to rollback an incomplete (and possibly corrupt) rollback
journal, the process doing the rollback will see that the journal
contains zero pages and will thus make no changes to the database.  Prior
to a commit, the rollback journal is flushed to disk to ensure that
all content has been synced to disk and there is no "garbage" left
in the file, and only then is the page count in the header changed from
zero to true number of pages in the rollback journal.  The rollback journal
header is always kept in a separate sector from any page data so that
it can be overwritten and flushed without risking damage to a data
page if a power outage occurs.  Notice that the rollback journal
is flushed to disk twice: once to write the page content and a second
time to write the page count in the header.

The previous paragraph describes what happens when the
synchronous pragma setting is "full".


PRAGMA synchronous=FULL;


The default synchronous setting is full so the above is what usually
happens.  However, if the synchronous setting is lowered to "normal",
SQLite only flushes the rollback journal once, after the page count has
been written.
This carries a risk of corruption because it might happen that the 
modified (non-zero) page count reaches the disk surface before all
of the data does.  The data will have been written first, but SQLite
assumes that the underlying filesystem can reorder write requests and
that the page count can be burned into oxide first even though its
write request occurred last.  So as a second line of defense, SQLite
also uses a 32-bit checksum on every page of data in the rollback
journal.  This checksum is evaluated for each page during rollback
while rolling back a journal as described in 
section 4.4.  If an incorrect checksum
is seen, the rollback is abandoned.  Note that the checksum does
not guarantee that the page data is correct since there is a small
but finite probability that the checksum might be right even if the data is
corrupt.  But the checksum does at least make such an error unlikely.


Note that the checksums in the rollback journal are not necessary
if the synchronous setting is FULL.  We only depend on the checksums
when synchronous is lowered to NORMAL.  Nevertheless, the checksums
never hurt and so they are included in the rollback journal regardless
of the synchronous setting.


c2: Atomic Commit In SQLite
c3: 6.3. Cache Spill Prior To Commit
c5: atomiccommit.html#_cache_spill_prior_to_commit
c4:
The commit process shown in section 3.0
assumes that all database changes fit in memory until it is time to
commit.  This is the common case.  But sometimes a larger change will
overflow the user-space cache prior to transaction commit.  In those
cases, the cache must spill to the database before the transaction
is complete.

At the beginning of a cache spill, the status of the database
connection is as shown in step 3.6.
Original page content has been saved in the rollback journal and
modifications of the pages exist in user memory.  To spill the cache,
SQLite executes steps 3.7 through
3.9.  In other words, the rollback journal
is flushed to disk, an exclusive lock is acquired, and changes are
written into the database.  But the remaining steps are deferred
until the transaction really commits.  A new journal header is
appended to the end of the rollback journal (in its own sector)
and the exclusive database lock is retained, but otherwise processing
returns to step 3.6.  When the transaction
commits, or if another cache spill occurs, steps
3.7 and 3.9 are
repeated.  (Step 3.8 is omitted on second
and subsequent passes since an exclusive database lock is already held
due to the first pass.)

A cache spill causes the lock on the database file to
escalate from reserved to exclusive.  This reduces concurrency.
A cache spill also causes extra disk flush or fsync operations to
occur and these operations are slow, hence a cache spill can
seriously reduce performance.
For these reasons a cache spill is avoided whenever possible.


c2: Atomic Commit In SQLite
c3: 7. Optimizations
c5: atomiccommit.html#_optimizations
c4:
Profiling indicates that for most systems and in most circumstances
SQLite spends most of its time doing disk I/O.  It follows then that
anything we can do to reduce the amount of disk I/O will likely have a
large positive impact on the performance of SQLite.  This section
describes some of the techniques used by SQLite to try to reduce the
amount of disk I/O to a minimum while still preserving atomic commit.


c2: Atomic Commit In SQLite
c3: 7.1. Cache Retained Between Transactions
c5: atomiccommit.html#_cache_retained_between_transactions
c4:
Step 3.12 of the commit process shows
that once the shared lock has been released, all user-space cache
images of database content must be discarded.  This is done because
without a shared lock, other processes are free to modify the database
file content and so any user-space image of that content might become
obsolete.  Consequently, each new transaction would begin by rereading
data which had previously been read.  This is not as bad as it sounds
at first since the data being read is still likely in the operating
systems file cache.  So the "read" is really just a copy of data
from kernel space into user space.  But even so, it still takes time.

Beginning with SQLite version 3.3.14 a mechanism has been added
to try to reduce the needless rereading of data.  In newer versions
of SQLite, the data in the user-space pager cache is retained when
the lock on the database file is released.  Later, after the
shared lock is acquired at the beginning of the next transaction,
SQLite checks to see if any other process has modified the database
file.  If the database has been changed in any way since the lock
was last released, the user-space cache is erased at that point.
But commonly the database file is unchanged and the user-space cache
can be retained, and some unnecessary read operations can be avoided.

In order to determine whether or not the database file has changed,
SQLite uses a counter in the database header (in bytes 24 through 27)
which is incremented during every change operation.  SQLite saves a copy
of this counter prior to releasing its database lock.  Then after
acquiring the next database lock it compares the saved counter value
against the current counter value and erases the cache if the values
are different, or reuses the cache if they are the same.


c2: Atomic Commit In SQLite
c3: 7.2. Exclusive Access Mode
c5: atomiccommit.html#_exclusive_access_mode
c4:
SQLite version 3.3.14 adds the concept of "Exclusive Access Mode".
In exclusive access mode, SQLite retains the exclusive
database lock at the conclusion of each transaction.  This prevents
other processes from accessing the database, but in many deployments
only a single process is using a database so this is not a
serious problem.  The advantage of exclusive access mode is that
disk I/O can be reduced in three ways:


It is not necessary to increment the change counter in the
database header for transactions after the first transaction.  This
will often save a write of page one to both the rollback
journal and the main database file.

No other processes can change the database so there is never
a need to check the change counter and clear the user-space cache
at the beginning of a transaction.

Each transaction can be committed by overwriting the rollback
journal header with zeros rather than deleting the journal file.
This avoids having to modify the directory entry for the journal file
and it avoids having to deallocate disk sectors associated with the 
journal.  Furthermore, the next transaction will overwrite existing
journal file content rather than append new content and on most systems
overwriting is much faster than appending.


The third optimization, zeroing the journal file header rather than
deleting the rollback journal file,
does not depend on holding an exclusive lock at all times.
This optimization can be set independently of exclusive lock mode
using the journal_mode pragma
as described in section 7.6 below.


c2: Atomic Commit In SQLite
c3: 7.3. Do Not Journal Freelist Pages
c5: atomiccommit.html#_do_not_journal_freelist_pages
c4:
When information is deleted from an SQLite database, the pages used
to hold the deleted information are added to a "freelist".  Subsequent
inserts will draw pages off of this freelist rather than expanding the
database file.

Some freelist pages contain critical data; specifically the locations
of other freelist pages.  But most freelist pages contain nothing useful.
These latter freelist pages are called "leaf" pages.  We are free to
modify the content of a leaf freelist page in the database without
changing the meaning of the database in any way.

Because the content of leaf freelist pages is unimportant, SQLite
avoids storing leaf freelist page content in the rollback journal
in step 3.5 of the commit process.
If a leaf freelist page is changed and that change does not get rolled back
during a transaction recovery, the database is not harmed by the omission.
Similarly, the content of a new freelist page is never written back
into the database at step 3.9 nor
read from the database at step 3.3.
These optimizations can greatly reduce the amount of I/O that occurs
when making changes to a database file that contains free space.


c2: Atomic Commit In SQLite
c3: 7.4. Single Page Updates And Atomic Sector Writes
c5: atomiccommit.html#_single_page_updates_and_atomic_sector_writes
c4:
Beginning in SQLite version 3.5.0, the new Virtual File System (VFS)
interface contains a method named xDeviceCharacteristics which reports
on special properties that the underlying mass storage device
might have.  Among the special properties that
xDeviceCharacteristics might report is the ability of to do an
atomic sector write.

Recall that by default SQLite assumes that sector writes are
linear but not atomic.  A linear write starts at one end of the
sector and changes information byte by byte until it gets to the
other end of the sector.  If a power loss occurs in the middle of
a linear write then part of the sector might be modified while the
other end is unchanged.  In an atomic sector write, either the entire
sector is overwritten or else nothing in the sector is changed.

We believe that most modern disk drives implement atomic sector
writes.  When power is lost, the drive uses energy stored in capacitors
and/or the angular momentum of the disk platter to provide power to 
complete any operation in progress.  Nevertheless, there are so many
layers in between the write system call and the on-board disk drive
electronics that we take the safe approach in both Unix and w32 VFS
implementations and assume that sector writes are not atomic.  On the
other hand, device
manufacturers with more control over their filesystems might want
to consider enabling the atomic write property of xDeviceCharacteristics
if their hardware really does do atomic writes.

When sector writes are atomic and the page size of a database is
the same as a sector size, and when there is a database change that
only touches a single database page, then SQLite skips the whole
journaling and syncing process and simply writes the modified page
directly into the database file.  The change counter in the first
page of the database file is modified separately since no harm is
done if power is lost before the change counter can be updated.


c2: Atomic Commit In SQLite
c3: 7.5. Filesystems With Safe Append Semantics
c5: atomiccommit.html#_filesystems_with_safe_append_semantics
c4:
Another optimization introduced in SQLite version 3.5.0 makes
use of "safe append" behavior of the underlying disk.
Recall that SQLite assumes that when data is appended to a file
(specifically to the rollback journal) that the size of the file
is increased first and that the content is written second.  So
if power is lost after the file size is increased but before the
content is written, the file is left containing invalid "garbage"
data.  The xDeviceCharacteristics method of the VFS might, however,
indicate that the filesystem implements "safe append" semantics.
This means that the content is written before the file size is
increased so that it is impossible for garbage to be introduced
into the rollback journal by a power loss or system crash.

When safe append semantics are indicated for a filesystem,
SQLite always stores the special value of -1 for the page count
in the header of the rollback journal.  The -1 page count value
tells any process attempting to rollback the journal that the
number of pages in the journal should be computed from the journal
size.  This -1 value is never changed.  So that when a commit
occurs, we save a single flush operation and a sector write of
the first page of the journal file.  Furthermore, when a cache
spill occurs we no longer need to append a new journal header
to the end of the journal; we can simply continue appending
new pages to the end of the existing journal.


c2: Atomic Commit In SQLite
c3: 7.6. Persistent Rollback Journals
c5: atomiccommit.html#_persistent_rollback_journals
c4:
Deleting a file is an expensive operation on many systems.
So as an optimization, SQLite can be configured to avoid the
delete operation of section 3.11.
Instead of deleting the journal file in order to commit a transaction,
the file is either truncated to zero bytes in length or its
header is overwritten with zeros.  Truncating the file to zero
length saves having to make modifications to the directory containing
the file since the file is not removed from the directory. 
Overwriting the header has the additional savings of not having
to update the length of the file (in the "inode" on many systems)
and not having to deal with newly freed disk sectors.  Furthermore,
at the next transaction the journal will be created by overwriting
existing content rather than appending new content onto the end
of a file, and overwriting is often much faster than appending.

SQLite can be configured to commit transactions by overwriting
the journal header with zeros instead of deleting the journal file
by setting the "PERSIST" journaling mode using the 
journal_mode PRAGMA.
For example:


PRAGMA journal_mode=PERSIST;


The use of persistent journal mode provides a noticeable performance
improvement on many systems.  Of course, the drawback is that the 
journal files remain on the disk, using disk space and cluttering
directories, long after the transaction commits.  The only safe way
to delete a persistent journal file is to commit a transaction
with journaling mode set to DELETE:


PRAGMA journal_mode=DELETE;
BEGIN EXCLUSIVE;
COMMIT;


Beware of deleting persistent journal files by any other means
since the journal file might be hot, in which case deleting it will
corrupt the corresponding database file.

Beginning in SQLite version 3.6.4 (2008-10-15), 
the TRUNCATE journal mode is
also supported:


PRAGMA journal_mode=TRUNCATE;


In truncate journal mode, the transaction is committed by truncating
the journal file to zero length rather than deleting the journal file
(as in DELETE mode) or by zeroing the header (as in PERSIST mode).
TRUNCATE mode shares the advantage of PERSIST mode that the directory
that contains the journal file and database does not need to be updated.
Hence truncating a file is often faster than deleting it.  TRUNCATE has
the additional advantage that it is not followed by a
system call (ex: fsync()) to synchronize the change to disk.  It might
be safer if it did.
But on many modern filesystems, a truncate is an atomic and
synchronous operation and so we think that TRUNCATE will usually be safe
in the face of power failures.  If you are uncertain about whether or
not TRUNCATE will be synchronous and atomic on your filesystem and it is
important to you that your database survive a power loss or operating
system crash that occurs during the truncation operation, then you might
consider using a different journaling mode.

On embedded systems with synchronous filesystems, TRUNCATE results
in slower behavior than PERSIST.  The commit operation is the same speed.
But subsequent transactions are slower following a TRUNCATE because it is
faster to overwrite existing content than to append to the end of a file.
New journal file entries will always be appended following a TRUNCATE but
will usually overwrite with PERSIST.


c2: Atomic Commit In SQLite
c3: 8. Testing Atomic Commit Behavior
c5: atomiccommit.html#_testing_atomic_commit_behavior
c4:
The developers of SQLite are confident that it is robust
in the face of power failures and system crashes because the
automatic test procedures do extensive checks on
the ability of SQLite to recover from simulated power loss.
We call these the "crash tests".

Crash tests in SQLite use a modified VFS that can simulate
the kinds of filesystem damage that occur during a power
loss or operating system crash.  The crash-test VFS can simulate
incomplete sector writes, pages filled with garbage data because
a write has not completed, and out of order writes, all occurring
at varying points during a test scenario.  Crash tests execute
transactions over and over, varying the time at which a simulated
power loss occurs and the properties of the damage inflicted.
Each test then reopens the database after the simulated crash and
verifies that the transaction either occurred completely
or not at all and that the database is in a completely
consistent state.

The crash tests in SQLite have discovered a number of very
subtle bugs (now fixed) in the recovery mechanism.  Some of 
these bugs were very obscure and unlikely to have been found
using only code inspection and analysis techniques.  From this
experience, the developers of SQLite feel confident that any other
database system that does not use a similar crash test system
likely contains undetected bugs that will lead to database
corruption following a system crash or power failure.


c2: Atomic Commit In SQLite
c3: 9. Things That Can Go Wrong
c5: atomiccommit.html#_things_that_can_go_wrong
c4:
The atomic commit mechanism in SQLite has proven to be robust,
but it can be circumvented by a sufficiently creative
adversary or a sufficiently broken operating system implementation.
This section describes a few of the ways in which an SQLite database
might be corrupted by a power failure or system crash.
(See also: How To Corrupt Your Database Files.)


c2: Atomic Commit In SQLite
c3: 9.1. Broken Locking Implementations
c5: atomiccommit.html#_broken_locking_implementations
c4:
SQLite uses filesystem locks to make sure that only one
process and database connection is trying to modify the database
at a time.  The filesystem locking mechanism is implemented
in the VFS layer and is different for every operating system.
SQLite depends on this implementation being correct.  If something
goes wrong and two or more processes are able to write the same
database file at the same time, severe damage can result.

We have received reports of implementations of both
Windows network filesystems and NFS in which locking was
subtly broken.  We can not verify these reports, but as
locking is difficult to get right on a network filesystem
we have no reason to doubt them.  You are advised to 
avoid using SQLite on a network filesystem in the first place,
since performance will be slow.  But if you must use a 
network filesystem to store SQLite database files, consider
using a secondary locking mechanism to prevent simultaneous
writes to the same database even if the native filesystem
locking mechanism malfunctions.

The versions of SQLite that come preinstalled on Apple
Mac OS X computers contain a version of SQLite that has been
extended to use alternative locking strategies that work on
all network filesystems that Apple supports.  These extensions
used by Apple work great as long as all processes are accessing
the database file in the same way.  Unfortunately, the locking
mechanisms do not exclude one another, so if one process is
accessing a file using (for example) AFP locking and another
process (perhaps on a different machine) is using dot-file locks,
the two processes might collide because AFP locks do not exclude
dot-file locks or vice versa.


c2: Atomic Commit In SQLite
c3: 9.2. Incomplete Disk Flushes
c5: atomiccommit.html#_incomplete_disk_flushes
c4:
SQLite uses the fsync() system call on Unix and the FlushFileBuffers()
system call on w32 in order to sync the file system buffers onto disk
oxide as shown in step 3.7 and
step 3.10.  Unfortunately, we have received
reports that neither of these interfaces works as advertised on many
systems.  We hear that FlushFileBuffers() can be completely disabled
using registry settings on some Windows versions.  Some historical
versions of Linux contain versions of fsync() which are no-ops on
some filesystems, we are told.  Even on systems where 
FlushFileBuffers() and fsync() are said to be working, often
the IDE disk control lies and says that data has reached oxide
while it is still held only in the volatile control cache.

On the Mac, you can set this pragma:


PRAGMA fullfsync=ON;


Setting fullfsync on a Mac will guarantee that data really does
get pushed out to the disk platter on a flush.  But the implementation
of fullfsync involves resetting the disk controller.  And so not only
is it profoundly slow, it also slows down other unrelated disk I/O.
So its use is not recommended.


c2: Atomic Commit In SQLite
c3: 9.3. Partial File Deletions
c5: atomiccommit.html#_partial_file_deletions
c4:
SQLite assumes that file deletion is an atomic operation from the
point of view of a user process.  If power fails in the middle of
a file deletion, then after power is restored SQLite expects to see
either the entire file with all of its original data intact, or it
expects not to find the file at all.  Transactions may not be atomic
on systems that do not work this way.


c2: Atomic Commit In SQLite
c3: 9.4. Garbage Written Into Files
c5: atomiccommit.html#_garbage_written_into_files
c4:
SQLite database files are ordinary disk files that can be
opened and written by ordinary user processes.  A rogue process
can open an SQLite database and fill it with corrupt data.  
Corrupt data might also be introduced into an SQLite database
by bugs in the operating system or disk controller; especially
bugs triggered by a power failure.  There is nothing SQLite can
do to defend against these kinds of problems.


c2: Atomic Commit In SQLite
c3: 9.5. Deleting Or Renaming A Hot Journal
c5: atomiccommit.html#_deleting_or_renaming_a_hot_journal
c4:
If a crash or power loss does occur and a hot journal is left on
the disk, it is essential that the original database file and the hot
journal remain on disk with their original names until the database
file is opened by another SQLite process and rolled back.  
During recovery at step 4.2 SQLite locates
the hot journal by looking for a file in the same directory as the
database being opened and whose name is derived from the name of the
file being opened.  If either the original database file or the
hot journal have been moved or renamed, then the hot journal will
not be seen and the database will not be rolled back.

We suspect that a common failure mode for SQLite recovery happens
like this:  A power failure occurs.  After power is restored, a well-meaning
user or system administrator begins looking around on the disk for
damage.  They see their database file named "important.data".  This file
is perhaps familiar to them.  But after the crash, there is also a
hot journal named "important.data-journal".  The user then deletes
the hot journal, thinking that they are helping to cleanup the system.
We know of no way to prevent this other than user education.

If there are multiple (hard or symbolic) links to a database file,
the journal will be created using the name of the link through which
the file was opened.  If a crash occurs and the database is opened again
using a different link, the hot journal will not be located and no
rollback will occur.

Sometimes a power failure will cause a filesystem to be corrupted
such that recently changed filenames are forgotten and the file is
moved into a "/lost+found" directory.  When that happens, the hot
journal will not be found and recovery will not occur.
SQLite tries to prevent this
by opening and syncing the directory containing the rollback journal
at the same time it syncs the journal file itself.  However, the
movement of files into /lost+found can be caused by unrelated processes
creating unrelated files in the same directory as the main database file.
And since this is out from under the control of SQLite, there is nothing
that SQLite can do to prevent it.  If you are running on a system that
is vulnerable to this kind of filesystem namespace corruption (most
modern journalling filesystems are immune, we believe) then you might
want to consider putting each SQLite database file in its own private
subdirectory.


c2: Atomic Commit In SQLite
c3: 10. Future Directions And Conclusion
c5: atomiccommit.html#_future_directions_and_conclusion
c4:
Every now and then someone discovers a new failure mode for
the atomic commit mechanism in SQLite and the developers have to
put in a patch.  This is happening less and less and the
failure modes are becoming more and more obscure.  But it would
still be foolish to suppose that the atomic commit logic of
SQLite is entirely bug-free.  The developers are committed to fixing
these bugs as quickly as they might be found.


The developers are also on the lookout for new ways to
optimize the commit mechanism.  The current VFS implementations
for Unix (Linux and Mac OS X) and Windows make pessimistic assumptions about
the behavior of those systems.  After consultation with experts
on how these systems work, we might be able to relax some of the
assumptions on these systems and allow them to run faster.  In
particular, we suspect that most modern filesystems exhibit the
safe append property and that many of them might support atomic
sector writes.  But until this is known for certain, SQLite will
take the conservative approach and assume the worst.


c2: The Use Of assert() In SQLite
c3: 1. Assert() And Similar Macros In SQLite
c5: assert.html#assert_and_similar_macros_in_sqlite
c4:
The assert(X) macro is 
part of standard C, in the
&lt;assert.h&gt; header file.
SQLite adds three other assert()-like macros named NEVER(X), ALWAYS(X),
and testcase(X).


assert(X) &rarr;
The assert(X) statement indicates that the condition X is always true.
In other words, X is an invariant.  The assert(X) macro works like a
procedure in that it has no return value.

ALWAYS(X) &rarr;
The ALWAYS(X) function indicates that condition X is always true as far
as the developers know, but there is no proof the X is true, or the
proof is complex and error-prone, or the proof depends on implementation
details that are likely to change in the future.  ALWAYS(X) behaves like
a function that returns the boolean value X, and is intended to be used
within the conditional of an "if" statement.

NEVER(X) &rarr;
The NEVER(X) function indicates that condition X is never true.  This
is the negative analog of the ALWAYS(X) function.

testcase(X) &rarr;
The testcase(X) statement indicates that X is sometimes true and sometimes
false.  In other words, testcase(X) indicates that X is definitely not an
invariant.  Since SQLite uses 100% MC/DC testing, the presence of a
testcase(X) macro indicates that not only is it possible for X to be either
true or false, but there are test cases to demonstrate this.



SQLite version 3.22.0 (2018-01-22) contains 5290 assert() macros,
839 testcase() macros, 88 ALWAYS() macros, and 63 NEVER() macros.


c2: The Use Of assert() In SQLite
c3: 1.1. Philosophy of assert()
c5: assert.html#philosophy_of_assert_
c4:
In SQLite, the presence of assert(X) means that the developers have
a proof that X is always true.  Readers can depend upon X being true to
help them reason about the code.  An assert(X) is a strong statement
about the truth of X.  There is no doubt.

The ALWAYS(X) and NEVER(X) macros are a weaker statement about the
truth of X.  The presence of ALWAYS(X) or NEVER(X) means that the developers
believe X is always or never true, but there is no proof, or the proof
is complex and error-prone, or the proof depends on other aspects 
of the system that seem likely to change.

Other systems sometimes use assert(X) in a way that is
similar to the use of ALWAYS(X) or NEVER(X) in SQLite.
Developers will add an assert(X) as a 
tacit acknowledgement that they
do not fully believe that X is always true.
We believe that this use of assert(X) is wrong and violates the intent
and purpose of having assert(X) available in C in the first place.
An assert(X) should not be seen as a safety-net or top-rope used to
guard against mistakes.  Nor is assert(X) appropriate for defense-in-depth.
An ALWAYS(X) or NEVER(X) macro, or something similar, should be used in 
those cases because ALWAYS(X) or NEVER(X) will be followed by code to
actually deal with the problem when the programmers reasoning
turns out to be wrong.  Since the code that follows ALWAYS(X) or NEVER(X)
is untested, it should be something very simple, like a "return" statement,
that is easily verified by inspection.


Because assert() can be and is commonly misused, some programming language
theorists and designers look upon it with disfavor.
For example, the designers of the Go programming language 
intentionally omit a built-in assert().
They feel that the harm caused by misuse of assert()
outweighs the benefits of including it as a language built-in.
The SQLite developers disagree.  In fact, the original purpose of this
article is to push back against the common notion that assert() is harmful.
In our experience, SQLite would be much more difficult to develop, test,
and maintain without assert().


c2: The Use Of assert() In SQLite
c3: 1.2. Different Behaviors According To Build Type
c5: assert.html#different_behaviors_according_to_build_type
c4:
Three separate builds are used to validate the SQLite software.

 A functionality testing build is used to validate the source code.
 A coverage testing build is used to validate the test suite, to confirm
     that the test suite provides 100% MC/DC.
 The release build is used to validate the generated machine code.

All tests must give the same answer in all three
builds. See the "How SQLite Is Tested" document for more detail.

The various assert()-like
macros behave differently according to how SQLite is built.


Functionality TestingCoverage TestingRelease
assert(X)
abort() if X is false
no-op
no-op

ALWAYS(X)
abort() if X is false
always true
pass through the value X

NEVER(X)
abort() if X is true
always false
pass through the value X

testcase(X)
no-op
do some harmless work if X is true
no-op



The default behavior of assert(X) in standard C is that it is enabled
for release builds.  This is a reasonable default.  However, the
SQLite code base has many assert() statements in performance-sensitive
areas of the code.  Leaving assert(X) turned on causes SQLite to run about
three times slower.  Also, SQLite strives to provide 100% MC/DC in an
as-delivered configuration, which is obviously impossible if assert(X)
statements are enabled.  For these reasons, assert(X) is a no-op for
release builds in SQLite.

The ALWAYS(X) and NEVER(X) macros behave like assert(X) during
functionality testing, because the developers want to be immediately
alerted to the issue if the value of X is different from what is expected.
But for delivery, ALWAYS(X) and NEVER(X) are simple pass-through macros,
which provide defense-in-depth.  For coverage testing ALWAYS(X) and NEVER(X)
are hard-coded boolean values so that they do not cause unreachable
machine code to be generated.

The testcase(X) macro is normally a no-op, but for a coverage test
build it does generate a small amount of extra code that includes at least
one branch, in order to verify that test cases exist for which X is both
true and false.


c2: The Use Of assert() In SQLite
c3: 2. Examples
c5: assert.html#examples
c4:
An assert() statement is often used to validate pre-conditions on 
internal functions and methods.
Example: https://sqlite.org/src/artifact/c1e97e4c6f?ln=1048.
This is deemed better than simply stating the pre-condition in a header 
comment, since the assert() is actually executed.  In a highly tested
program like SQLite, the reader knows that the pre-condition is true
for all of the hundreds of millions of test cases run against SQLite,
since it has been verified by the assert().
In contrast, a text pre-condition statement in a header comment
is untested.  It might have been true when the code was written, 
but who is to say that it is still true now?


Sometimes SQLite uses compile-time evaluatable assert() statements.
Consider the code at
https://sqlite.org/src/artifact/c1e97e4c6f?ln=2130-2138.
Four assert() statements verify the values for compile-time constants
so that the reader can quickly check the validity of the if-statement
that follows, without having to look up the constant values in a separate
header file.


Sometimes compile-time assert() statements are used to verify that
SQLite has been correctly compiled.  For example, the code at
https://sqlite.org/src/artifact/c1e97e4c6f?ln=157
verifies that the SQLITE_PTRSIZE preprocessor macro is set correctly
for the target architecture.


The CORRUPT_DB macro is used in many assert() statements.
In functional testing builds, CORRUPT_DB references a global variable
that is true if the database file might contain corruption.  This variable
is true by default, since we do not normally know whether or not a database
is corrupt, but during testing while working on databases that are known
to be well-formed, that global variable can be set to false.
Then the CORRUPT_DB macro
can be used in assert() statements such as seen at
https://sqlite.org/src/artifact/18a53540aa3?ln=1679-1680.
Those assert()s specify pre-conditions to the routine that are true for
consistent database files, but which might be false if the database file
is corrupt. Knowledge of these kinds of conditions is very helpful to
readers who are trying to understand a block of code in isolation.


ALWAYS(X) and NEVER(X) functions are used in places where we always
want the test to occur even though the developers believe the value of
X is always true or false.  For example, the sqlite3BtreeCloseCursor()
routine shown must remove the closing cursor from a linked list of all
cursors.  We know that the cursor is on the list, so that the loop
must terminate by the "break" statement, but it is convenient to
use the ALWAYS(X) test at
https://sqlite.org/src/artifact/18a53540aa3?ln=4371 to prevent
running off the end of the linked list in case there is an error in some
other part of the code that has corrupted the linked list.


An ALWAYS(X) or NEVER(X) sometimes verifies pre-conditions that are
subject to change if other parts of the code are modified in
subtle ways.  At https://sqlite.org/src/artifact/18a53540aa3?ln=5512-5516
we have a test for two pre-conditions that are true only because
of the limited scope of use of the sqlite3BtreeRowCountEst() function.
Future enhancements to SQLite might use sqlite3BtreeRowCountEst() in
new ways where those preconditions no longer hold, and the NEVER()
macros will quickly alert the developers to that fact when the
situation arises.  But if, for some reason, the pre-conditions are
not satisfied in a release build, the program will still behave sanely
and will not do an undefined memory access.


The testcase() macro is often used to verify that boundary
cases of an inequality comparison are checked.  For example, at
https://sqlite.org/src/artifact/18a53540aa3?ln=5766.  These
kind of checks help to prevent off-by-one errors.


c2: NUL Characters In Strings
c3: 1. Introduction
c5: nulinstr.html#introduction
c4:
SQLite allows NUL characters (ASCII 0x00, Unicode \u0000) in the middle
of string values stored in the database.  However, the use of NUL within
strings can lead to surprising behaviors:



The length() SQL function only counts characters up to and excluding
the first NUL.



The quote() SQL function only shows characters up to and excluding
the first NUL.


The .dump command in the CLI omits the first NUL character and all
subsequent text in the SQL output that it generates.  In fact, the
CLI omits everything past the first NUL character in all contexts.



The use of NUL characters in SQL text strings is not recommended.


c2: NUL Characters In Strings
c3: 2. Unexpected Behavior
c5: nulinstr.html#unexpected_behavior
c4:
Consider the following SQL:

CREATE TABLE t1(
  a INTEGER PRIMARY KEY,
  b TEXT
);
INSERT INTO t1(a,b) VALUES(1, 'abc'||char(0)||'xyz');

SELECT a, b, length(b) FROM t1;



The SELECT statement above shows output of:

1,'abc',3



(Through this document, we assume that the CLI has ".mode quote" set.)
But if you run:

SELECT * FROM t1 WHERE b='abc';



Then no rows are returned.  SQLite knows that the t1.b column actually
holds a 7-character string, and the 7-character string 'abc'||char(0)||'xyz'
is not equal to the 3-character string 'abc', and so no rows are returned.
But a user might be easily confused by this because the CLI output
seems to show that the string has only 3 characters.  This seems like
a bug.  But it is how SQLite works.


c2: NUL Characters In Strings
c3: 3. How To Tell If You Have NUL Characters In Your Strings
c5: nulinstr.html#how_to_tell_if_you_have_nul_characters_in_your_strings
c4:
If you CAST a string into a BLOB, then the entire length of the
string is shown.  For example:

SELECT a, CAST(b AS BLOB) FROM t1;



Gives this result:

1,X'6162630078797a'



In the BLOB output, you can clearly see the NUL character as the 4th
character in the 7-character string.


Another, more automated, way
to tell if a string value X contains embedded NUL characters is to
use an expression like this:

instr(X,char(0))



If this expression returns a non-zero value N, then there exists an 
embedded NUL at the N-th character position.  Thus to count the number
of rows that contain embedded NUL characters:

SELECT count(*) FROM t1 WHERE instr(b,char(0))>0;


c2: NUL Characters In Strings
c3: 4. Removing NUL Characters From A Text Field
c5: nulinstr.html#removing_nul_characters_from_a_text_field
c4:
The following example shows how to remove NUL character, and all text
that follows, from a column of a table.  So if you have a database file
that contains embedded NULs and you would like to remove them, running
UPDATE statements similar to the following might help:

UPDATE t1 SET b=substr(b,1,instr(b,char(0)))
 WHERE instr(b,char(0));


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 1. Introduction
c5: withoutrowid.html#introduction
c4:
By default, every row in SQLite has a special column, usually called the
"rowid", that uniquely identifies that row within the table.  However
if the phrase "WITHOUT ROWID" is added to the end of a CREATE TABLE statement,
then the special "rowid" column is omitted.  There are sometimes
space and performance advantages to omitting the rowid.

A WITHOUT ROWID table is a table that uses a 
Clustered Index
as the primary key.


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 1.1. Syntax
c5: withoutrowid.html#syntax
c4:
To create a WITHOUT ROWID table, simply add the keywords "WITHOUT ROWID"
to the end of the CREATE TABLE statement.  For example:


CREATE TABLE IF NOT EXISTS wordcount(
  word TEXT PRIMARY KEY,
  cnt INTEGER
) WITHOUT ROWID;


As with all SQL syntax, the case of the keywords does not matter.  
One can write "WITHOUT rowid" or "without rowid" or "WiThOuT rOwId" and
it will mean the same thing.

Every WITHOUT ROWID table must have a PRIMARY KEY.  An error is raised
if a CREATE TABLE statement with the WITHOUT ROWID clause lacks a PRIMARY KEY.

In most contexts, the special "rowid" column of normal tables can 
also be called "oid" or "_rowid_".  However, only "rowid" works as 
the keyword in the CREATE TABLE statement.


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 1.2. Compatibility
c5: withoutrowid.html#compatibility
c4:
SQLite version 3.8.2 (2013-12-06) or later 
is necessary in order to use a WITHOUT
ROWID table.  An attempt to open a database that contains one or more WITHOUT
ROWID tables using an earlier version of SQLite will result in a
"malformed database schema" error.


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 1.3. Quirks
c5: withoutrowid.html#quirks
c4:
WITHOUT ROWID is found only in SQLite and is not compatible
with any other SQL database engine, as far as we know.
In an elegant system, all tables would behave as WITHOUT ROWID
tables even without the WITHOUT ROWID keyword.  However, when SQLite was
first designed, it used only integer rowids for row keys 
to simplify the implementation.
This approach worked well for many years.  But as the demands on
SQLite grew, the need for tables in which the PRIMARY KEY really did
correspond to the underlying row key grew more acute.  The WITHOUT ROWID
concept was added
in order to meet that need without breaking backwards
compatibility with the billions of SQLite databases already in use at
the time (circa 2013).


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 2. Differences From Ordinary Rowid Tables
c5: withoutrowid.html#differences_from_ordinary_rowid_tables
c4:
The WITHOUT ROWID syntax is an optimization.  It provides no new
capabilities.  Anything that can be done using a WITHOUT ROWID table
can also be done in exactly the same way, and exactly the same syntax,
using an ordinary rowid table.  The only advantage of a WITHOUT ROWID
table is that it can sometimes use less disk space and/or perform a little
faster than an ordinary rowid table.

For the most part, ordinary rowid tables and WITHOUT ROWID tables
are interchangeable.  But there are some additional restrictions on
WITHOUT ROWID tables that do not apply to ordinary rowid tables:



Every WITHOUT ROWID table must have a PRIMARY KEY.
An attempt to create a WITHOUT ROWID table without a PRIMARY KEY results
in an error.


The special behaviors associated "INTEGER PRIMARY KEY" do not apply
on WITHOUT ROWID tables.
In an ordinary table, "INTEGER PRIMARY KEY" means that the column is an
alias for the rowid.  But since there is no rowid in a WITHOUT ROWID
table, that special meaning no longer applies.  An "INTEGER PRIMARY KEY" 
column in a WITHOUT ROWID table works
like an "INT PRIMARY KEY" column in an ordinary table: It is a PRIMARY KEY
that has integer affinity.


AUTOINCREMENT does not work on WITHOUT ROWID tables.
The AUTOINCREMENT mechanism assumes the presence of a rowid and so it
does not work on a WITHOUT ROWID table.  An error is raised if the
 "AUTOINCREMENT" keyword is used in the CREATE TABLE statement for
a WITHOUT ROWID table.


NOT NULL is enforced on every column of the PRIMARY KEY in a WITHOUT
ROWID table.
This is in accordance with the SQL standard.  Each column of a PRIMARY KEY
is supposed to be individually NOT NULL.  However, NOT NULL was not enforced
on PRIMARY KEY columns by early versions of SQLite due to a bug.  By the
time that this bug was discovered, so many SQLite databases were already
in circulation that the decision was made not to fix this bug for fear of
breaking compatibility.  So, ordinary rowid tables in SQLite violate the
SQL standard and allow NULL values in PRIMARY KEY fields.  But WITHOUT ROWID
tables do follow the standard and will throw an error on any attempt to
insert a NULL into a PRIMARY KEY column.


The sqlite3_last_insert_rowid() function
does not work for WITHOUT ROWID tables.
Inserts into a WITHOUT ROWID do not change the value returned by the
sqlite3_last_insert_rowid() function.  The last_insert_rowid() SQL
function is also unaffected since it is just a wrapper around
sqlite3_last_insert_rowid().


The incremental blob I/O mechanism does not work
for WITHOUT ROWID tables.
Incremental BLOB I/O uses the rowid to create an sqlite3_blob object for
doing the direct I/O.  However, WITHOUT ROWID tables do not have a rowid,
and so there is no way to create an sqlite3_blob object for a WITHOUT
ROWID table.


The sqlite3_update_hook() interface does not fire callbacks for changes
to a WITHOUT ROWID table.
Part of the callback from sqlite3_update_hook() is the rowid of the table
row that has changed.  However, WITHOUT ROWID tables do not have a rowid.
Hence, the update hook is not invoked when a WITHOUT ROWID table changes.


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 3. Benefits Of WITHOUT ROWID Tables
c5: withoutrowid.html#benefits_of_without_rowid_tables
c4:
A WITHOUT ROWID table is an optimization that can reduce storage and
processing requirements.

In an ordinary SQLite table, the PRIMARY KEY is really just a 
UNIQUE index.  The key used to look up records on disk
is the rowid.
The special "INTEGER PRIMARY KEY" column type in ordinary SQLite tables 
causes the column to be an alias for the rowid, and so an INTEGER PRIMARY
KEY is a true PRIMARY KEY.  But any other kind of PRIMARY KEYs, including
"INT PRIMARY KEY" are just unique indexes in an ordinary rowid table.

Consider a table (shown below) intended to store a
vocabulary of words together with a count of the number of occurrences of
each word in some text corpus:


CREATE TABLE IF NOT EXISTS wordcount(
  word TEXT PRIMARY KEY,
  cnt INTEGER
);


As an ordinary SQLite table, "wordcount" is implemented as two
separate B-Trees.  The main table uses the hidden rowid value as the key
and stores the "word" and "cnt" columns as data.  The "TEXT PRIMARY KEY"
phrase of the CREATE TABLE statement
causes the creation of an unique index on the "word" column.  This index is a
separate B-Tree that uses "word" and the "rowid" as the key and stores no
data at all.  Note that the complete text of every "word" is stored twice:
once in the main table and again in the index.

Consider querying this table to find the number of occurrences of the
word "xyzzy".:


SELECT cnt FROM wordcount WHERE word='xyzzy';


This query first has to search the index B-Tree looking for any entry
that contains the matching value for "word".  When an entry is found in
the index, the rowid is extracted and used to search the main table.
Then the "cnt" value is read out of the main table and returned.  Hence, two
separate binary searches are required to fulfill the request.

A WITHOUT ROWID table uses a different data design for the equivalent
table.


CREATE TABLE IF NOT EXISTS wordcount(
  word TEXT PRIMARY KEY,
  cnt INTEGER
) WITHOUT ROWID;


In this latter table, there is only a single B-Tree which uses the "word"
column as its key and the "cnt" column as its data.  (Technicality:  the
low-level implementation actually stores both "word" and "cnt" in the "key"
area of the B-Tree.  But unless you are looking at the low-level byte encoding
of the database file, that fact is unimportant.)  Because there is only
a single B-Tree, the text of the "word" column is only stored once in the
database.  Furthermore, querying the "cnt" value for a specific "word"
only involves a single binary search into the main B-Tree, since the "cnt"
value can be retrieved directly from the record found by that first search
and without the need to do a second binary search on the rowid.

Thus, in some cases, a WITHOUT ROWID table can use about half the amount
of disk space and can operate nearly twice as fast.  Of course, in a 
real-world schema, there will typically be secondary indices and/or
UNIQUE constraints, and the situation is more complicated.  But even then,
there can often be space and performance advantages to using WITHOUT ROWID
on tables that have non-integer or composite PRIMARY KEYs.


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 4. When To Use WITHOUT ROWID
c5: withoutrowid.html#when_to_use_without_rowid
c4:
The WITHOUT ROWID optimization is likely to be helpful for tables
that have non-integer or composite (multi-column) PRIMARY KEYs and that do
not store large strings or BLOBs.

WITHOUT ROWID tables will work correctly (that is to say, they
provide the correct answer) for tables with a single INTEGER PRIMARY KEY. 
However, ordinary rowid tables will run faster in that case.  
Hence, it is good design
to avoid creating WITHOUT ROWID tables with single-column PRIMARY KEYs 
of type INTEGER.

WITHOUT ROWID tables work best when individual rows are not too large.
A good rule-of-thumb is that the average size of a single row in a
WITHOUT ROWID table should be less than about 1/20th the size of 
a database page.  That means that rows should not contain more than about
50 bytes each for a 1KiB page size or about 200 bytes each for 4KiB
page size.  WITHOUT ROWID tables will work (in the sense that
they get the correct answer) for arbitrarily large rows - up to 2GB in size -
but traditional rowid tables tend to work faster for large row sizes.
This is because rowid tables are implemented as B*-Trees where
all content is stored in the leaves of the tree, whereas WITHOUT ROWID 
tables are implemented using ordinary B-Trees with content stored on both
leaves and intermediate nodes.  Storing content in 
intermediate nodes causes each intermediate node entry to take up more
space on the page and thus reduces the fan-out, increasing the search cost.

The "sqlite3_analyzer.exe" utility program, available as source code
in the SQLite source tree or as a precompiled binary on the
SQLite Download page, can be
used to measure the average sizes of table rows in an existing SQLite
database.

Note that except for a few corner-case differences detailed above,
WITHOUT ROWID tables and rowid tables work the same.  They both generate
the same answers given the same SQL statements.  So it is a simple matter
to run experiments on an application, late in the development cycle,
to test whether or not the use of WITHOUT ROWID tables will be helpful.
A good strategy is to simply not worry about WITHOUT ROWID until near
the end of product development, then go back and run tests to see
if adding WITHOUT ROWID to tables with non-integer PRIMARY KEYs helps
or hurts performance, and retaining the WITHOUT ROWID only in those cases
where it helps.


c2: Clustered Indexes and the WITHOUT ROWID Optimization
c3: 5. Determining If An Existing Table Is WITHOUT ROWID
c5: withoutrowid.html#determining_if_an_existing_table_is_without_rowid
c4:
A WITHOUT ROWID table returns the same content for
PRAGMA table_info and PRAGMA table_xinfo as does an ordinary
table.  But unlike an ordinary table, a WITHOUT ROWID also
responds to the PRAGMA index_info command.  The PRAGMA index_info
on a WITHOUT ROWID table returns information abou the PRIMARY KEY
for the table.  In this way, the PRAGMA index_info command can be
used to unabiguously determine whether a particular table is a 
WITHOUT ROWID table or an ordinary table - an ordinary table will
always return no rows but a WITHOUT ROWID table will always return
one or more rows.


c2: sqldiff.exe: Database Difference Utility
c3: 1. Usage
c5: sqldiff.html#usage
c4:
The sqldiff.exe binary is a command-line utility program that
displays content differences between SQLite databases.  Example
usage:

sqldiff &#91;options&#93; database1.sqlite database2.sqlite



The usual output is an SQL script that will transform
database1.sqlite (the "source" database) into database2.sqlite
(the "destination" database).  This behavior can be
altered using command-line switches:


--changeset FILE
Do not write changes to standard output.  Instead, write a (binary)
       changeset file into FILE.  The changeset can be interpreted using
       the session extension to SQLite.
--lib LIBRARY
-L LIBRARY
Load the shared library or DLL file LIBRARY into SQLite prior to
       computing the differences.  This can be used to add application-defined
       collating sequences that are required by the schema.
--primarykey
Use the schema-defined PRIMARY KEY instead of the rowid to
       pair rows in the source and destination database.  (See additional
       explanation below.)
--schema
Show only column name and table differences in the schema,
       not the table content
--summary
Show how many rows have changed on each table, but do not show
       the actual changes
--table TABLE
Show only the differences in content for TABLE, not for the
       entire database
--transaction
Wrap SQL output in a single large transaction
--vtab
Add support for handling FTS3, FTS5 and rtree virtual tables. 
       See below for details.


c2: sqldiff.exe: Database Difference Utility
c3: 2. How It Works
c5: sqldiff.html#how_it_works
c4:
The sqldiff.exe utility works by finding rows in the source and
destination that are logical "pairs".  The default behavior is to
treat two rows as pairs if they are in tables with the same name
and they have the same rowid, or in the case of a WITHOUT ROWID
table if they have the same PRIMARY KEY.  Any differences in the
content of paired rows are output as UPDATEs.  Rows in the source
database that could not be paired are output as DELETEs.  Rows in
the destination database that could not be paired are output as
INSERTs.

The --primarykey flag changes the pairing algorithm slightly so
that the schema-declared PRIMARY KEY is always used for pairing,
even on tables that have a rowid.  This is often a better choice
for finding differences, however it can lead to missed differences in
the case of rows that have one or more PRIMARY KEY columns set to
NULL.


c2: sqldiff.exe: Database Difference Utility
c3: 3. Limitations
c5: sqldiff.html#limitations
c4:
The sqldiff.exe utility does not compute changesets for
either: rowid tables for which the rowid is inaccessible;
or tables which have no explicit primary key.
Given the --changeset option, sqldiff omits them from the comparison.
Examples of such tables are:

CREATE TABLE NilChangeset (
   -- inaccessible rowid due to hiding its aliases
   "rowid" TEXT,
   "oid" TEXT,
   "_rowid_" TEXT
);


and

CREATE TABLE NilChangeset (
   -- no explicit primary key
   "authorId" TEXT,
   "bookId" TEXT
);



When sqldiff is made to compare only such tables, no error occurs.
However, the result may be unexpected.
For example, the effect of this invocation:

sqldiff --changeset CHANGESET_OUT --table NilChangeset db1.sdb db2.sdb


will be to produce an empty file named "CHANGESET_OUT". See  session limitations for details.

The sqldiff.exe utility does not (currently) display differences in
TRIGGERs or VIEWs.


The sqldiff utility is not designed to support schema migrations
and is forgiving with respect to differing column definitions.
Normally, only the column names and their order are compared
for like-named tables before content comparison proceeds.

However, the single-table comparison option, with "sqlite_schema"
named, can be used to show or detect detailed schema differences
between a pair of databases.
When doing this, the output should not be used directly to modify a database.


By default, differences in the schema or content of virtual tables are
not reported on. 

However, if a virtual table implementation creates real tables (sometimes
referred to as "shadow" tables) within the database to store its data in, then
sqldiff.exe does calculate the difference between these. This can have
surprising effects if the resulting SQL script is then run on a database that
is not exactly the same as the source database. For several of SQLite's
bundled virtual tables (FTS3, FTS5, rtree and others), the surprising effects
may include corruption of the virtual table content.

 If the --vtab option is passed to sqldiff.exe, then it ignores all 
underlying shadow tables belonging to an FTS3, FTS5 or rtree virtual table
and instead includes the virtual table differences directly.


c2: EXPLAIN QUERY PLAN
c3: 1. The EXPLAIN QUERY PLAN Command
c5: eqp.html#the_explain_query_plan_command
c4:
Warning: The data returned by the EXPLAIN QUERY PLAN command is 
intended for interactive debugging only.  The output format may change
between SQLite releases. Applications should not depend on the output
format of the EXPLAIN QUERY PLAN command.


Alert: As warned above, the EXPLAIN QUERY PLAN output format did
change substantially with the version 3.24.0 release (2018-06-04).
Additional minor changes occurred in version 3.36.0 (2021-06-18).
Further changes are possible in subsequent releases.


The EXPLAIN QUERY PLAN SQL command is used to obtain a high-level
description of the strategy or plan that SQLite uses to implement a specific
SQL query.  Most significantly, EXPLAIN QUERY PLAN reports on the way in 
which the query uses database indices. This document is a guide to
understanding and interpreting the EXPLAIN QUERY PLAN output.  Background
information is available separately:


 A primer on How SQLite Works.
 Notes on the query optimizer.
 How indexing works.
 The next generation query planner.


A query plan is represented as a tree.
In raw form, as returned by sqlite3_step(), each node of the tree
consists of four fields:  An integer node id, an integer parent id,
an auxiliary integer field that is not currently used, and a description
of the node.
The entire tree is therefore a table with four columns and zero or more
rows.
The command-line shell will usually intercept this table and renders
it as an ASCII-art graph for more convenient viewing.  To disable the
shells automatic graph rendering and to display EXPLAIN QUERY PLAN
output in its tabular format, run the command ".explain off" to set
the "EXPLAIN formatting mode" to off.  To restore automatic graph rendering,
run ".explain auto".  You can see the current "EXPLAIN formatting mode" 
setting using the ".show" command.

One can also set the CLI into automatic EXPLAIN QUERY PLAN mode
using the ".eqp on" command:

sqlite&gt; .eqp on


 In automatic EXPLAIN QUERY PLAN mode, the shell automatically runs
a separate EXPLAIN QUERY PLAN query for each statement you enter and
displays the result before actually running the query.  Use the
".eqp off" command to turn automatic EXPLAIN QUERY PLAN mode back off.

EXPLAIN QUERY PLAN is most useful on a SELECT statement,
but may also appear with other statements that read data from database
tables (e.g. UPDATE, DELETE, INSERT INTO ... SELECT).


c2: EXPLAIN QUERY PLAN
c3: 1.1. Table and Index Scans
c5: eqp.html#table_and_index_scans
c4:
When processing a SELECT (or other) statement, SQLite may retrieve data from
  database tables in a variety of ways. It may scan through all the records in
  a table (a full-table scan), scan a contiguous subset of the records in a
  table based on the rowid index, scan a contiguous subset of the entries in a
  database index, or use a combination of the above strategies
  in a single scan. The various ways in which SQLite may retrieve data from a
  table or index are described in detail here.


  For each table read by the query, the output of EXPLAIN QUERY 
  PLAN includes a record for which the value in the "detail" column begins
  with either "SCAN" or "SEARCH". "SCAN" is used for a full-table scan,
  including cases where SQLite iterates through all records in a table
  in an order defined by an index. "SEARCH" indicates that only a subset of 
  the table rows are visited. Each SCAN or SEARCH record includes the
  following information:


   The name of the table, view, or subquery that data is read from.
   Whether or not an index or automatic index is used.
   Whether or not the covering index optimization applies.
   Which terms of the WHERE clause are used for indexing.



  For example, the following EXPLAIN QUERY PLAN command operates on a SELECT
  statement that is implemented by performing a full-table scan on table t1:
sqlite&gt; EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1;
QUERY PLAN
`--SCAN t1



  The example above shows
  SQLite picking full-table scan will visit all rows in the table.
  If the query were able to use an index, then the 
  SCAN/SEARCH record would include the name of the index and, for a
  SEARCH record, an indication of how the subset of rows visited is
  identified. For example:
sqlite&gt; CREATE INDEX i1 ON t1(a);
sqlite&gt; EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1;
QUERY PLAN
`--SEARCH t1 USING INDEX i1 (a=?)



  The previous example, SQLite uses index "i1" to optimize
  a WHERE clause term of the form (a=?) - in this case "a=1".
  The previous example could not use a covering index, but the following
  example can, and that fact is reflected in the output:
sqlite&gt; CREATE INDEX i2 ON t1(a, b);
sqlite&gt; EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1; 
QUERY PLAN
`--SEARCH t1 USING COVERING INDEX i2 (a=?)



  All joins in SQLite are implemented using nested scans. When a
  SELECT query that features a join is analyzed using EXPLAIN QUERY PLAN, one
  SCAN or SEARCH record is output for each nested loop. For example:
sqlite&gt; EXPLAIN QUERY PLAN SELECT t1.*, t2.* FROM t1, t2 WHERE t1.a=1 AND t1.b>2;
QUERY PLAN
|--SEARCH t1 USING INDEX i2 (a=? AND b>?)
`--SCAN t2



  The order of the entries indicates the nesting order. In
  this case, the scan of table t1 using index i2 is the outer loop (since it
  appears first)
  and the full-table scan of table t2 is the inner loop (since it appears
  last).
  In the following example, the positions of t1 and t2 in the FROM 
  clause of the SELECT are reversed. The query strategy remains the same.
  The output from EXPLAIN QUERY PLAN shows how the query is actually
  evaluated, not how it is specified in the SQL statement.
sqlite&gt; EXPLAIN QUERY PLAN SELECT t1.*, t2.* FROM t2, t1 WHERE t1.a=1 AND t1.b>2;
QUERY PLAN
|--SEARCH t1 USING INDEX i2 (a=? AND b>?)
`--SCAN t2





  If the WHERE clause of a query contains an OR expression, then SQLite might
  use the "OR by union" strategy (also known as the
  OR optimization). In this case there will be single top-level record
  for the search, with two sub-records, one for each index:
sqlite&gt; CREATE INDEX i3 ON t1(b);
sqlite&gt; EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=1 OR b=2;
QUERY PLAN
`--MULTI-INDEX OR
   |--SEARCH t1 USING COVERING INDEX i2 (a=?)
   `--SEARCH t1 USING INDEX i3 (b=?)


c2: EXPLAIN QUERY PLAN
c3: 1.2. Temporary Sorting B-Trees
c5: eqp.html#temporary_sorting_b_trees
c4:
If a SELECT query contains an ORDER BY, GROUP BY or DISTINCT clause, 
  SQLite may need to use a temporary b-tree structure to sort the output
  rows. Or, it might use an index. Using an index is 
  almost always much more efficient than performing a sort.
  If a temporary b-tree is required, a record is added to the EXPLAIN
  QUERY PLAN output with the "detail" field set to a string value of
  the form "USE TEMP B-TREE FOR xxx", where xxx is one of "ORDER BY",
  "GROUP BY" or "DISTINCT". For example:

sqlite&gt; EXPLAIN QUERY PLAN SELECT c, d FROM t2 ORDER BY c;
QUERY PLAN
|--SCAN t2
`--USE TEMP B-TREE FOR ORDER BY



  In this case using the temporary b-tree can be avoided by creating an index
  on t2(c), as follows:

sqlite&gt; CREATE INDEX i4 ON t2(c);
sqlite&gt; EXPLAIN QUERY PLAN SELECT c, d FROM t2 ORDER BY c; 
QUERY PLAN
`--SCAN t2 USING INDEX i4


c2: EXPLAIN QUERY PLAN
c3: 1.3. Subqueries
c5: eqp.html#subqueries
c4:
In all the examples above, there has only been a single SELECT statement.
  If a query contains sub-selects, those are shown as being children of
  the outer SELECT.  For example:

sqlite&gt; EXPLAIN QUERY PLAN SELECT (SELECT b FROM t1 WHERE a=0), (SELECT a FROM t1 WHERE b=t2.c) FROM t2;
|--SCAN TABLE t2 USING COVERING INDEX i4
|--SCALAR SUBQUERY
|  `--SEARCH t1 USING COVERING INDEX i2 (a=?)
`--CORRELATED SCALAR SUBQUERY
   `--SEARCH t1 USING INDEX i3 (b=?)



  The example above contains two "SCALAR" subqueries.  The subqueries
  are SCALAR in the sense that they return a single value - a one-row,
  one-column table.  If the actual query returns more than that, then
  only the first column of the first row is used.

  The first subquery above is constant with respect to the outer query.
  The value for the first subquery can be computed once and then reused
  for each row of the outer SELECT.  The second subquery, however, is
  "CORRELATED".  The value of the second subquery changes depending
  on values in the current row of the outer query.  Hence, the second
  subquery must be run once for each output row in the outer SELECT.


  Unless the flattening optimization is applied, if a subquery appears in
  the FROM clause of a SELECT statement, SQLite can either run the subquery and
  stores the results in a temporary table, or it can run the subquery as a
  co-routine.  The following query is an example of the latter.  The subquery
  is run by a co-routine.  The outer query blocks whenever it needs another
  row of input from the subquery.  Control switches to the co-routine which
  produces the desired output row, then control switches back to the main
  routine which continues processing.  

sqlite&gt; EXPLAIN QUERY PLAN SELECT count(*)
      &gt; FROM (SELECT max(b) AS x FROM t1 GROUP BY a) AS qqq
      &gt; GROUP BY x;
QUERY PLAN
|--CO-ROUTINE qqq
|  `--SCAN t1 USING COVERING INDEX i2
|--SCAN qqqq
`--USE TEMP B-TREE FOR GROUP BY



  
  If the flattening optimization is used on a subquery in the FROM clause
  of a SELECT statement, that effectively merges the subquery into the outer
  query.  The output of EXPLAIN QUERY PLAN reflects this, as in the following
  example:

sqlite&gt; EXPLAIN QUERY PLAN SELECT * FROM (SELECT * FROM t2 WHERE c=1) AS t3, t1;
QUERY PLAN
|--SEARCH t2 USING INDEX i4 (c=?)
`--SCAN t1




  If the content of a subquery might need to be visited more than once, then
  the use of a co-routine is undesirable, as the co-routine would then have to
  compute the data more than once.  And if the subquery cannot be flattened,
  that means the subquery must be manifested into a transient table.

sqlite&gt; SELECT * FROM
      &gt;   (SELECT * FROM t1 WHERE a=1 ORDER BY b LIMIT 2) AS x,
      &gt;   (SELECT * FROM t2 WHERE c=1 ORDER BY d LIMIT 2) AS y;
QUERY PLAN
|--MATERIALIZE x
|  `--SEARCH t1 USING COVERING INDEX i2 (a=?)
|--MATERIALIZE y
|  |--SEARCH t2 USING INDEX i4 (c=?)
|  `--USE TEMP B-TREE FOR ORDER BY
|--SCAN x
`--SCAN y


c2: EXPLAIN QUERY PLAN
c3: 1.4. Compound Queries
c5: eqp.html#compound_queries
c4:
Each component query of a compound query (UNION, UNION ALL, EXCEPT or 
  INTERSECT) is assigned computed separately and is given its own line in
  the EXPLAIN QUERY PLAN output.

sqlite&gt; EXPLAIN QUERY PLAN SELECT a FROM t1 UNION SELECT c FROM t2;
QUERY PLAN
`--COMPOUND QUERY
   |--LEFT-MOST SUBQUERY
   |  `--SCAN t1 USING COVERING INDEX i1
   `--UNION USING TEMP B-TREE
      `--SCAN t2 USING COVERING INDEX i4



  The "USING TEMP B-TREE" clause in the above output indicates that a 
  temporary b-tree structure is used to implement the UNION of the results
  of the two sub-selects.  An alternative method of computing a compound
  is to run each subquery as a co-routine, arrange for their outputs to
  appear in sorted order, and merge the results together.  When the query
  planner chooses this latter approach, the EXPLAIN QUERY PLAN output
  looks like this:

sqlite&gt; EXPLAIN QUERY PLAN SELECT a FROM t1 EXCEPT SELECT d FROM t2 ORDER BY 1;
QUERY PLAN
`--MERGE (EXCEPT)
   |--LEFT
   |  `--SCAN t1 USING COVERING INDEX i1
   `--RIGHT
      |--SCAN t2
      `--USE TEMP B-TREE FOR ORDER BY


c2: SQLite Foreign Key Support
c3: Overview
c5: foreignkeys.html#overview
c4:
This document describes the support for SQL foreign key constraints
   introduced in SQLite version 3.6.19 (2009-10-14). 

The first section introduces the 
   concept of an SQL foreign key by example and defines the terminology 
   used for the remainder of the document. Section 2 describes the steps 
   an application must take in order to enable foreign key constraints in 
   SQLite (it is disabled by default). The next section, section 3, 
   describes the indexes that the user must create in order to use 
   foreign key constraints, and those that should be created in order for
   foreign key constraints to function efficiently. Section 4 describes
   the advanced foreign key related features supported by SQLite and
   section 5 describes the way the ALTER and DROP TABLE commands are
   enhanced to support foreign key constraints. Finally, section 6 
   enumerates the missing features and limits of the current implementation.

This document does not contain a full description of the syntax used
   to create foreign key constraints in SQLite. This may be found as 
   part of the documentation for the CREATE TABLE statement.


c2: SQLite Foreign Key Support
c3: 1. Introduction to Foreign Key Constraints
c5: foreignkeys.html#fk_basics
c4:
SQL foreign key constraints are used to enforce "exists" relationships 
    between tables. For example, consider a database schema created using 
    the following SQL commands:

CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER,
  trackname   TEXT, 
  trackartist INTEGER     -- Must map to an artist.artistid!
);


  
    The applications using this database are entitled to assume that for
    each row in the track table there exists a corresponding row in the
    artist table. After all, the comment in the declaration says so.
    Unfortunately, if a user edits the database using an external tool or 
    if there is a bug in an application, rows might be inserted into the 
    track table that do not correspond to any row in the artist
    table. Or rows might be deleted from the artist table, leaving
    orphaned rows in the track table that do not correspond to any of
    the remaining rows in artist. This might cause the application
    or applications to malfunction later on, or at least make coding the
    application more difficult.

  
    One solution is to add an SQL foreign key constraint to the database 
    schema to enforce the relationship between the artist and 
    track table. To do so, a foreign key definition may be added
    by modifying the declaration of the track table to the following:

CREATE TABLE track(
  trackid     INTEGER, 
  trackname   TEXT, 
  trackartist INTEGER,
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);


  
    This way, the constraint is enforced by SQLite. Attempting to insert
    a row into the track table that does not correspond to any
    row in the artist table will fail, as will attempting to
    delete a row from the artist table when there exist dependent 
    rows in the track table There is one exception: if the foreign
    key column in the track table is NULL, then no corresponding
    entry in the artist table is required. Expressed in SQL, this
    means that for every row in the track table, the following
    expression evaluates to true:
trackartist IS NULL OR EXISTS(SELECT 1 FROM artist WHERE artistid=trackartist)


  Tip: If the application requires a stricter relationship between 
     artist and track, where NULL values are not permitted 
     in the trackartist column, simply add the appropriate 
     "NOT NULL" constraint to the schema.

  There are several other ways to add an equivalent foreign key declaration 
     to a CREATE TABLE statement. Refer to the 
     CREATE TABLE documentation for details.

  The following SQLite command-line session illustrates the effect of the
     foreign key constraint added to the track table:

sqlite&gt; SELECT * FROM artist;
artistid  artistname       
--------  -----------------
1         Dean Martin      
2         Frank Sinatra    

sqlite> SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
11       That's Amore       1  
12       Christmas Blues    1  
13       My Way             2  

sqlite&gt; -- This fails because the value inserted into the trackartist column (3)
sqlite&gt; -- does not correspond to row in the artist table.
sqlite&gt; INSERT INTO track VALUES(14, 'Mr. Bojangles', 3);
SQL error: foreign key constraint failed

sqlite&gt; -- This succeeds because a NULL is inserted into trackartist. A
sqlite&gt; -- corresponding row in the artist table is not required in this case.
sqlite&gt; INSERT INTO track VALUES(14, 'Mr. Bojangles', NULL);

sqlite&gt; -- Trying to modify the trackartist field of the record after it has 
sqlite&gt; -- been inserted does not work either, since the new value of trackartist (3)
sqlite&gt; -- Still does not correspond to any row in the artist table.
sqlite&gt; UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';
SQL error: foreign key constraint failed

sqlite&gt; -- Insert the required row into the artist table. It is then possible to
sqlite&gt; -- update the inserted row to set trackartist to 3 (since a corresponding
sqlite&gt; -- row in the artist table now exists).
sqlite&gt; INSERT INTO artist VALUES(3, 'Sammy Davis Jr.');
sqlite&gt; UPDATE track SET trackartist = 3 WHERE trackname = 'Mr. Bojangles';

sqlite&gt; -- Now that "Sammy Davis Jr." (artistid = 3) has been added to the database,
sqlite&gt; -- it is possible to INSERT new tracks using this artist without violating
sqlite&gt; -- the foreign key constraint:
sqlite&gt; INSERT INTO track VALUES(15, 'Boogie Woogie', 3);


  
    As you would expect, it is not possible to manipulate the database to a state
    that violates the foreign key constraint by deleting or updating rows in the 
    artist table either:
sqlite&gt; -- Attempting to delete the artist record for "Frank Sinatra" fails, since
sqlite&gt; -- the track table contains a row that refer to it.
sqlite&gt; DELETE FROM artist WHERE artistname = 'Frank Sinatra';
SQL error: foreign key constraint failed

sqlite&gt; -- Delete all the records from the track table that refer to the artist
sqlite&gt; -- "Frank Sinatra". Only then is it possible to delete the artist.
sqlite&gt; DELETE FROM track WHERE trackname = 'My Way';
sqlite&gt; DELETE FROM artist WHERE artistname = 'Frank Sinatra';

sqlite&gt; -- Try to update the artistid of a row in the artist table while there
sqlite&gt; -- exists records in the track table that refer to it. 
sqlite&gt; UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';
SQL error: foreign key constraint failed

sqlite&gt; -- Once all the records that refer to a row in the artist table have
sqlite&gt; -- been deleted, it is possible to modify the artistid of the row.
sqlite&gt; DELETE FROM track WHERE trackname IN('That''s Amore', 'Christmas Blues');
sqlite&gt; UPDATE artist SET artistid=4 WHERE artistname = 'Dean Martin';


  
    SQLite uses the following terminology:


  
    The parent table is the table that a foreign key constraint
        refers to. The parent table in the example in this section is the
        artist table. Some books and articles refer to this as the
        referenced table, which is arguably more correct, but tends
        to lead to confusion.

    The child table is the table that a foreign key constraint
        is applied to and the table that contains the REFERENCES clause.
        The example in this section uses the track table
        as the child table. Other books and articles refer to this as the
        referencing table.

    The parent key is the column or set of columns in the parent 
        table that the foreign key constraint refers to. This is normally, but
        not always, the primary key of the parent table.  The parent key must
        be a named column or columns in the parent table, not the rowid.

    The child key is the column or set of columns in the child 
        table that are constrained by the foreign key constraint and which
        hold the REFERENCES clause.
  

  
    The foreign key constraint is satisfied if for each row in the child table 
    either one or more of the child key columns are NULL, or there exists a 
    row in the parent table for which each parent key column contains a value
    equal to the value in its associated child key column.

  
    In the above paragraph, the term "equal" means equal when values are 
    compared using the rules specified 
    here. The following clarifications apply:
    
  
    When comparing text values, the collating sequence
        associated with the parent key column is always used.
    When comparing values, if the parent key column has an affinity,
        then that affinity is applied to the child key value before the
        comparison is performed.


c2: SQLite Foreign Key Support
c3: 2. Enabling Foreign Key Support
c5: foreignkeys.html#fk_enable
c4:
In order to use foreign key constraints in SQLite, the library must
    be compiled with neither SQLITE_OMIT_FOREIGN_KEY nor 
    SQLITE_OMIT_TRIGGER defined. If SQLITE_OMIT_TRIGGER is defined 
    but SQLITE_OMIT_FOREIGN_KEY is not, then SQLite behaves as it did prior 
    to version 3.6.19 (2009-10-14)
    - foreign key definitions are parsed and may be 
    queried using PRAGMA foreign_key_list, but foreign key constraints 
    are not enforced. The PRAGMA foreign_keys command is a no-op in this 
    configuration. If OMIT_FOREIGN_KEY is defined, then foreign key 
    definitions cannot even be parsed (attempting to specify a foreign
    key definition is a syntax error).

  
    Assuming the library is compiled with foreign key constraints enabled,
    it must still be enabled by the application at runtime, using the
    PRAGMA foreign_keys command. For example:

sqlite&gt; PRAGMA foreign_keys = ON;


  
    Foreign key constraints are disabled by default 
    (for backwards compatibility),
    so must be enabled separately for each database connection.
    (Note, however, that future releases of SQLite might change
    so that foreign key constraints enabled by default.  Careful
    developers will not
    make any assumptions about whether or not foreign keys are enabled by
    default but will instead enable or disable them as necessary.)
    The application can also use a PRAGMA foreign_keys statement to
    determine if foreign keys are currently enabled. The following 
    command-line session demonstrates this:
sqlite> PRAGMA foreign_keys;
0
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys;
1
sqlite> PRAGMA foreign_keys = OFF;
sqlite> PRAGMA foreign_keys;
0


  Tip: If the command "PRAGMA foreign_keys" returns no data instead of a
     single row containing "0" or "1", then the version of SQLite you are
     using does not support foreign keys (either because it is older than
     3.6.19 or because it was compiled with SQLITE_OMIT_FOREIGN_KEY or 
     SQLITE_OMIT_TRIGGER defined).

  
    It is not possible to enable or disable foreign key constraints
    in the middle of a multi-statement transaction (when SQLite
    is not in autocommit mode).  Attempting to do so does not return
    an error; it simply has no effect.


c2: SQLite Foreign Key Support
c3: 3. Required and Suggested Database Indexes
c5: foreignkeys.html#fk_indexes
c4:
Usually, the parent key of a foreign key constraint is the primary key of
    the parent table. If they are not the primary key, then the parent key
    columns must be collectively subject to a UNIQUE constraint or have
    a UNIQUE index. 
    If the parent key columns have a UNIQUE index,
    then that index must use the collation sequences that are specified
    in the CREATE TABLE statement for the parent table.
    For example,

CREATE TABLE parent(a PRIMARY KEY, b UNIQUE, c, d, e, f);
CREATE UNIQUE INDEX i1 ON parent(c, d);
CREATE INDEX i2 ON parent(e);
CREATE UNIQUE INDEX i3 ON parent(f COLLATE nocase);

CREATE TABLE child1(f, g REFERENCES parent(a));                        -- Ok
CREATE TABLE child2(h, i REFERENCES parent(b));                        -- Ok
CREATE TABLE child3(j, k, FOREIGN KEY(j, k) REFERENCES parent(c, d));  -- Ok
CREATE TABLE child4(l, m REFERENCES parent(e));                        -- Error!
CREATE TABLE child5(n, o REFERENCES parent(f));                        -- Error!
CREATE TABLE child6(p, q, FOREIGN KEY(p, q) REFERENCES parent(b, c));  -- Error!
CREATE TABLE child7(r REFERENCES parent(c));                           -- Error!


  
    The foreign key constraints created as part of tables child1, 
    child2 and child3 are all fine. The foreign key
    declared as part of table child4 is an error because even though
    the parent key column is indexed, the index is not UNIQUE.
    The foreign key for table child5
    is an error because even though the parent key column has a unique
    index, the index uses a different collating sequence.
    Tables child6 and child7 are incorrect because while
    both have UNIQUE indices on their parent keys, the keys are not an
    exact match to the columns of a single UNIQUE index.

  
    If the database schema contains foreign key errors that require looking
    at more than one table definition to identify, then those errors are not
    detected when the tables are created. Instead, such errors prevent
    the application from preparing SQL statements that modify the content
    of the child or parent tables in ways that use the foreign keys.
    Errors reported when content is changed are "DML errors" and errors
    reported when the schema is changed are "DDL errors".
    So, in other words, misconfigured foreign key constraints that require
    looking at both the child and parent are DML errors.
    The English language error message for foreign key DML errors is usually
    "foreign key mismatch" but can also be "no such table" if the parent
    table does not exist.
    Foreign key DML errors are reported if:

  
     The parent table does not exist, or
     The parent key columns named in the foreign key constraint do
         not exist, or
     The parent key columns named in the foreign key constraint are not
         the primary key of the parent table and are not subject to a unique
         constraint using collating sequence specified in the CREATE TABLE, or
     The child table references the primary key of the parent without
         specifying the primary key columns and the number of primary key
         columns in the parent do not match the number of child key columns.
  

  
    The last bullet above is illustrated by the following:

CREATE TABLE parent2(a, b, PRIMARY KEY(a,b));

CREATE TABLE child8(x, y, FOREIGN KEY(x,y) REFERENCES parent2);        -- Ok
CREATE TABLE child9(x REFERENCES parent2);                             -- Error!
CREATE TABLE child10(x,y,z, FOREIGN KEY(x,y,z) REFERENCES parent2);    -- Error!


  
    By contrast, if foreign key errors can be recognized simply by looking
    at the definition of the child table and without having to consult the
    parent table definition, then the 
    CREATE TABLE statement for the child table fails.  Because the error
    occurs during a schema change, this is a DDL error.
    Foreign key DDL errors are reported regardless of
    whether or not foreign key constraints are enabled when the
    table is created.

  
    Indices are not required for child key columns but they are almost
    always beneficial. Returning to
    the example in section 1, each time an application
    deletes a row from the artist table (the parent table), it
    performs the equivalent of the following SELECT statement to search
    for referencing rows in the track table (the child table).

SELECT rowid FROM track WHERE trackartist = ?


 
   where ? in the above is replaced with the value of the artistid
   column of the record being deleted from the artist table (recall
   that the trackartist column is the child key and the artistid
   column is the parent key). Or, more generally:

SELECT rowid FROM &lt;child-table&gt; WHERE &lt;child-key&gt; = :parent_key_value


 
   If this SELECT returns any rows at all, then SQLite concludes that
   deleting the row from the parent table would violate the foreign key
   constraint and returns an error.
   Similar queries may be run if the content of the parent key
   is modified or a new row is inserted into the parent table.
   If these queries cannot use an index, they are forced to do a
   linear scan of the entire child table.  In a non-trivial database, this may
   be prohibitively expensive.

 
   So, in most real systems, an index should be created on the child key columns
   of each foreign key constraint. The child key index does not have
   to be (and usually will not be) a UNIQUE index.
   Returning again to the example in section 1, the
   complete database schema for efficient implementation of the foreign key 
   constraint might be:

CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER,
  trackname   TEXT, 
  trackartist INTEGER REFERENCES artist
);
CREATE INDEX trackindex ON track(trackartist);


  
    The block above uses a shorthand form to create the foreign key constraint.
    Attaching a "REFERENCES &lt;parent-table&gt;" clause to a column
    definition creates a foreign key constraint that maps the column to the
    primary key of &lt;parent-table&gt;. Refer to the CREATE TABLE 
    documentation for further details.


c2: SQLite Foreign Key Support
c3: 4.1. Composite Foreign Key Constraints
c5: foreignkeys.html#fk_composite
c4:
A composite foreign key constraint is one where the child and parent keys
    are both composite keys. For example, consider
    the following database schema:

CREATE TABLE album(
  albumartist TEXT,
  albumname TEXT,
  albumcover BINARY,
  PRIMARY KEY(albumartist, albumname)
);

CREATE TABLE song(
  songid     INTEGER,
  songartist TEXT,
  songalbum TEXT,
  songname   TEXT,
  FOREIGN KEY(songartist, songalbum) REFERENCES album(albumartist, albumname)
);


  
    In this system, each entry in the song table is required to map to an entry
    in the album table with the same combination of artist and album.

  
    Parent and child keys must have the same cardinality.
    In SQLite, if any of the child key columns (in this case songartist 
    and songalbum) are NULL, then there is no requirement for a corresponding
    row in the parent table.


c2: SQLite Foreign Key Support
c3: 4.2. Deferred Foreign Key Constraints
c5: foreignkeys.html#fk_deferred
c4:
Each foreign key constraint in SQLite is classified as either immediate
     or deferred. Foreign key constraints are immediate by default.
     All the foreign key examples presented
     so far have been of immediate foreign key constraints.

  
    If a statement modifies the contents of the database so that an immediate 
    foreign key constraint is in violation at the conclusion the statement, 
    an exception is thrown and 
    the effects of the statement are reverted. By contrast, if
    a statement modifies the contents of the database such that a deferred 
    foreign key constraint is violated, the violation is not reported
    immediately. Deferred foreign key constraints are not checked
    until the transaction tries to COMMIT.
    For as long as the user has 
    an open transaction, the database is allowed to exist in a state that 
    violates any number of deferred foreign key constraints. However, 
    COMMIT will fail as long as foreign key constraints remain in
    violation.

  
    If the current statement is not inside an explicit transaction (a 
    BEGIN/COMMIT/ROLLBACK block), then an implicit
    transaction is committed
    as soon as the statement has finished executing. In this case deferred
    constraints behave the same as immediate constraints.

  
    To mark a foreign key constraint as deferred, its declaration must
    include the following clause:

DEFERRABLE INITIALLY DEFERRED                -- A deferred foreign key constraint


  
    The full syntax for specifying foreign key constraints is available as part
    of the CREATE TABLE documentation. Replacing the phrase above
    with any of the following 
    creates an immediate foreign key constraint.

NOT DEFERRABLE INITIALLY DEFERRED            -- An immediate foreign key constraint
NOT DEFERRABLE INITIALLY IMMEDIATE           -- An immediate foreign key constraint
NOT DEFERRABLE                               -- An immediate foreign key constraint
DEFERRABLE INITIALLY IMMEDIATE               -- An immediate foreign key constraint
DEFERRABLE                                   -- An immediate foreign key constraint


  The defer_foreign_keys pragma can be used to temporarily change all foreign
    key constraints to deferred regardless of how they are declared.

  
    The following example illustrates the effect of using a deferred foreign
    key constraint.

-- Database schema. Both tables are initially empty. 
CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER,
  trackname   TEXT, 
  trackartist INTEGER REFERENCES artist(artistid) DEFERRABLE INITIALLY DEFERRED
);

sqlite3&gt; -- If the foreign key constraint were immediate, this INSERT would
sqlite3&gt; -- cause an error (since as there is no row in table artist with
sqlite3&gt; -- artistid=5). But as the constraint is deferred and there is an
sqlite3&gt; -- open transaction, no error occurs.
sqlite3&gt; BEGIN;
sqlite3&gt;   INSERT INTO track VALUES(1, 'White Christmas', 5);

sqlite3&gt; -- The following COMMIT fails, as the database is in a state that
sqlite3&gt; -- does not satisfy the deferred foreign key constraint. The
sqlite3&gt; -- transaction remains open.
sqlite3&gt; COMMIT;
SQL error: foreign key constraint failed

sqlite3&gt; -- After inserting a row into the artist table with artistid=5, the
sqlite3&gt; -- deferred foreign key constraint is satisfied. It is then possible
sqlite3&gt; -- to commit the transaction without error.
sqlite3&gt;   INSERT INTO artist VALUES(5, 'Bing Crosby');
sqlite3&gt; COMMIT;

  
    A nested savepoint transaction may be RELEASEd while the
    database is in a state that does not satisfy a deferred foreign key 
    constraint. A transaction savepoint (a non-nested savepoint that was
    opened while there was not currently an open transaction), on the 
    other hand, is subject to the same restrictions as a COMMIT - attempting 
    to RELEASE it while the database is in such a state will fail.

  
    If a COMMIT statement (or the RELEASE of a transaction SAVEPOINT) fails
    because the database is currently in a state that violates a deferred
    foreign key constraint and there are currently
    nested savepoints, the nested savepoints remain open.


c2: SQLite Foreign Key Support
c3: 4.3. ON DELETE and ON UPDATE Actions
c5: foreignkeys.html#fk_actions
c4:
Foreign key ON DELETE and ON UPDATE clauses are used to configure actions
    that take place when deleting rows from the parent table (ON DELETE), or 
    modifying the parent key values of existing rows (ON UPDATE). A single
    foreign key constraint may have different actions configured for ON DELETE
    and ON UPDATE. Foreign key actions are similar to triggers in many ways.

  
    The ON DELETE and ON UPDATE action associated with each foreign key in an
    SQLite database is one of "NO ACTION", "RESTRICT", "SET NULL",
    "SET DEFAULT" or "CASCADE". If an action is not explicitly specified, it 
    defaults to "NO ACTION".

  
     NO ACTION: Configuring "NO ACTION" means just that: when a
     parent key is modified or deleted from the database, no special action is
     taken.

     RESTRICT: The "RESTRICT" action means that the application
      is prohibited from deleting (for ON DELETE RESTRICT) or modifying
      (for ON UPDATE RESTRICT) a parent key when there exists one or more child
      keys mapped to it. The difference between the effect of a RESTRICT
      action and normal foreign key constraint enforcement is that the
      RESTRICT action processing happens as soon as the field is updated -
      not at the end of the current statement as it would with an immediate
      constraint, or at the end of the current transaction as it would with
      a deferred constraint.
      Even if the foreign key constraint it is 
      attached to is deferred, configuring a RESTRICT action causes SQLite to 
      return an error immediately if a parent key with dependent child keys is 
      deleted or modified.

     SET NULL: If the configured action is "SET NULL", then when
      a parent key is deleted (for ON DELETE SET NULL) or modified (for ON 
      UPDATE SET NULL), the child key columns of all rows in the child table
      that mapped to the parent key are set to contain SQL NULL values.

     SET DEFAULT: The "SET DEFAULT" actions are similar to
      "SET NULL",
      except that each of the child key columns is set to contain the column's 
      default value instead of NULL. Refer to the CREATE TABLE 
      documentation for details on how default values are assigned to table
      columns.

     CASCADE: A "CASCADE" action propagates the delete or update
      operation on the parent key to each dependent child key. For an "ON 
      DELETE CASCADE" action, this means that each row in the child table that
      was associated with the deleted parent row is also deleted. For an "ON
      UPDATE CASCADE" action, it means that the values stored in each dependent
      child key are modified to match the new parent key values.
  

  
    For example, adding an "ON UPDATE CASCADE" clause to the foreign key as
    shown below enhances the example schema from section 1 to allow the user
    to update the artistid (the parent key of the foreign key constraint) 
    column without breaking referential integrity:
-- Database schema
CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER,
  trackname   TEXT, 
  trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE
);

sqlite&gt; SELECT * FROM artist;
artistid  artistname       
--------  -----------------
1         Dean Martin      
2         Frank Sinatra    

sqlite&gt; SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
11       That's Amore       1
12       Christmas Blues    1
13       My Way             2  

sqlite&gt; -- Update the artistid column of the artist record for "Dean Martin".
sqlite&gt; -- Normally, this would raise a constraint, as it would orphan the two
sqlite&gt; -- dependent records in the track table. However, the ON UPDATE CASCADE clause
sqlite&gt; -- attached to the foreign key definition causes the update to "cascade"
sqlite&gt; -- to the child table, preventing the foreign key constraint violation.
sqlite&gt; UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin';

sqlite&gt; SELECT * FROM artist;
artistid  artistname       
--------  -----------------
2         Frank Sinatra    
100       Dean Martin      

sqlite&gt; SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
11       That's Amore       100
12       Christmas Blues    100  
13       My Way             2  


  
    Configuring an ON UPDATE or ON DELETE action does not mean that the foreign
    key constraint does not need to be satisfied. For example, if an
    "ON DELETE SET DEFAULT" action is configured,
    but there is no row in the parent table 
    that corresponds to the default values of the child key columns, deleting
    a parent key while dependent child keys exist still causes a foreign key
    violation. For example:

-- Database schema
CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER,
  trackname   TEXT, 
  trackartist INTEGER DEFAULT 0 REFERENCES artist(artistid) ON DELETE SET DEFAULT
);

sqlite&gt; SELECT * FROM artist;
artistid  artistname       
--------  -----------------
3         Sammy Davis Jr.

sqlite&gt; SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
14       Mr. Bojangles      3

sqlite&gt; -- Deleting the row from the parent table causes the child key
sqlite&gt; -- value of the dependent row to be set to integer value 0. However, this
sqlite&gt; -- value does not correspond to any row in the parent table. Therefore
sqlite&gt; -- the foreign key constraint is violated and an is exception thrown.
sqlite&gt; DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';
SQL error: foreign key constraint failed

sqlite&gt; -- This time, the value 0 does correspond to a parent table row. And
sqlite&gt; -- so the DELETE statement does not violate the foreign key constraint
sqlite&gt; -- and no exception is thrown.
sqlite&gt; INSERT INTO artist VALUES(0, 'Unknown Artist');
sqlite&gt; DELETE FROM artist WHERE artistname = 'Sammy Davis Jr.';

sqlite&gt; SELECT * FROM artist;
artistid  artistname       
--------  -----------------
0         Unknown Artist

sqlite&gt; SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
14       Mr. Bojangles      0


  
    Those familiar with SQLite triggers
    will have noticed that the 
    "ON DELETE SET DEFAULT" action demonstrated in the example above is
    similar in effect to the following AFTER DELETE trigger:
CREATE TRIGGER on_delete_set_default AFTER DELETE ON artist BEGIN
  UPDATE child SET trackartist = 0 WHERE trackartist = old.artistid;
END;


  
    Whenever a row in the parent table of a foreign key constraint is deleted,
    or when the values stored in the parent key column or columns are modified, 
    the logical sequence of events is:

  
    Execute applicable BEFORE trigger programs,
    Check local (non foreign key) constraints,
    Update or delete the row in the parent table,
    Perform any required foreign key actions,
    Execute applicable AFTER trigger programs.
  

  
    There is one important difference between ON UPDATE foreign key actions and
    SQL triggers. An ON UPDATE action is only taken if the values of the
    parent key are modified so that the new parent key values are 
    not equal to the old. For example:

-- Database schema
CREATE TABLE parent(x PRIMARY KEY);
CREATE TABLE child(y REFERENCES parent ON UPDATE SET NULL);

sqlite&gt; SELECT * FROM parent;
x
----
key

sqlite&gt; SELECT * FROM child;
y
----
key

sqlite&gt; -- Since the following UPDATE statement does not actually modify
sqlite&gt; -- the parent key value, the ON UPDATE action is not performed and
sqlite&gt; -- the child key value is not set to NULL.
sqlite&gt; UPDATE parent SET x = 'key';
sqlite&gt; SELECT IFNULL(y, 'null') FROM child;
y
----
key

sqlite&gt; -- This time, since the UPDATE statement does modify the parent key
sqlite&gt; -- value, the ON UPDATE action is performed and the child key is set
sqlite&gt; -- to NULL.
sqlite&gt; UPDATE parent SET x = 'key2';
sqlite&gt; SELECT IFNULL(y, 'null') FROM child;
y
----
null


c2: SQLite Foreign Key Support
c3: 5. CREATE, ALTER and DROP TABLE commands
c5: foreignkeys.html#fk_schemacommands
c4:
This section describes the way the CREATE TABLE, ALTER TABLE,
    and DROP TABLE commands
    interact with SQLite's foreign keys.

  
    A CREATE TABLE command operates the same whether or not
    foreign key constraints are enabled.  The parent key definitions of 
    foreign key constraints are not checked when a table is created. There is
    nothing stopping the user from creating a foreign key definition that
    refers to a parent table that does not exist, or to parent key columns that
    do not exist or are not collectively bound by a PRIMARY KEY or UNIQUE
    constraint.

  
    The ALTER TABLE command works differently in two respects when foreign
    key constraints are enabled:

  
     
         It is not possible to use the "ALTER TABLE ... ADD COLUMN" syntax
         to add a column that includes a REFERENCES clause, unless the default
         value of the new column is NULL. Attempting to do so returns an
         error.

     
         If an "ALTER TABLE ... RENAME TO" command is used to rename a table
         that is the parent table of one or more foreign key constraints, the
         definitions of the foreign key constraints are modified to refer to
         the parent table by its new name. The text of the child CREATE
         TABLE statement or statements stored in the sqlite_schema table are 
         modified to reflect the new parent table name.
  

  
    If foreign key constraints are enabled when it is prepared, the 
    DROP TABLE command performs an implicit DELETE to remove all
    rows from the table before dropping it. The implicit DELETE does not cause
    any SQL triggers to fire, but may invoke foreign key actions or constraint
    violations. If an immediate foreign key constraint is violated, the DROP
    TABLE statement fails and the table is not dropped. If a deferred foreign
    key constraint is violated, then an error is reported when the user attempts
    to commit the transaction if the foreign key constraint violations still
    exist at that point. Any "foreign key mismatch" errors encountered as part 
    of an implicit DELETE are ignored.

  
    The intent of these enhancements to the ALTER TABLE and DROP TABLE
    commands is to ensure that they cannot be used to create a database that
    contains foreign key violations, at least while foreign key constraints are
    enabled. There is one exception to this rule though. If a parent key is
    not subject to a PRIMARY KEY or UNIQUE constraint created as part of the
    parent table definition, but is subject to a UNIQUE constraint by virtue
    of an index created using the CREATE INDEX command, then the child 
    table may be populated without causing a "foreign key mismatch" error. If
    the UNIQUE index is dropped from the database schema, then the parent table
    itself is dropped, no error will be reported. However the database may be
    left in a state where the child table of the foreign key constraint contains
    rows that do not refer to any parent table row. This case can be avoided
    if all parent keys in the database schema are constrained by PRIMARY KEY
    or UNIQUE constraints added as part of the parent table definition, not
    by external UNIQUE indexes.

  
    The properties of the DROP TABLE and ALTER TABLE commands described
    above only apply if foreign keys are enabled. If the user considers them
    undesirable, then the workaround is to use PRAGMA foreign_keys to 
    disable foreign key constraints before executing the DROP or ALTER TABLE 
    command. Of course, while foreign key constraints are disabled, there is nothing
    to stop the user from violating foreign key constraints and thus creating
    an internally inconsistent database.


c2: SQLite Foreign Key Support
c3: 6. Limits and Unsupported Features
c5: foreignkeys.html#fk_unsupported
c4:
This section lists a few limitations and omitted features that are not
    mentioned elsewhere.

  
     
      No support for the MATCH clause. According to SQL92, a MATCH clause
         may be attached to a composite foreign key definition to modify the way
         NULL values that occur in child keys are handled. If "MATCH SIMPLE" is
         specified, then a child key is not required to correspond to any row
         of the parent table if one or more of the child key values are NULL.
         If "MATCH FULL" is specified, then if any of the child key values is
         NULL, no corresponding row in the parent table is required, but all
         child key values must be NULL. Finally, if the foreign key constraint
         is declared as "MATCH PARTIAL" and one of the child key values is NULL,
         there must exist at least one row in the parent table for which the
         non-NULL child key values match the parent key values.

       
         SQLite parses MATCH clauses (i.e. does not report a syntax error
         if you specify one), but does not enforce them. All foreign key 
         constraints in SQLite are handled as if MATCH SIMPLE were specified.
     
      No support for switching constraints between deferred and immediate 
         mode. Many systems allow the user to toggle individual foreign key
         constraints between deferred and immediate 
         mode at runtime (for example using the Oracle "SET CONSTRAINT" command).
         SQLite does not support this. In SQLite, a foreign key constraint is
         permanently marked as deferred or immediate when it is created.

    
      Recursion limit on foreign key actions. The 
         SQLITE_MAX_TRIGGER_DEPTH and SQLITE_LIMIT_TRIGGER_DEPTH
         settings determine the maximum allowable depth of trigger
         program recursion. For the purposes of these limits,
         foreign key actions are considered trigger programs. The
         PRAGMA recursive_triggers setting does not affect the operation 
         of foreign key actions. It is not possible to disable recursive foreign 
         key actions.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 1. Overview
c5: geopoly.html#overview
c4:
The Geopoly module is an alternative interface to the R-Tree extension that uses
the GeoJSON notation
(RFC-7946) to describe two-dimensional
polygons.  Geopoly includes functions for detecting when one polygon is
contained within or overlaps with another, for computing the
area enclosed by a polygon, for doing linear transformations of polygons,
for rendering polygons as
SVG, and other
similar operations.


The source code for Geopoly is included in the amalgamation but is not
included in the library unless the -DSQLITE_ENABLE_GEOPOLY compile-time option
is used.


Geopoly operates on "simple" polygons - that is, polygons for which
the boundary does not intersect itself.  Geopoly thus extends the capabilities
of the R-Tree extension which can only deal with rectangular areas.
On the other hand, the R-Tree extension is
able to handle between 1 and 5 coordinate dimensions, whereas Geopoly is restricted
to 2-dimensional shapes only.


Each polygon in the Geopoly module can be associated with an arbitrary
number of auxiliary data fields.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 1.1. GeoJSON
c5: geopoly.html#geojson
c4:
The GeoJSON standard is syntax for
exchanging geospatial information using JSON.  GeoJSON is a rich standard
that can describe nearly any kind of geospatial content.

The Geopoly module only understands
a small subset of GeoJSON, but a critical subset.  
In particular, GeoJSON understands
the JSON array of vertexes that describes a simple polygon.

A polygon is defined by its vertexes.
Each vertex is a JSON array of two numeric values which are the
X and Y coordinates of the vertex.
A polygon is a JSON array of at least four of these vertexes, 
and hence is an array of arrays.
The first and last vertex in the array must be the same.
The polygon follows the right-hand rule:  When tracing a line from
one vertex to the next, the area to the right of the line is outside
of the polygon and the area to the left is inside the polygon.
In other words, the net rotation of the vertexes is counter-clockwise.


For example, the following JSON describes an isosceles triangle, sitting
on the X axis and with an area of 0.5:

&#91;&#91;0,0],&#91;1,0],&#91;0.5,1],&#91;0,0]]



A triangle has three vertexes, but the GeoJSON description of the triangle
has 4 vertexes because the first and last vertex are duplicates.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 1.2. Binary storage format
c5: geopoly.html#binary_storage_format
c4:
Internally, Geopoly stores polygons in a binary format - an SQL BLOB.
Details of the binary format are given below.
All of the Geopoly interfaces are able to accept polygons in either the
GeoJSON format or in the binary format.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 2. Using The Geopoly Extension
c5: geopoly.html#using_the_geopoly_extension
c4:
A geopoly table is created as follows:

CREATE VIRTUAL TABLE newtab USING geopoly(a,b,c);



The statement above creates a new geopoly table named "newtab".
Every geopoly table contains a built-in integer "rowid" column
and a "_shape" column that contains
the polygon associated with that row of the table.
The example above also defines three auxiliary data columns 
named "a", "b", and "c" that can store whatever additional
information the application needs to associate
with each polygon.  If there is no need to store auxiliary
information, the list of auxiliary columns can be omitted.


Store new polygons in the table using ordinary INSERT statements:

INSERT INTO newtab(_shape) VALUES('&#91;&#91;0,0],&#91;1,0],&#91;0.5,1],&#91;0,0]]');



UPDATE and DELETE statements work similarly.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 2.1. Queries
c5: geopoly.html#queries
c4:
To query the geopoly table using an indexed geospatial search, 
use one of the functions geopoly_overlap()
or geopoly_within() as a boolean function in the WHERE clause,
with the "_shape" column as the first argument to the function.
For example:

SELECT * FROM newtab WHERE geopoly_overlap(_shape, $query_polygon);



The previous example will return every row for which the _shape
overlaps the polygon in the $query_polygon parameter.  The
geopoly_within() function works similarly, but only returns rows for
which the _shape is completely contained within $query_polygon.


Queries (and also DELETE and UPDATE statements) in which the WHERE
clause contains a bare geopoly_overlap() or geopoly_within() function
make use of the underlying R*Tree data structures for a fast lookup that
only has to examine a subset of the rows in the table.  The number of
rows examines depends, of course, on the size of the $query_polygon.
Large $query_polygons will normally need to look at more rows than small
ones.


Queries against the rowid of a geopoly table are also very quick, even
for tables with a vast number of rows.
However, none of the auxiliary data columns are indexes, and so queries
against the auxiliary data columns will involve a full table scan.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3. Special Functions
c5: geopoly.html#special_functions
c4:
The geopoly module defines several new SQL functions that are useful for
dealing with polygons.  All polygon arguments to these functions can be
either the GeoJSON format or the internal binary format.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.1. The geopoly_overlap(P1,P2) Function
c5: geopoly.html#the_geopoly_overlap_p1_p2_function
c4:
If P1 and P2 are both polygons, then the geopoly_overlap(P1,P2) function returns
a non-zero integer if there is any overlap between P1 and P2, or it returns
zero if P1 and P2 completely disjoint.
If either P1 or P2 is not a polygon, this routine returns NULL.


The geopoly_overlap(P1,P2) function is special in that the geopoly virtual
table knows how to use R*Tree indexes to optimize queries in which the 
WHERE clause uses geopoly_overlap() as a boolean function.  Only the
geopoly_overlap(P1,P2) and geopoly_within(P1,P2) functions have this
capability.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.2. The geopoly_within(P1,P2) Function
c5: geopoly.html#the_geopoly_within_p1_p2_function
c4:
If P1 and P2 are both polygons, then the geopoly_within(P1,P2) function returns
a non-zero integer if P1 is completely contained within P2, or it returns zero
if any part of P1 is outside of P2.  If P1 and P2 are the same polygon, this routine
returns non-zero.
If either P1 or P2 is not a polygon, this routine returns NULL.


The geopoly_within(P1,P2) function is special in that the geopoly virtual
table knows how to use R*Tree indexes to optimize queries in which the 
WHERE clause uses geopoly_within() as a boolean function.  Only the
geopoly_within(P1,P2) and geopoly_overlap(P1,P2) functions have this
capability.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.3. The geopoly_area(P) Function
c5: geopoly.html#the_geopoly_area_p_function
c4:
If P is a polygon, then geopoly_area(P) returns the area enclosed by
that polygon.  If P is not a polygon, geopoly_area(P) returns NULL.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.4. The geopoly_blob(P) Function
c5: geopoly.html#the_geopoly_blob_p_function
c4:
If P is a polygon, then geopoly_blob(P) returns the binary encoding
of that polygon as a BLOB.
If P is not a polygon, geopoly_blob(P) returns NULL.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.5. The geopoly_json(P) Function
c5: geopoly.html#the_geopoly_json_p_function
c4:
If P is a polygon, then geopoly_json(P) returns the GeoJSON representation
of that polygon as a TEXT string.
If P is not a polygon, geopoly_json(P) returns NULL.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.6. The geopoly_svg(P,...) Function
c5: geopoly.html#the_geopoly_svg_p_function
c4:
If P is a polygon, then geopoly_svg(P,...) returns a text string which is a
Scalable Vector Graphics (SVG)
representation of that polygon.  If there is more one argument, then second
and subsequent arguments are added as attributes to each SVG glyph.  For example:

SELECT geopoly_svg($polygon,'class="poly"','style="fill:blue;"');



If P is not a polygon, geopoly_svg(P,...) returns NULL.


Note that geopoly uses a traditional right-handed cartesian coordinate system
with the origin at the lower left, whereas SVG uses a left-handed coordinate
system with the origin at the upper left.  The geopoly_svg() routine makes no
attempt to transform the coordinate system, so the displayed images are shown
in mirror image and rotated.  If that is undesirable, the geopoly_xform() routine
can be used to transform the output from cartesian to SVG coordinates prior to
passing the polygons into geopoly_svg().


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.7. The geopoly_bbox(P) and geopoly_group_bbox(P) Functions
c5: geopoly.html#the_geopoly_bbox_p_and_geopoly_group_bbox_p_functions
c4:
If P is a polygon, then geopoly_bbox(P) returns a new polygon that is
the smallest (axis-aligned) rectangle completely enclosing P.
If P is not a polygon, geopoly_bbox(P) returns NULL.


The geopoly_group_bbox(P) function is an aggregate version of geopoly_bbox(P).
The geopoly_group_bbox(P) function returns the smallest rectangle that will
enclose all P values seen during aggregation.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.8. The geopoly_contains_point(P,X,Y) Function
c5: geopoly.html#the_geopoly_contains_point_p_x_y_function
c4:
If P is a polygon, then geopoly_contains_point(P,X,Y) returns a 
non-zero integer if and only
if the coordinate X,Y is inside or on the boundary of the polygon P.
If P is not a polygon, geopoly_contains_point(P,X,Y) returns NULL.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.9. The geopoly_xform(P,A,B,C,D,E,F) Function
c5: geopoly.html#the_geopoly_xform_p_a_b_c_d_e_f_function
c4:
The geopoly_xform(P,A,B,C,D,E,F) function returns a new polygon that is an
affine transformation of the polygon P and where the transformation
is defined by values A,B,C,D,E,F. If P is not a valid polygon, this
routine returns NULL.


The transformation converts each vertex of the polygon according to the
following formula:

x1 = A*x0 + B*y0 + E
y1 = C*x0 + D*y0 + F



So, for example, to move a polygon by some amount DX, DY without changing
its shape, use:

geopoly_xform($polygon, 1, 0, 0, 1, $DX, $DY)



To rotate a polygon by R radians around the point 0, 0:

geopoly_xform($polygon, cos($R), sin($R), -sin($R), cos($R), 0, 0)



Note that a transformation that flips the polygon might cause the
order of vertexes to be reversed.  In other words, the transformation
might cause the vertexes to circulate in clockwise order instead of
counter-clockwise.  This can be corrected by sending the result
through the geopoly_ccw() function after transformation.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.10. The geopoly_regular(X,Y,R,N) Function
c5: geopoly.html#the_geopoly_regular_x_y_r_n_function
c4:
The geopoly_regular(X,Y,R,N) function returns a convex, simple, regular,
equilateral, equiangular polygon with N sides, centered at X,Y, and with
a circumradius of R.  Or, if R is negative or if N is less than 3, the
function returns NULL.  The N value is capped at 1000 so that the routine
will never render a polygon with more than 1000 sides even if the N value
is larger than 1000.


As an example, the following graphic:





Was generated by this script:

SELECT '&lt;svg width="600" height="300">';
WITH t1(x,y,n,color) AS (VALUES
   (100,100,3,'red'),
   (200,100,4,'orange'),
   (300,100,5,'green'),
   (400,100,6,'blue'),
   (500,100,7,'purple'),
   (100,200,8,'red'),
   (200,200,10,'orange'),
   (300,200,12,'green'),
   (400,200,16,'blue'),
   (500,200,20,'purple')
)
SELECT
   geopoly_svg(geopoly_regular(x,y,40,n),
        printf('style="fill:none;stroke:%s;stroke-width:2"',color))
   || printf(' &lt;text x="%d" y="%d" alignment-baseline="central" text-anchor="middle">%d&lt;/text>',x,y+6,n)
  FROM t1;
SELECT '&lt;/svg>';


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 3.11. The geopoly_ccw(J) Function
c5: geopoly.html#the_geopoly_ccw_j_function
c4:
The geopoly_ccw(J) function returns the polygon J with counter-clockwise (CCW) rotation.


RFC-7946 requires that polygons use CCW rotation.
But the spec also observes that many legacy GeoJSON files do not following the spec and
contain polygons with clockwise (CW) rotation.  The geopoly_ccw() function is useful for
applications that are reading legacy GeoJSON scripts.  If the input to geopoly_ccw() is
a correctly-formatted polygon, then no changes are made.  However, if the circulation of
the input polygon is backwards, then geopoly_ccw() reverses the circulation order so that
it conforms to the spec and so that it will work correctly with the Geopoly module.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 4. Implementation Details
c5: geopoly.html#implementation_details
c4:
The geopoly module is an extension to the R-Tree extension.  Geopoly
uses the same underlying logic and shadow tables as the R-Tree extension.
Geopoly merely presents a different interface, and provides some extra logic
to compute polygon decoding, overlap, and containment.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 4.1. Binary Encoding of Polygons
c5: geopoly.html#binary_encoding_of_polygons
c4:
Geopoly stores all polygons internally using a binary format.  A binary
polygon consists of a 4-byte header following by an array of coordinate
pairs in which each dimension of each coordinate is a 32-bit floating point
number.


The first byte of the header is a flag byte.  The least significant bit
of the flag byte determines whether the coordinate pairs that follow the
header are stored big-endian or little-endian.  A value of 0 for the least
significant bit means big-endian and a value of 1 means little endian.
Other bits of the first byte in the header are reserved for future expansion.


The next three bytes in the header record the number of vertexes in the polygon
as a big-endian integer.  Thus there is an upper bound of about 16 million
vertexes per polygon.


Following the header is the array of coordinate pairs.  Each coordinate is
a 32-bit floating point number.  The use of 32-bit floating point values for
coordinates means that any point on the earth's surface can be mapped with
a resolution of approximately 2.5 meters.  Higher resolutions are of course
possible if the map is restricted to a single continent or country.
Note that the resolution of coordinates in the geopoly module is similar
in magnitude to daily movement of points on the earth's surface due to
tidal forces.


The list of coordinates in the binary format contains no redundancy.  
The last coordinate is not a repeat of the first as it is with GeoJSON.  
Hence, there is always one fewer coordinate pair in the binary representation of
a polygon compared to the GeoJSON representation.


c2: The Geopoly Interface To The SQLite R*Tree Module
c3: 4.2. Shadow Tables
c5: geopoly.html#shadow_tables
c4:
The geopoly module is built on top of the R-Tree extension and uses the
same underlying shadow tables and algorithms.  For indexing purposes, each
polygon is represented in the shadow tables as a rectangular bounding box.
The underlying R-Tree implementation uses bounding boxes to limit the search
space.  Then the geoploy_overlap() and/or geopoly_within() routines further
refine the search to the exact answer.


c2: Application-Defined SQL Functions
c3: 1. Executive Summary
c5: appfunc.html#executive_summary
c4:
Applications that use SQLite can define custom SQL functions that call
back into application code to compute their results.  The custom SQL
function implementations can be embedded in the application code itself,
or can be loadable extensions.

Application-defined or custom SQL functions are created using the
sqlite3_create_function() family of interfaces.
Custom SQL functions can be scalar functions, aggregate functions,
or window functions.
Custom SQL functions can have any number of arguments from 0 up to
SQLITE_MAX_FUNCTION_ARG.
The sqlite3_create_function() interface specifies callbacks that are
invoked to carry out the processing for the new SQL function.

SQLite also supports custom table-valued functions, but they are
implemented by a different mechanism that is not covered in this document.


c2: Application-Defined SQL Functions
c3: 2. Defining New SQL Functions
c5: appfunc.html#defining_new_sql_functions
c4:
The sqlite3_create_function() family of interfaces is used to create
new custom SQL functions.  Each member of this family is a wrapper around
a common core.  All family members accomplish the same thing; they merely
have different calling signatures.


sqlite3_create_function() &rarr;
The original version of sqlite3_create_function() allows the application
to create a single new SQL function that can be either a scalar or an
aggregate.  The name of the function is specified using UTF8.

sqlite3_create_function16() &rarr;
This variant works exactly like the sqlite3_create_function() original
except that the name of the function itself is specified as a UTF16
string rather than as a UTF8 string.

sqlite3_create_function_v2() &rarr;
This variant works like the original sqlite3_create_function() except
that it includes an additional parameter that is a pointer to a
destructor for the sqlite3_user_data() pointer that is passed in
as the 5th argument to all of the sqlite3_create_function() variants.
That destructor function (if it is non-NULL) is called when the
custom function is deleted - usually when the database connection is
closing.

sqlite3_create_window_function() &rarr;
This variant works like the original sqlite3_create_function() except
that it accepts a different set of callback pointers - the callback
pointers used by window function definitions.


c2: Application-Defined SQL Functions
c3: 2.1. Common Parameters
c5: appfunc.html#common_parameters
c4:
Many of the parameters passed to the sqlite3_create_function()
family of interfaces are common across the entire family.


db &rarr;
The 1st parameter is always a pointer to the database connection
on which the custom SQL function will work.  Custom SQL functions are
created separately for each database connection.  There is no short-hand
mechanism for creating SQL functions that work across all database
connections.

zFunctionName &rarr;
The 2nd parameter is the name of the SQL function that is being
created.  The name is usually in UTF8, except that the name should
be in UTF16 in the native byte order for sqlite3_create_function16().

The maximum length of a SQL function name is 255 bytes of UTF8.
Any attempt to create a function with a longer name will result in
an SQLITE_MISUSE error.

The SQL function creation interfaces may be called multiple
times with the same function name.
If two calls have the same function number but a different number of
arguments, for example, then two variants of the SQL function will
be registered, each taking a different number of arguments.

nArg &rarr;
The 3rd parameter is always the number of arguments that the function
accepts.  The value must be an integer between -1 and 
SQLITE_MAX_FUNCTION_ARG (default value: 127).  A value of -1 means
that the SQL function is a variadic function that can take any number
of arguments between 0 and SQLITE_MAX_FUNCTION_ARG.

eTextRep &rarr;
The 4th parameter is a 32-bit integer flag whose bits convey various
properties about the new function.  The original purpose of this
parameter was to specify the preferred text encoding for the function,
using one of the following constants:

 SQLITE_UTF8
 SQLITE_UTF16BE
 SQLITE_UTF16LE

All custom SQL functions will accept text in any encoding.  Encoding
conversions will happen automatically.  The preferred encoding merely
specifies the encoding for which the function implementation is optimized.
It is possible to specify multiple functions with the same name and the
same number of arguments, but different preferred encodings and different
callbacks used to implement the function, and SQLite will chose the
set of callbacks for which the input encodings most closely match the
preferred encoding.

The 4th parameter as more recently be extended with additional flag bits
to convey additional information about the function.  The additional
bits include:

 SQLITE_DETERMINISTIC
 SQLITE_DIRECTONLY
 SQLITE_INNOCUOUS
 SQLITE_SUBTYPE


Additional bits may be added in future versions of SQLite.

pApp &rarr;
The 5th parameter is an arbitrary pointer that is passed through
into the callback routines.  SQLite itself does nothing with this
pointer, except to make it available to the callbacks, and to pass
it into the destructor when the function is unregistered.


c2: Application-Defined SQL Functions
c3: 2.2. Multiple Calls To sqlite3_create_function() For The Same Function
c5: appfunc.html#multiple_calls_to_sqlite3_create_function_for_the_same_function
c4:
It is common for an application to invoke sqlite3_create_function() multiple
times for the same SQL function.  For example, if an SQL function can take
either 2 or 3 arguments, then sqlite3_create_function() would be invoked
once for the 2-argument version and a second time for the 3-argument version.
The underlying implementation (the callbacks) can be different for both
variants.


An application can also register multiple SQL functions with the same name
and same number of arguments, but a different preferred text encoding.
In that case, SQLite will invoke the function using the callbacks for
the version whose preferred text encoding most closely matches the database
text encoding.  In this way, multiple implementations of the same function
can be provided that are optimized for UTF8 or UTF16.


If multiple calls to sqlite3_create_function() specify the same function name,
and the same number of arguments, and the same preferred text encoding, then
the callbacks and other parameters of the second call overwrite the first,
and the destructor callback from the first call (if it exists) is invoked.


c2: Application-Defined SQL Functions
c3: 2.3.1. The Scalar Function Callback
c5: appfunc.html#the_scalar_function_callback
c4:
Scalar SQL functions are implemented by a single callback in the
xFunc parameter to sqlite3_create_function().
The following code demonstrations the implementation of a "noop(X)"
scalar SQL function that merely returns its argument:

static void noopfunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  assert( argc==1 );
  sqlite3_result_value(context, argv&#91;0&#93;);
}



The 1st parameter, context, is a pointer to an opaque object
that describes the content from which the SQL function was invoked.  This
context point becomes the first parameter to many other routines that
the function implement might to invoke, including:



sqlite3_aggregate_context
sqlite3_context_db_handle
sqlite3_get_auxdata
sqlite3_result_blob
sqlite3_result_blob64
sqlite3_result_double
sqlite3_result_error
sqlite3_result_error16
sqlite3_result_error_code
sqlite3_result_error_nomem
sqlite3_result_error_toobig
sqlite3_result_int
sqlite3_result_int64
sqlite3_result_null
sqlite3_result_pointer
sqlite3_result_subtype
sqlite3_result_text
sqlite3_result_text16
sqlite3_result_text16be
sqlite3_result_text16le
sqlite3_result_text64
sqlite3_result_value
sqlite3_result_zeroblob
sqlite3_result_zeroblob64
sqlite3_set_auxdata
sqlite3_user_data




The sqlite3_result() family of functions are
used to specify the result of the scalar SQL function.  One or more of
these should be invoked by the callback to set the function return value.
If none of these routines are invoked for a specific callback, then the
return value will be NULL.

The sqlite3_user_data() routine returns a copy of the pArg
pointer that was given to sqlite3_create_function() when the SQL
function was created.

The sqlite3_context_db_handle() routine returns a pointer to the
database connection object.

The sqlite3_aggregate_context() routine is used only in the
implementations of aggregate and window functions.  Scalar functions
may not use sqlite3_aggregate_context().  The sqlite3_aggregate_context()
function is included in the interface list only for completeness.


The 2nd and 3rd arguments to the scalar SQL function implemenetation,
argc and argv, are
the number of arguments to the SQL function itself and the values for
each argument of the SQL function.
Argument values can be of any datatype and are thus stored in
instances of the sqlite3_value object.
Specific C-language values can be extracted from this object using
the sqlite3_value() family of interfaces.


c2: Application-Defined SQL Functions
c3: 2.3.2. The Aggregate Function Callbacks
c5: appfunc.html#the_aggregate_function_callbacks
c4:
Aggregate SQL functions are implemented by using two callback
functions, xStep and xFinal.  The xStep() function 
is called for each row of the aggregate and the xFinal() function
is invoked to compute the final answer at the end.
The following (slightly simplified) version of the built-in
count() function illustrates:

typedef struct CountCtx CountCtx;
struct CountCtx {
  i64 n;
};
static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, sizeof(*p));
  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv&#91;0&#93;)) && p ){
    p->n++;
  }
}   
static void countFinalize(sqlite3_context *context){
  CountCtx *p;
  p = sqlite3_aggregate_context(context, 0);
  sqlite3_result_int64(context, p ? p->n : 0);
}


Recall that there are two versions of the count() aggregate.
With zero arguments, count() returns a count of the number of rows.
With one argument, count() returns the number of times that the
argument was non-NULL.

The countStep() callback is invoked once for each row in the aggregate.
As you can see, the count is incremented if either there are no arguments,
or if the one argument is not NULL.

The step function for an aggregate should always begin with a call
to the sqlite3_aggregate_context() routine to fetch the persistent
state of the aggregate function.  On the first invocation of the step()
function, the aggregate context is initialized to a block of memory
that is N bytes in size, where N is the second parameter to
sqlite3_aggregate_context() and that memory is zeroed.  On all subsequent
calls to the step() function, the same block of memory is returned.
Except, sqlite3_aggregate_context() might return NULL in the case of
an out-of-memory error, so aggregate functions should be prepared to
deal with that case.

After all rows are processed the countFinalize() routine is called
exactly once.  This routine computes the final result and invokes
one of the sqlite3_result() family of functions
to set the final result.  The aggregate context will be freed automatically
by SQLite, though the xFinalize() routine must clean up any substructure
associated with the aggregate context before it returns.  If the xStep()
method is called one or more times, then SQLite guarantees thta the
xFinal() method will be called at once, even if the query aborts.


c2: Application-Defined SQL Functions
c3: 2.3.3. The Window Function Callbacks
c5: appfunc.html#the_window_function_callbacks
c4:
Window functions use the same xStep() and xFinal() callbacks that
aggregate functions use, plus two others: xValue and xInverse.
See the documentation on
application-defined window functions for further details.


c2: Application-Defined SQL Functions
c3: 2.3.4. Examples
c5: appfunc.html#examples
c4:
There are dozens and dozens of SQL function implementations scattered
throughout the SQLite source code that can be used as example applications.
The built-in SQL functions use the same interface as application-defined
SQL functions, so built-in functions can be used as examples too.
Search for "sqlite3_context" in the SQLite source code to find examples.


c2: Application-Defined SQL Functions
c3: 3. Security Implications
c5: appfunc.html#security_implications
c4:
Application-defined SQL functions can become security vulnerabilities if
not carefully managed.  Suppose, for example, an application defines
a new "system(X)" SQL function that runs its argument X as a command and
returns the integer result code.  Perhaps the implementation is like this:

static void systemFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zCmd = (const char*)sqlite3_value_text(argv&#91;0&#93;);
  if( zCmd!=0 ){
    int rc = system(zCmd);
    sqlite3_result_int(context, rc);
  }
}



This is a function with powerful side-effects.  Most programmers would
be naturally cautious about using it, but probably would not see the
harm in merely having it available.  But there is great risk in merely
defining such a function, even if the application itself never invokes
it!


Suppose the application normally does a query against table TAB1
when it starts up.  If an attacker can gain access to the database
file and modify the schema like this:

ALTER TABLE tab1 RENAME TO tab1_real;
CREATE VIEW tab1 AS SELECT * FROM tab1 WHERE system('rm -rf *') IS NOT NULL;



Then, when the application attempts to open the database, register the
system() function, then run an innocent query against the "tab1" table,
it instead deletes all the files in its working directory.  Yikes!


To prevent this kind of mischief, applications that create their own
custom SQL functions should take one or more of the following safety
precautions.  The more precautions taken the better:



Invoke sqlite3_db_config(db,SQLITE_DBCONFIG_TRUSTED_SCHEMA,0,0)
on each database connection as soon as it is opened.
This prevents application-defined functions from being used in places
where an attacker might be able to surreptiously invoke them by modifying
a database schema:

 In in VIEWs.
 In in TRIGGERSs.
 In CHECK constraints of a table definition.
 In DEFAULT constraints of a table definition.
 In the definitions of generated columns.
 In the expression part of an index on an expression.
 In the WHERE clause of a partial index.


To put it another way, this setting requires that application-defined
functions only be run directly by top-level SQL invoked from the application
itself, not as a consequence of doing some other innocent-looking query.


Use the PRAGMA trusted_schema=OFF SQL statement to disable trusted
schema.  This has the same effect as the previous bullet, but does not
require the use of C-code and hence can be performed in programs written
in another programming language and that do not have access SQLite
C-language APIs.


Compile SQLite using the -DSQLITE_TRUSTED_SCHEMA=0 compile-time option.
This make SQLite distrust application-defined functions inside of
the schema by default.


If any application-defined SQL functions have potentially dangerous
side-effects, or if they could potentially leak sensitive information
to an attacker if misused, then tag those functions using the
SQLITE_DIRECTONLY option on the "enc" parameter.  This means
that the function can never be run from schema-code even if the
trusted-schema option is on.


Never tag an application-defined SQL function with SQLITE_INNOCUOUS
unless you really need to and you have checked the implementation closely
and are certain that it can do no harm even if it falls under the
control of an attacker.


c2: How To Download Canonical SQLite Source Code
c3: 1. Introduction
c5: getthecode.html#introduction
c4:
Most programmers compile SQLite into their applications using
the amalgamation.  The amalgamation is C-code but it is not
"source code".  The amalgamation is generated from source code
by scripts.

This document describes how to obtain the canonical source code
for SQLite - the raw source files from which the amalgamation is
built.  See the How To Compile SQLite page for additional information
on what to do with the canonical source code once it is obtained.


c2: How To Download Canonical SQLite Source Code
c3: 2. Direct Downloads
c5: getthecode.html#direct_downloads
c4:
Snapshots of official releases of SQLite source code can often
be obtained directly from the download page of the SQLite website.
Even if the specific version desired is not listed on the download page,
the naming conventions are fairly clear and so programmers can often
guess the name of an historical release and download it that way.


c2: How To Download Canonical SQLite Source Code
c3: 3. Obtaining Code Directly From the Version Control System
c5: getthecode.html#obtaining_code_directly_from_the_version_control_system
c4:
For any historical version of SQLite, the source tree can be obtained
from the Fossil version control system,
either downloading a tarball or ZIP archive for a specific version, or
by cloning the entire project history.

SQLite sources are maintained on three geographically dispersed
servers:


https://www.sqlite.org/src (Dallas)
https://www2.sqlite.org/src (Newark)
https://www3.sqlite.org/src (San Francisco)


The documentation is maintained in separate source repositories on
those same servers:


https://www.sqlite.org/docsrc (Dallas)
https://www2.sqlite.org/docsrc (Newark)
https://www3.sqlite.org/docsrc (San Francisco)


To download a specific historical version, first locate the specific
version desired by visiting the timeline page on one of these servers
(for example: https://www.sqlite.org/src/timeline).  If
you know the approximate date of the version you want to download, you
can add a query parameter like "c=YYYY-MM-DD" to the "timeline" URL to
see a timeline centered on that date.  For example, to see all the check-ins
that occurred around August 26, 2013, visit
https://www.sqlite.org/src/timeline?c=2013-08-26.
If you are looking for an official release, visit the
chronology page, click on the date to the left of the release
you are looking for, and that will take you immediately to the
check-in corresponding to the release.

Once you locate a specific version, click on the hyperlink for that
version to see the "Check-in Information Page".
Then click on either the "Tarball" link or the
"ZIP archive" link to download the complete source tree.


c2: How To Download Canonical SQLite Source Code
c3: 4. Cloning The Complete Development History
c5: getthecode.html#cloning_the_complete_development_history
c4:
To clone the entire history of SQLite, first go to the
https://www.fossil-scm.org/download.html page and grab a precompiled binary
for the Fossil version control program.  Or get the source code on the
same page and compile it yourself.

As of 2017-03-12, you must use Fossil version
2.0 or later for the following instructions to work.  
The SQLite repository started using
artifacts named using SHA3 hashes instead of SHA1 hashes on that date,
and Fossil 2.0 or later is needed in order to understand the new SHA3
hashes.  To find out what version of Fossil you are running, 
type "fossil -v".

Fossil is a completely stand-alone
program, so install it simply by putting the "fossil" or "fossil.exe"
executable someplace on your $PATH or %PATH%.  After you have Fossil
installed, do this:

fossil clone https://www.sqlite.org/src sqlite.fossil


The command above
will make a copy of the complete development history of
SQLite into the "sqlite.fossil" file on your computer.  Making this copy
takes about a minute and uses about 32 megabytes of transfer.  After
making the copy, "open" the repository by typing:

fossil open sqlite.fossil


This second command will "checkout" the latest check-in from the SQLite
source tree into your current directory.  Subsequently, you can easily switch
to a different version by typing:

fossil update VERSION


Where VERSION can be a branch name (like "trunk" or "session") to get the
latest check-in on a specific branch, or VERSION can be a SHA1 hash or a
prefix of a SHA1 hash for a specific check-in, or VERSION can be a tag
such as "version-3.8.8".  Every time you run "fossil update" it will
automatically reach out to the original repository at
https://www.sqlite.org/src to obtain new check-ins that might have been
made by others since your previous update.


c2: The COMPLETION() Table-Valued Function
c3: 1. Overview
c5: completion.html#overview
c4:
The COMPLETION extension implements a table-valued function named
"completion" that can be used to suggest completions of partially entered
words during interactive SQL input.  The completion table can be
used to help implement tab-completion, for example.


c2: The COMPLETION() Table-Valued Function
c3: 2. Details
c5: completion.html#details
c4:
The designed query interface is:

SELECT DISTINCT candidate COLLATE nocase
  FROM completion($prefix, $wholeline)
 ORDER BY 1;


The query above will return suggestions for the whole input word that
begins with $prefix.  The $wholeline parameter is all text from the beginning
of the line up to the insertion point.  The $wholeline parameter is used
for context.

The $prefix parameter may be NULL, in which case the prefix is deduced
from $wholeline.  Or, the $wholeline parameter may be NULL or omitted if 
context information is unavailable or if context-aware completion is not
desired.

The completion table might return the same candidate more than once, and
it will return candidates in an arbitrary order.  The DISTINCT keyword and
the ORDER BY in the sample query above are added to make the answers unique
and in lexicographical order.


c2: The COMPLETION() Table-Valued Function
c3: 2.1. Example Usage
c5: completion.html#example_usage
c4:
The completion table is used to implement tab-completion in the
command-line shell in conjunction with either the readline or linenoise
input line editing packages for unix.  See the
https://sqlite.org/src/file/src/shell.c.in source file for example
code.  Search for "FROM completion" to find the relevant code sections.

Because the completion table is built into the command-line shell in order
to provide for tab-completions, you can run test queries against the
completion table directly in the command-line shell.  Simply type a
query such as the example shown above, filling in appropriate values
for $prefix and $wholeline, and observe the output.


c2: The COMPLETION() Table-Valued Function
c3: 3. Limitations
c5: completion.html#limitations
c4:
The completion table is designed for interactive use.  It will return
answers at a speed appropriate for human typing.  No effort is made to
be unusually efficient, so long as the response time is nearly instantaneous
in a user interface.

As of this writing (2017-07-13), the completion virtual table only
looks for SQL keywords, and schema, table, and column names.  The
context contained in $wholeline is completely ignored.  Future enhancements
will try to return new completions taken from function and pragma names
and other sources, as well as consider more context.  The completion
table should be considered a work-in-progress.


c2: Deterministic SQL Functions
c3: 1. Overview
c5: deterministic.html#overview
c4:
SQL functions in SQLite can be either "deterministic" or "non-deterministic".


A deterministic function always gives the same answer when it has
the same inputs.  Most built-in SQL functions in SQLite are
deterministic.  For example, the abs(X) function always returns
the same answer as long as its input X is the same.


Non-deterministic functions might give different answers on each
invocation, even if the arguments are always the same.  The following
are examples of non-deterministic functions:


 random()
 changes()
 last_insert_rowid()
 sqlite3_version()



The random() function is obviously non-deterministic because it gives
a different answer every time it is invoked.  The answers from changes()
and last_insert_rowid() depend on prior SQL statements, and so they
are also non-deterministic. The
sqlite3_version() function is mostly constant, but it can change when
SQLite is upgraded, and so even though it always returns the same answer
for any particular session, because it can change answers across sessions
it is still considered non-deterministic.


c2: Deterministic SQL Functions
c3: 2. Restrictions on the use of non-deterministic functions
c5: deterministic.html#restrictions_on_the_use_of_non_deterministic_functions
c4:
There are some contexts in SQLite that do not allow the use of
non-deterministic functions:


In the expression of a CHECK constraint.
In the WHERE clause of a partial index.
In an expression used as part of an expression index.
In the expression of a generated column.



In the cases above, the values returned by the function affects the
information stored in the database file.  The values of functions
in CHECK constraints determines which entries are valid for a table,
and functions in the WHERE clause of a partial index or in an index on
an expression compute values stored in the index b-tree.
If any of these functions later returns a different
value, then the database might no longer be well-formed.  
Hence, to avoid database corruption,
only deterministic functions can be used in the contexts
above.


c2: Deterministic SQL Functions
c3: 3. Special-case Processing For Date/Time Functions
c5: deterministic.html#special_case_processing_for_date_time_functions
c4:
The built-in date and time functions of SQLite are a special case.
These functions are usually considered deterministic.  However, if
these functions use the string "now" as the date, or if they use
the localtime modifier or the utc modifier, then they are
considered non-deterministic.  Because the function inputs are
not necessarily known until run-time, the date/time functions will
throw an exception if they encounter any of the non-deterministic
features in a context where only deterministic functions are allowed.


Prior to SQLite 3.20.0 (2017-08-01) all date/time functions were
always considered non-deterministic.  The ability for date/time functions
to be deterministic sometimes and non-deterministic at other times,
depending on their arguments, was added for the 3.20.0 release.


c2: Deterministic SQL Functions
c3: 3.1. Bug fix in version 3.35.2
c5: deterministic.html#bug_fix_in_version_3_35_2
c4:
When the enhancement was made to SQLite 3.20.0 such that date/time
functions would be considered deterministic as they do not depend
on the current time, one case was overlooked:
Many of the date/time functions can be called
with no arguments at all.  These no-argument date/time functions
behave as if they had a single "'now'" argument.
Thus "datetime()" and
"datetime('now')" both yield the current date and time.
However, only the second form was recognized as non-deterministic.
This meant that developers could sneak the non-deterministic
"datetime()" form into CHECK constraints, index
expressions, generated column expressions, and similar places
where non-deterministic functions make no sense.
This oversight was fixed in version 3.35.2 (2021-03-17).
However, there may be legacy databases in circulation that were created
by SQLite version 3.20.0 through 3.35.1 that have non-deterministic
date/time functions in their schemas.


c2: Deterministic SQL Functions
c3: 4. Application-defined deterministic functions
c5: deterministic.html#application_defined_deterministic_functions
c4:
By default, application-defined SQL functions are considered to
be non-deterministic.  However, if the 4th parameter to
sqlite3_create_function_v2() is OR-ed with 
SQLITE_DETERMINISTIC, then SQLite will treat that function as if it
were deterministic.


Note that if a non-deterministic function is tagged with
SQLITE_DETERMINISTIC and if that function ends up being used in
the WHERE clause of a partial index or in an
expression index, then when the function begins to return different
answers, the associated index may become corrupt.  If an SQL function
is nearly deterministic (which is to say, if it only rarely changes,
like sqlite_version()) and it is used in an index that becomes
corrupt, the corruption can be fixed by running REINDEX.


The interfaces necessary to construct a function that is sometimes
deterministic and sometimes non-deterministic depending on their
inputs, such as the built-in date/time functions, are not published.
Generic application-defined SQL functions must
be always deterministic or always non-deterministic.


c2: Floating Point Numbers
c3: 1. How SQLite Stores Numbers
c5: floatingpoint.html#how_sqlite_stores_numbers
c4:
SQLite stores integer values in the 64-bit 
twos-complement
format.
This gives a storage range of -9223372036854775808 to +9223372036854775807,
inclusive.  Integers within this range are exact.


So-called "REAL" or floating point values are stored in the
IEEE 754
Binary-64
format.
This gives a range of positive values between approximately
1.7976931348623157e+308 and 4.9406564584124654e-324 with an equivalent
range of negative values.  A binary64 can also be 0.0 (and -0.0), positive
and negative infinity and "NaN" or "Not-a-Number".  Floating point
values are approximate.


Pay close attention to the last sentence in the previous paragraph:

Floating point values are approximate.



If you need an exact answer, you should not use binary64 floating-point
values, in SQLite or in any other product.  This is not an SQLite limitation.
It is a mathematical limitation inherent in the design of floating-point numbers.


c2: Floating Point Numbers
c3: 1.1. Floating-Point Accuracy
c5: floatingpoint.html#floating_point_accuracy
c4:
SQLite promises to preserve the 15 most significant digits of a floating
point value.  However, it makes no guarantees about the accuracy of
computations on floating point values, as no such guarantees are possible.
Performing math on floating-point values introduces error.
For example, consider what happens if you attempt to subtract two floating-point
numbers of similar magnitude:



1152693165.1106291898
-1152693165.1106280772

0.0000011126



The result shown above (0.0000011126) is the correct answer.  But if you
do this computation using binary64 floating-point, the answer you get is
0.00000095367431640625 - an error of about 14%.  If you do many similar
computations as part of your program, the errors add up so that your final
result might be completely meaningless.

The error arises because only about the first 15 significant digits of
each number are stored accurately, and the first difference between the two numbers
being subtracted is in the 16th digit.


c2: Floating Point Numbers
c3: 1.2. Floating Point Numbers
c5: floatingpoint.html#floating_point_numbers
c4:
The binary64 floating-point format uses 64 bits per number.  Hence there
are 1.845e+19 different possible floating point values.  On the other hand
there are infinitely many real numbers in the range of 
1.7977e+308 and 4.9407e-324.  It follows then that binary64 cannot possibly
represent all possible real numbers within that range.  Approximations are
required.


An IEEE 754 floating-point value is an integer multiplied by a power
of two:


M &times 2E


The M value is the "mantissa" and E is the "exponent".  Both
M and E are integers.

For Binary64, M is a 53-bit integer and E is an 11-bit integer that is
offset so that represents a range of values between -1074 and +972, inclusive.

(NB:  The usual description of IEEE 754 is more complex, and it is important
to understand the added complexity if you really want to appreciate the details,
merits, and limitations of IEEE 754.  However, the integer description shown
here, while not exactly right, is easier to understand and is sufficient for
the purposes of this article.)


c2: Floating Point Numbers
c3: 1.2.1. Unrepresentable numbers
c5: floatingpoint.html#unrepresentable_numbers
c4:
Not every decimal number with fewer than 16 significant digits can be
represented exactly as a binary64 number.  In fact, most decimal numbers
with digits to the right of the decimal point lack an exact binary64
equivalent.  For example, if you have a database column that is intended
to hold an item price in dollars and cents, the only cents value that
can be exactly represented are 0.00, 0.25, 0.50, and 0.75.  Any other
numbers to the right of the decimal point result in an approximation.
If you provide a "price" value of 47.49, that number will be represented
in binary64 as:


6683623321994527 &times; 2-47


Which works out to be:


47.49000000000000198951966012828052043914794921875


That number is very close to 47.49, but it is not exact.  It is a little
too big.  If we reduce M by one to 6683623321994526 so that we have the
next smaller possible binary64 value, we get:


47.4899999999999948840923025272786617279052734375




This second number is too small.
The first number is closer to the desired value of 47.49, so that is the
one that gets used.  But it is not exact.  Most decimal values work this
way in IEEE 754.  Remember the key point we made above:


Floating point values are approximate.


If you remember nothing else about floating-point values, 
please don't forget this one key idea.


c2: Floating Point Numbers
c3: 1.2.2. Is it close enough?
c5: floatingpoint.html#is_it_close_enough_
c4:
The precision provided by IEEE 754 Binary64 is sufficient for most computations.
For example, if "47.49" represents a price and inflation is running
at 2% per year, then the price is going up by about 0.0000000301 dollars per
second.  The error in the recorded value of 47.49 represents about 66 nanoseconds
worth of inflation.  So if the 47.49 price is exact
when you enter it, then the effects of inflation will cause the true value to
exactly equal the value actually stored
(47.4900000000000019895196601282805204391479492187) in less than 
one ten-millionth of a second.
Surely that level of precision is sufficient for most purposes?


c2: Floating Point Numbers
c3: 2.1. The ieee754.c Extension
c5: floatingpoint.html#the_ieee754_c_extension
c4:
The ieee754 extension converts a floating point number between its
binary64 representation and the M&times;2E format.
In other words in the expression:


F = M &times 2E


The ieee754 extension converts between F and (M,E) and back again.

The ieee754 extension is not part of the amalgamation, but it is included
by default in the CLI.  If you want to include the ieee754 extension in your
application, you will need to compile and load it separately.


c2: Floating Point Numbers
c3: 2.1.1. The ieee754() function
c5: floatingpoint.html#the_ieee754_function
c4:
The ieee754(F) SQL function takes a single floating-point argument
as its input and returns a string that looks like this:


'ieee754(M,E)'


Except that the M and E are replaced by the mantissa and exponent of the
floating point number.  For example:

sqlite> .mode box
sqlite> SELECT ieee754(47.49) AS x;
┌───────────────────────────────┐
│               x               │
├───────────────────────────────┤
│ ieee754(6683623321994527,-47) │
└───────────────────────────────┘



Going in the other direction, the 2-argument version of ieee754() takes
the M and E values and converts them into the corresponding F value:

sqlite> select ieee754(6683623321994527,-47) as x;
┌───────┐
│   x   │
├───────┤
│ 47.49 │
└───────┘


c2: Floating Point Numbers
c3: 2.1.2. The ieee754_mantissa() and ieee754_exponent() functions
c5: floatingpoint.html#the_ieee754_mantissa_and_ieee754_exponent_functions
c4:
The text output of the one-argument form of ieee754() is great for human
readability, but it is awkward to use as part of a larger expression.  Hence
the ieee754_mantissa() and ieee754_exponent() routines were added to return
the M and E values corresponding to their single argument F
value.
For example:

sqlite> .mode box
sqlite> SELECT ieee754_mantissa(47.49) AS M, ieee754_exponent(47.49) AS E;
┌──────────────────┬─────┐
│        M         │  E  │
├──────────────────┼─────┤
│ 6683623321994527 │ -47 │
└──────────────────┴─────┘


c2: Floating Point Numbers
c3: 2.1.3. The ieee754_from_blob() and ieee754_to_blob() functions
c5: floatingpoint.html#the_ieee754_from_blob_and_ieee754_to_blob_functions
c4:
The ieee754_to_blob(F) SQL function converts the floating point number F
into an 8-byte BLOB that is the big-endian binary64 encoding of that number.
The ieee754_from_blob(B) function goes the other way, converting an 8-byte
blob into the floating-point value that the binary64 encoding represents.

So, for example, if you read
on
Wikipedia that the encoding for the minimum positive binary64 value is
0x0000000000000001, then you can find the corresponding floating point value
like this:

sqlite> .mode box
sqlite> SELECT ieee754_from_blob(x'0000000000000001') AS F;
┌───────────────────────┐
│           F           │
├───────────────────────┤
│ 4.94065645841247e-324 │
└───────────────────────┘


Or go the other way:

sqlite> .mode box
sqlite> SELECT quote(ieee754_to_blob(4.94065645841247e-324)) AS binary64;
┌─────────────────────┐
│      binary64       │
├─────────────────────┤
│ X'0000000000000001' │
└─────────────────────┘


c2: Floating Point Numbers
c3: 2.2. The decimal.c Extension
c5: floatingpoint.html#the_decimal_c_extension
c4:
The decimal extension provides arbitrary-precision decimal arithmetic on
numbers stored as text strings.  Because the numbers are stored to arbitrary
precision and as text, no approximations are needed.  Computations can be
done exactly.

The decimal extension is not (currently) part of the SQLite amalgamation.
However, it is included in the CLI.

There are three math functions available:



 decimal_add(A,B)
 decimal_sub(A,B)
 decimal_mul(A,B)



These functions respectively add, subtract, and multiply their arguments
and return a new text string that is the decimal representation of the result.
There is no division operator at this time.

Use the decimal_cmp(A,B) to compare two decimal values.  The result will
be negative, zero, or positive if A is less than, equal to, or greater than B,
respectively.

The decimal_sum(X) function is an aggregate, like the built-in
sum() aggregate function, except that decimal_sum() computes its result
to arbitrary precision and is therefore precise.

Finally, the decimal extension provides the "decimal" collating sequences
that compares decimal text strings in numeric order.


c2: Floating Point Numbers
c3: 3. Techniques
c5: floatingpoint.html#techniques
c4:
The following SQL illustrates how to use the ieee754 and decimal
extensions to compute the exact decimal equivalent
for a binary64 floating-point number.

-- The pow2 table will hold all the necessary powers of two.
CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
WITH RECURSIVE c(x,v) AS (
  VALUES(0,'1')
  UNION ALL
  SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1&lt;=971
) INSERT INTO pow2(x,v) SELECT x, v FROM c;
WITH RECURSIVE c(x,v) AS (
  VALUES(-1,'0.5')
  UNION ALL
  SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1&gt;=-1075
) INSERT INTO pow2(x,v) SELECT x, v FROM c;

-- This query finds the decimal representation of each value in the "c" table.
WITH c(n) AS (VALUES(47.49))
                 ----XXXXX----------- Replace with whatever you want
SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
  FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);


c2: Command Line Shell For SQLite
c3: 1. Getting Started
c5: cli.html#getting_started
c4:
The SQLite project provides a simple command-line program named
sqlite3 (or sqlite3.exe on Windows)
that allows the user to manually enter and execute SQL
statements against an SQLite database or against a
ZIP archive.  This document provides a brief
introduction on how to use the sqlite3 program.

Start the sqlite3 program by typing "sqlite3" at the
command prompt, optionally followed 
by the name the file that holds the SQLite database
(or ZIP archive).  If the named
file does not exist, a new database file with the given name will be
created automatically.  If no database file is specified on the
command-line, a temporary database is created and automatically deleted when 
the "sqlite3" program exits.

On startup, the sqlite3 program will show a brief banner
message then prompt you to enter SQL.  Type in SQL statements (terminated
by a semicolon), press "Enter" and the SQL will be executed.

For example, to create a new SQLite database named "ex1" 
with a single table named "tbl1", you might do this:

$ sqlite3 ex1
SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
sqlite&gt; create table tbl1(one text, two int);
sqlite&gt; insert into tbl1 values('hello!',10);
sqlite&gt; insert into tbl1 values('goodbye', 20);
sqlite&gt; select * from tbl1;
hello!|10
goodbye|20
sqlite&gt;


Terminate the sqlite3 program by typing your system
End-Of-File character (usually a Control-D).  Use the interrupt
character (usually a Control-C) to stop a long-running SQL statement.

Make sure you type a semicolon at the end of each SQL command!
The sqlite3 program looks for a semicolon to know when your SQL command is
complete.  If you omit the semicolon, sqlite3 will give you a
continuation prompt and wait for you to enter more text to 
complete the SQL command.  This feature allows you to
enter SQL commands that span multiple lines.  For example:


sqlite&gt; CREATE TABLE tbl2 (
   ...&gt;   f1 varchar(30) primary key,
   ...&gt;   f2 text,
   ...&gt;   f3 real
   ...&gt; );
sqlite&gt;


c2: Command Line Shell For SQLite
c3: 2. Double-click Startup On Windows
c5: cli.html#double_click_startup_on_windows
c4:
Windows users can double-click on the sqlite3.exe icon to cause
the command-line shell to pop-up a terminal window running SQLite.  However,
because double-clicking starts the sqlite3.exe without command-line arguments,
no database file will have been specified, so SQLite will use a temporary
database that is deleted when the session exits.
To use a persistent disk file as the database, enter the ".open" command
immediately after the terminal window starts up:

SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite&gt; .open ex1.db
sqlite&gt;


The example above causes the database file named "ex1.db" to be opened
and used.  The "ex1.db" file is created if it does not previously exist.
You might want to
use a full pathname to ensure that the file is in the directory that you
think it is in.  Use forward-slashes as the directory separator character.
In other words use "c:/work/ex1.db", not "c:\work\ex1.db".

Alternatively, you can create a new database using the default temporary
storage, then save that database into a disk file using the ".save" command:

SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite&gt; ... many SQL commands omitted ...
sqlite&gt; .save ex1.db
sqlite&gt;


Be careful when using the ".save" command as it will overwrite any
preexisting database files having the same name without prompting for
confirmation.  As with the ".open" command, you might want to use a
full pathname with forward-slash directory separators to avoid ambiguity.


c2: Command Line Shell For SQLite
c3: 3. Special commands to sqlite3 (dot-commands)
c5: cli.html#special_commands_to_sqlite3_dot_commands_
c4:
Most of the time, sqlite3 just reads lines of input and passes them
on to the SQLite library for execution.
But input lines that begin with a dot (".")
are intercepted and interpreted by the sqlite3 program itself.
These "dot commands" are typically used to change the output format
of queries, or to execute certain prepackaged query statements.
There were originally just a few dot commands, but over the years
many new features have accumulated so that today there are over 60.



For a listing of the available dot commands, you can enter ".help" with
no arguments.  Or enter ".help TOPIC" for detailed information about TOPIC.
The list of available dot-commands follows:


sqlite&gt; .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.binary on|off           Turn binary output on or off.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection &#91;close&#93; &#91;#&#93;  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.load FILE ?ENTRY?       Load an extension library
.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?       Set output mode
.nonce STRING            Disable safe mode for one command if the nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Exit this program
.read FILE               Read input from FILE
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save FILE               Write in-memory database into FILE
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output
sqlite&gt;


c2: Command Line Shell For SQLite
c3: 4.1. Line Structure
c5: cli.html#line_structure
c4:
The CLI's input is parsed into a sequence consisting of:
  
    SQL statements;
    dot-commands; or
    CLI comments
  
SQL statements are free-form, and can be spread across multiple lines,
  with whitespace or SQL comments embedded anywhere.
  They are terminated by either a ';' character at the end of an input line,
  or a '/' character or the word "go" on a line by itself.
  When not at the end of an input line, the ';' character
  acts to separate SQL statements.
  Trailing whitespace is ignored for purposes of termination.
A dot-command has a more restrictive structure:

It must begin with its "." at the left margin
    with no preceding whitespace.
It must be entirely contained on a single input line.
It cannot occur in the middle of an ordinary SQL
    statement.  In other words, it cannot occur at a
    continuation prompt.
There is no comment syntax for dot-commands.

The CLI also accepts whole-line comments that
begin with a '#' character and extend to the end of the line.
There can be no with whitespace prior to the '#'.


c2: Command Line Shell For SQLite
c3: 4.2. Dot-command arguments
c5: cli.html#dot_command_arguments
c4:
The arguments passed to dot-commands are parsed from the command tail, 
  per these rules:

  The trailing newline and any other trailing whitespace is discarded;
  Whitespace immediately following the dot-command name, or any argument
    input end bound is discarded;
  An argument input begins with any non-whitespace character;
  An argument input ends with a character which
    depends upon its leading character thusly:
  
    for a leading single-quote ('), a single-quote acts
      as the end delimiter;
    for a leading double-quote ("), an unescaped double-quote
      acts as the end delimiter;
    for any other leading character, the end delimiter is
      any whitespace; and
    the command tail end acts as the end delimiter for any argument;
  
  Within a double-quoted argument input, a backslash-escaped double-quote
    is part of the argument rather than its terminating quote;
  Within a double-quoted argument, traditional C-string literal, backslash
    escape sequence translation is done; and
  Argument input delimiters (the bounding quotes or whitespace)
    are discarded to yield the passed argument.


c2: Command Line Shell For SQLite
c3: 4.3. Dot-command execution
c5: cli.html#dot_command_execution
c4:
The dot-commands
are interpreted by the sqlite3.exe command-line program, not by
SQLite itself.  So none of the dot-commands will work as an argument
to SQLite interfaces such as sqlite3_prepare() or sqlite3_exec().


c2: Command Line Shell For SQLite
c3: 5. Changing Output Formats
c5: cli.html#changing_output_formats
c4:
The sqlite3 program is able to show the results of a query
in 14 different output formats:


 ascii
 box
 csv
 column
 html
 insert
 json
 line
 list
 markdown
 quote
 table
 tabs
 tcl


You can use the ".mode" dot command to switch between these output
formats.
The default output mode is "list".  In
list mode, each row of a query result is written on one line of
output and each column within that row is separated by a specific
separator string.  The default separator is a pipe symbol ("|").
List mode is especially useful when you are going to send the output
of a query to another program (such as AWK) for additional processing.

sqlite&gt; .mode list
sqlite&gt; select * from tbl1;
hello!|10
goodbye|20
sqlite&gt;


Type ".mode" with no arguments to show the current mode:

sqlite&gt; .mode
current output mode: list
sqlite&gt;


Use the ".separator" dot command to change the separator.
For example, to change the separator to a comma and
a space, you could do this:

sqlite&gt; .separator ", "
sqlite&gt; select * from tbl1;
hello!, 10
goodbye, 20
sqlite&gt;


The next ".mode" command might reset the ".separator" back to some
default value (depending on its arguments).
So you will likely need to repeat the ".separator" command whenever you
change modes if you want to continue using a non-standard separator.



In "quote" mode, the output is formatted as SQL literals.  Strings are
enclosed in single-quotes and internal single-quotes are escaped by doubling.
Blobs are displayed in hexadecimal blob literal notation (Ex: x'abcd').
Numbers are displayed as ASCII text and NULL values are shown as "NULL".
All columns are separated from each other by a comma (or whatever alternative
character is selected using ".separator").

sqlite&gt; .mode quote
sqlite&gt; select * from tbl1;
'hello!',10
'goodbye',20
sqlite&gt;


In "line" mode, each column in a row of the database
is shown on a line by itself.  Each line consists of the column
name, an equal sign and the column data.  Successive records are
separated by a blank line.  Here is an example of line mode
output:

sqlite&gt; .mode line
sqlite&gt; select * from tbl1;
one = hello!
two = 10

one = goodbye
two = 20
sqlite&gt;





In column mode, each record is shown on a separate line with the
data aligned in columns.  For example:

sqlite&gt; .mode column
sqlite&gt; select * from tbl1;
one       two       
--------  ---
hello!    10        
goodbye   20        
sqlite&gt;


In "column" mode (and also in "box", "table", and "markdown" modes)
the width of columns adjusts automatically.  But you can override this,
providing a speicified width for each column using the ".width" command.
The arguments to ".width" are integers which are the number of
characters to devote to each column.  Negative numbers mean right-justify.
Thus:

sqlite&gt; .width 12 -6
sqlite&gt; select * from tbl1;
one              two
------------  ------
hello!            10
goodbye           20
sqlite&gt;


A width of 0 means the column width is chosen automatically.
Unspecified column widths become zero.  Hence, the command
".width" with no arguments resets all column widths to zero and
hence causes all column widths to be determined automatically.

The "column" mode is a tabular output format.  Other
tabular output formats are "box", "markdown", and "table":

sqlite&gt; .width
sqlite&gt; .mode markdown
sqlite&gt; select * from tbl1;
|   one   | two |
|---------|-----|
| hello!  | 10  |
| goodbye | 20  |
sqlite&gt; .mode table
sqlite&gt; select * from tbl1;
+---------+-----+
|   one   | two |
+---------+-----+
| hello!  | 10  |
| goodbye | 20  |
+---------+-----+
sqlite&gt; .mode box
sqlite&gt; select * from tbl1;
┌─────────┬─────┐
│   one   │ two │
├─────────┼─────┤
│ hello!  │ 10  │
│ goodbye │ 20  │
└─────────┴─────┘
sqlite&gt;





The columnar modes accept some addition options to control formatting.
The "--wrap N" option (where N is an integer) causes columns
to wrap text that is longer than N characters.  Wrapping is disabled if
N is zero.

sqlite&gt; insert into tbl1 values('The quick fox jumps over a lazy brown dog.',99);
sqlite&gt; .mode box --wrap 30
sqlite&gt; select * from tbl1 where two&gt;50;
┌────────────────────────────────┬─────┐
│              one               │ two │
├────────────────────────────────┼─────┤
│ The quick fox jumps over a laz │ 90  │
│ y brown dog.                   │     │
└────────────────────────────────┴─────┘
sqlite&gt;


Wrapping happens after exactly N characters, 
which might be in the middle of a word.
To wrap at a word boundary, add the "--wordwrap on" option 
(or just "-ww" for short):

sqlite&gt; .mode box --wrap 30 -ww
sqlite&gt; select * from tbl1 where two&gt;50;
┌─────────────────────────────┬─────┐
│             one             │ two │
├─────────────────────────────┼─────┤
│ The quick fox jumps over a  │ 90  │
│ lazy brown dog.             │     │
└─────────────────────────────┴─────┘
sqlite&gt;


The "--quote" option causes the results in each column to be
quoted like an SQL literal, as in the "quote" mode.  See the on-line
help for additional options.



The command ".mode box --wrap 60 --quote" is so useful for general-purpose
database queries that it is given its own alias.  Instead of typing out
that whole 27-character command, you can just say ".mode qbox".

Another useful output mode is "insert".  In insert mode, the output
is formatted to look like SQL INSERT statements.  Use insert
mode to generate text that can later be used to input data into a 
different database.

When specifying insert mode, you have to give an extra argument
which is the name of the table to be inserted into.  For example:

sqlite&gt; .mode insert new_table
sqlite&gt; select * from tbl1 where two&lt;50;
INSERT INTO "new_table" VALUES('hello',10);
INSERT INTO "new_table" VALUES('goodbye',20);
sqlite&gt;



Other output modes include "csv", "json", and "tcl".  Try these
yourself to see what they do.


c2: Command Line Shell For SQLite
c3: 6. Querying the database schema
c5: cli.html#querying_the_database_schema
c4:
The sqlite3 program provides several convenience commands that
are useful for looking at the schema of the database.  There is
nothing that these commands do that cannot be done by some other
means.  These commands are provided purely as a shortcut.



For example, to see a list of the tables in the database, you
can enter ".tables".


sqlite&gt; .tables
tbl1 tbl2
sqlite&gt;



The ".tables" command is similar to setting list mode then
executing the following query:

SELECT name FROM sqlite_schema 
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
ORDER BY 1


But the ".tables" command does more.  It queries the sqlite_schema table
for all attached databases, not just the primary database.  And it arranges
its output into neat columns.

The ".indexes" command works in a similar way to list all of
the indexes. If the ".indexes" command is given an argument which is
the name of a table, then it shows just indexes on that table.



The ".schema" command shows the complete schema for the database,
or for a single table if an optional tablename argument is provided:

sqlite&gt; .schema
create table tbl1(one varchar(10), two smallint)
CREATE TABLE tbl2 (
  f1 varchar(30) primary key,
  f2 text,
  f3 real
);
sqlite&gt; .schema tbl2
CREATE TABLE tbl2 (
  f1 varchar(30) primary key,
  f2 text,
  f3 real
);
sqlite&gt;



The ".schema" command is roughly the same as setting
list mode, then entering the following query:

SELECT sql FROM sqlite_schema
ORDER BY tbl_name, type DESC, name


As with ".tables", the ".schema" command shows the schema for
all attached databases.  If you only want to see the schema for
a single database (perhaps "main") then you can add an argument
to ".schema" to restrict its output:

sqlite&gt; .schema main.*


The ".schema" command can be augmented with the "--indent" option,
in which case it tries to reformat the various CREATE statements of
the schema so that they are more easily readable by humans.



The ".databases" command shows a list of all databases open in
the current connection.  There will always be at least 2.  The first
one is "main", the original database opened.  The second is "temp",
the database used for temporary tables. There may be additional 
databases listed for databases attached using the ATTACH statement.
The first output column is the name the database is attached with, 
and the second result column is the filename of the external file.
There may be a third result column which will be either "'r/o'" or
"'r/w'" depending on whether the database file is read-only or read-write.
And there might be a fourth result column showing the result of
sqlite3_txn_state() for that database file.

sqlite&gt; .databases




The ".fullschema" dot-command works like the ".schema" command in
that it displays the entire database schema.  But ".fullschema" also
includes dumps of the statistics tables "sqlite_stat1", "sqlite_stat3",
and "sqlite_stat4", if they exist.  The ".fullschema" command normally
provides all of the information needed to exactly recreate a query
plan for a specific query.  When reporting suspected problems with
the SQLite query planner to the SQLite development team, developers
are requested to provide the complete ".fullschema" output as part
of the trouble report.  Note that the sqlite_stat3 and sqlite_stat4
tables contain samples of index entries and so might contain sensitive
data, so do not send the ".fullschema" output of a proprietary database
over a public channel.


c2: Command Line Shell For SQLite
c3: 7. Opening Database Files
c5: cli.html#opening_database_files
c4:
The ".open" command opens a new database connection, after first closing the
previously opened database command.  In its simplest form, the ".open" command merely
invokes sqlite3_open() on the file named as its argument.  Use the name ":memory:"
to open a new in-memory database that disappears when the CLI exits or when the
".open" command is run again.

If the --new option is included with ".open", then the database is reset prior
to being opened.  Any prior data is destroyed.  This is a destructive overwrite of
prior data and no confirmation is requested, so use this option carefully.

The --readonly option opens the database in read-only mode.  Write will be
prohibited.

The --deserialize option causes the entire content of the on-disk file to be
read into memory and then opened as an in-memory database using the
sqlite3_deserialize() interface.  This will, of course, require a lot of memory
if you have a large database.  Also, any changes you make to the database will not
be saved back to disk unless you explicitly save them using the ".save" or ".backup"
commands.

The --append option causes the SQLite database to be appended to an existing
file rather than working as a stand-alone file.  See the 
appendvfs extension for
more information.

The --zip option causes the specified input file to be interpreted as a ZIP archive
instead of as an SQLite database file.

The --hexdb option causes the database content to be to be read from subsequent
lines of input in a hex format, rather than from a separate file on disk.  
The "dbtotxt" command-line tool can be used to generate
the appropriate text for a database.  The --hexdb option is intended for use by the
SQLite developers for testing purposes.  We do not know of any use cases for this
option outside of internal SQLite testing and development.


c2: Command Line Shell For SQLite
c3: 8.1. Writing results to a file
c5: cli.html#writing_results_to_a_file
c4:
By default, sqlite3 sends query results to standard output.  You
can change this using the ".output" and ".once" commands.  Just put 
the name of an output file as an argument to .output and all subsequent
query results will be written to that file.  Or use the .once command
instead of .output and output will only be redirected for the single next
command before reverting to the console.  Use .output with no arguments to
begin writing to standard output again.  For example:

sqlite&gt; .mode list
sqlite&gt; .separator |
sqlite&gt; .output test_file_1.txt
sqlite&gt; select * from tbl1;
sqlite&gt; .exit
$ cat test_file_1.txt
hello|10
goodbye|20
$


If the first character of the ".output" or ".once" filename is a pipe
symbol ("|") then the remaining characters are treated as a command and the
output is sent to that command.  This makes it easy to pipe the results
of a query into some other process.  For example, the 
"open -f" command on a Mac opens a text editor to display the content that
it reads from standard input.  So to see the results of a query
in a text editor, one could type:

sqlite&gt; .once | open -f
sqlite&gt; SELECT * FROM bigTable;


If the ".output" or ".once" commands have an argument of "-e" then
output is collected into a temporary file and the system text editor is
invoked on that text file.  Thus, the command ".once -e" achieves the
same result as ".once '|open -f'" but with the benefit of being portable
across all systems.

If the ".output" or ".once" commands have a "-x" argument, that causes
them to accumulate output as Comma-Separated-Values (CSV) in a temporary
file, then invoke the default system utility for viewing CSV files
(usually a spreadsheet program) on the result.  This is a quick way of
sending the result of a query to a spreadsheet for easy viewing:

sqlite&gt; .once -x
sqlite&gt; SELECT * FROM bigTable;




The ".excel" command is an alias for ".once -x".  It does exactly the same
thing.


c2: Command Line Shell For SQLite
c3: 8.2. Reading SQL from a file
c5: cli.html#reading_sql_from_a_file
c4:
In interactive mode, sqlite3 reads input text (either SQL statements
or dot-commands) from the keyboard.  You can also redirect input from
a file when you launch sqlite3, of course, but then you do not have the
ability to interact with the program.  Sometimes it is useful to run an
SQL script contained in a file entering other commands from the command-line.
For this, the ".read" dot-command is provided.

The ".read" command takes a single argument which is (usually) the name
of a file from which to read input text.

sqlite&gt; .read myscript.sql


The ".read" command temporarily stops reading from the keyboard and instead
takes its input from the file named.  Upon reaching the end of the file,
input reverts back to the keyboard.  The script file may contain dot-commands,
just like ordinary interactive input.

If the argument to ".read" begins with the "|" character, then instead of
opening the argument as a file, it runs the argument (without the leading "|")
as a command, then uses the output of that command as its input.  Thus, if you
have a script that generates SQL, you can execute that SQL directly using
a command similar to the following:

sqlite&gt; .read |myscript.bat


c2: Command Line Shell For SQLite
c3: 8.3. File I/O Functions
c5: cli.html#file_i_o_functions
c4:
The command-line shell adds two application-defined SQL functions that
facilitate reading content from a file into a table column, and writing the
content of a column into a file, respectively.

The readfile(X) SQL function reads the entire content of the file named
X and returns that content as a BLOB.  This can be used to load content into
a table.  For example:

sqlite&gt; CREATE TABLE images(name TEXT, type TEXT, img BLOB);
sqlite&gt; INSERT INTO images(name,type,img)
   ...&gt;   VALUES('icon','jpeg',readfile('icon.jpg'));


The writefile(X,Y) SQL function write the blob Y into the file named X
and returns the number of bytes written.  Use this function to extract
the content of a single table column into a file.  For example:

sqlite&gt; SELECT writefile('icon.jpg',img) FROM images WHERE name='icon';


Note that the readfile(X) and writefile(X,Y) functions are extension
functions and are not built into the core SQLite library.  These routines
are available as a loadable extension in the
ext/misc/fileio.c
source file in the SQLite source code repositories.


c2: Command Line Shell For SQLite
c3: 8.4. The edit() SQL function
c5: cli.html#the_edit_sql_function
c4:
The CLI has another built-in SQL function named edit().  Edit() takes
one or two arguments.  The first argument is a value - often a large
multi-line string to be edited.  The second argument is the invocation
for a text editor. (It may include options to affect the editor's
behavior.) If the second argument is omitted, the VISUAL environment
variable is used.  The edit() function writes its first argument into a
temporary file, invokes the editor on the temporary file, rereads the file
back into memory after the editor is done, then returns the edited text.

The edit() function can be used to make changes to large text
values.  For example:

sqlite&gt; UPDATE docs SET body=edit(body) WHERE name='report-15';


In this example, the content of the docs.body field for the entry where
docs.name is "report-15" will be sent to the editor.  After the editor returns,
the result will be written back into the docs.body field.

The default operation of edit() is to invoke a text editor.  But by using
an alternative edit program in the second argument, you can also get it to edit
images or other non-text resources.  For example, if you want to modify a JPEG
image that happens to be stored in a field of a table, you could run:

sqlite&gt; UPDATE pics SET img=edit(img,'gimp') WHERE id='pic-1542';


The edit program can also be used as a viewer, by simply ignoring the
return value.  For example, to merely look at the image above, you might run:

sqlite&gt; SELECT length(edit(img,'gimp')) WHERE id='pic-1542';


c2: Command Line Shell For SQLite
c3: 8.5. Importing files as CSV or other formats
c5: cli.html#importing_files_as_csv_or_other_formats
c4:
Use the ".import" command to import CSV (comma separated value)
or similarly delimited data into an SQLite table.
The ".import" command takes two arguments which are the
source from which data is to be read and the name of the
SQLite table into which the data is to be inserted. The source argument
is the name of a file to be read or, if it begins with a "|" character,
it specifies a command which will be run to produce the input data.

Note that it may be important to set the "mode" before running the
 ".import" command.  This is prudent to prevent the command-line shell
from trying to interpret the input file text as some format other than
how the file is structured. If the --csv or --ascii options are used,
they control import input delimiters. Otherwise, the delimiters are
those in effect for the current output mode.

To import into a table not in the "main" schema, the --schema option
may be used to specify that the table is in some other schema. This can
be useful for ATTACH'ed databases or to import into a TEMP table.

When .import is run, its treatment of the first input row depends
upon whether the target table already exists. If it does not exist,
the table is automatically created and the content of the first input
row is used to set the name of all the columns in the table. In this
case, the table data content is taken from the second and subsequent
input rows. If the target table already exists, every row of the
input, including the first, is taken to be actual data content.  If
the input file contains an initial row of column labels, you can make
the .import command skip that initial row using the "--skip 1" option.

Here is an example usage, loading a pre-existing temporary table
from a CSV file which has column names in its first row:

sqlite&gt; .import --csv --skip 1 --schema temp C:/work/somedata.csv tab1


c2: Command Line Shell For SQLite
c3: 8.6. Export to CSV
c5: cli.html#export_to_csv
c4:
To export an SQLite table (or part of a table) as CSV, simply set
the "mode" to "csv" and then run a query to extract the desired rows
of the table.

sqlite&gt; .headers on
sqlite&gt; .mode csv
sqlite&gt; .once c:/work/dataout.csv
sqlite&gt; SELECT * FROM tab1;
sqlite&gt; .system c:/work/dataout.csv


In the example above, the ".headers on" line causes column labels to
be printed as the first row of output.  This means that the first row of
the resulting CSV file will contain column labels.  If column labels are
not desired, set ".headers off" instead. (The ".headers off" setting is
the default and can be omitted if the headers have not been previously
turned on.)

The line ".once FILENAME" causes all query output to go into
the named file instead of being printed on the console.  In the example
above, that line causes the CSV content to be written into a file named
"C:/work/dataout.csv".

The final line of the example (the ".system c:/work/dataout.csv")
has the same effect as double-clicking on the c:/work/dataout.csv file
in windows.  This will typically bring up a spreadsheet program to display
the CSV file.

That command only works as written on Windows.  
The equivalent line on a Mac would be:

sqlite&gt; .system open dataout.csv


On Linux and other unix systems you will need to enter something like:


sqlite&gt; .system xdg-open dataout.csv


c2: Command Line Shell For SQLite
c3: 8.6.1. Export to Excel
c5: cli.html#_export_to_excel_
c4:
To simplify export to a spreadsheet, the CLI provides the
".excel" command which captures the output of a single query and sends
that output to the default spreadsheet program on the host computer.
Use it like this:

sqlite&gt; .excel
sqlite&gt; SELECT * FROM tab;



The command above writes the output of the query as CSV into a temporary
file, invokes the default handler for CSV files (usually the preferred
spreadsheet program such as Excel or LibreOffice), then deletes the
temporary file.  This is essentially a short-hand method of doing
the sequence of ".csv", ".once", and ".system" commands described above.


The ".excel" command is really an alias for ".once -x".  The -x option
to .once causes it to writes results as CSV into a temporary file that
is named with a ".csv" suffix, then invoke the systems default handler
for CSV files.


There is also a ".once -e" command which works similarly, except that
it names the temporary file with a ".txt" suffix so that the default
text editor for the system will be invoked, instead of the default
spreadsheet.


c2: Command Line Shell For SQLite
c3: 9. Accessing ZIP Archives As Database Files
c5: cli.html#accessing_zip_archives_as_database_files
c4:
In addition to reading and writing SQLite database files,
the sqlite3 program will also read and write ZIP archives.
Simply specify a ZIP archive filename in place of an SQLite database
filename on the initial command line, or in the ".open" command,
and sqlite3 will automatically detect that the file is a
ZIP archive instead of an SQLite database and will open it as such.
This works regardless of file suffix.  So you can open JAR, DOCX,
and ODP files and any other file format that is really a ZIP
archive and SQLite will read it for you.

A ZIP archive appears to be a database containing a single table
with the following schema:

CREATE TABLE zip(
  name,     // Name of the file
  mode,     // Unix-style file permissions
  mtime,    // Timestamp, seconds since 1970
  sz,       // File size after decompression
  rawdata,  // Raw compressed file data
  data,     // Uncompressed file content
  method    // ZIP compression method code
);


So, for example, if you wanted to see the compression efficiency
(expressed as the size of the compressed content relative to the
original uncompressed file size) for all files in the ZIP archive,
sorted from most compressed to least compressed, you could run a
query like this:

sqlite&gt; SELECT name, (100.0*length(rawdata))/sz FROM zip ORDER BY 2;


Or using file I/O functions, you can extract elements of the
ZIP archive:

sqlite&gt; SELECT writefile(name,content) FROM zip
   ...&gt; WHERE name LIKE 'docProps/%';


c2: Command Line Shell For SQLite
c3: 9.1. How ZIP archive access is implemented
c5: cli.html#how_zip_archive_access_is_implemented
c4:
The command-line shell uses the Zipfile virtual table to
access ZIP archives.  You can see this by running the ".schema"
command when a ZIP archive is open:

sqlite&gt; .schema
CREATE VIRTUAL TABLE zip USING zipfile('document.docx')
/* zip(name,mode,mtime,sz,rawdata,data,method) */;


When opening a file, if the command-line client discovers that the
file is ZIP archive instead of an SQLite database, it actually opens
an in-memory database and then in that in-memory database it creates
an instance of the Zipfile virtual table that is attached to the
ZIP archive.

The special processing for opening ZIP archives is a trick of the
command-line shell, not the core SQLite library.  So if you want to
open a ZIP archive as a database in your application, you will need to
activate the Zipfile virtual table module then run an appropriate
CREATE VIRTUAL TABLE statement.


c2: Command Line Shell For SQLite
c3: 10. Converting An Entire Database To A Text File
c5: cli.html#converting_an_entire_database_to_a_text_file
c4:
Use the ".dump" command to convert the entire contents of a
database into a single UTF-8 text file.  This file can be converted
back into a database by piping it back into sqlite3.

A good way to make an archival copy of a database is this:


$ sqlite3 ex1 .dump | gzip -c &gt;ex1.dump.gz



This generates a file named ex1.dump.gz that contains everything
you need to reconstruct the database at a later time, or on another
machine.  To reconstruct the database, just type:


$ zcat ex1.dump.gz | sqlite3 ex2



The text format is pure SQL so you
can also use the .dump command to export an SQLite database
into other popular SQL database engines.  Like this:


$ createdb ex2
$ sqlite3 ex1 .dump | psql ex2


c2: Command Line Shell For SQLite
c3: 11. Recover Data From a Corrupted Database
c5: cli.html#recover_data_from_a_corrupted_database
c4:
Like the ".dump" command, ".recover" attempts to convert the entire 
contents of a database file to text. The difference is that instead of
reading data using the normal SQL database interface, ".recover"
attempts to reassemble the database based on data extracted directly from 
as many database pages as possible. If the database is corrupt, ".recover"
is usually able to recover data from all uncorrupted parts of the database,
whereas ".dump" stops when the first sign of corruption is encountered.

If the ".recover" command recovers one or more rows that it cannot 
attribute to any database table, the output script creates a "lost_and_found"
table to store the orphaned rows. The schema of the lost_and_found
table is as follows:

CREATE TABLE lost_and_found(
    rootpgno INTEGER,             -- root page of tree pgno is a part of
    pgno INTEGER,                 -- page number row was found on
    nfield INTEGER,               -- number of fields in row
    id INTEGER,                   -- value of rowid field, or NULL
    c0, c1, c2, c3...             -- columns for fields of row
);


The "lost_and_found" table contains one row for each orphaned row recovered
from the database. Additionally, there is one row for each recovered index
entry that cannot be attributed to any SQL index. This is because, in an
SQLite database, the same format is used to store SQL index entries and
WITHOUT ROWID table entries.


  ColumnContents
  rootpgno Even though it may not be possible to attribute the 
      row to a specific database table, it may be part of a tree structure
      within the database file. In this case, the root page number of that
      tree structure is stored in this column. Or, if the page the row was
      found on is not part of a tree structure, this column stores a copy of
      the value in column "pgno" - the page number of the page the row was
      found on. In many, although not all, cases, all rows in the
      lost_and_found table with the same value in this column belong to the
      same table.

  pgno The page number of the page on which this row was found.

  nfield The number of fields in this row.

  id If the row comes from a WITHOUT ROWID table, this column 
      contains NULL. Otherwise, it contains the 64-bit integer rowid value for
      the row.

  c0,&nbsp;c1,&nbsp;c2... The values for each column of the row
      are stored in these columns. The ".recover" command creates the
      lost_and_found table with as many columns as required by the longest
      orphaned row.


If the recovered database schema already contains a table named
"lost_and_found", the ".recover" command uses the name "lost_and_found0". If
the name "lost_and_found0" is also already taken, "lost_and_found1", and so
on. The default name "lost_and_found" may be overridden by invoking ".recover"
with the --lost-and-found switch. For example, to have the output script call
the table "orphaned_rows":

sqlite&gt; .recover --lost-and-found orphaned_rows


c2: Command Line Shell For SQLite
c3: 12. Loading Extensions
c5: cli.html#loading_extensions
c4:
You can add new custom application-defined SQL functions,
collating sequences, virtual tables, and VFSes to the command-line
shell at run-time using the ".load" command.  First, build the
extension as a DLL or shared library (as described in the
Run-Time Loadable Extensions document) then type:

sqlite&gt; .load /path/to/my_extension


Note that SQLite automatically adds the appropriate extension suffix
(".dll" on windows, ".dylib" on Mac, ".so" on most other unixes) to the
extension filename.  It is generally a good idea to specify the full
pathname of the extension.

SQLite computes the entry point for the extension based on the extension
filename.  To override this choice, simply add the name of the extension
as a second argument to the ".load" command.

Source code for several useful extensions can be found in the
ext/misc
subdirectory of the SQLite source tree.  You can use these extensions
as-is, or as a basis for creating your own custom extensions to address
your own particular needs.


c2: Command Line Shell For SQLite
c3: 13. Cryptographic Hashes Of Database Content
c5: cli.html#cryptographic_hashes_of_database_content
c4:
The ".sha3sum" dot-command computes a
SHA3 hash of the content
of the database.  To be clear, the hash is computed over the database content,
not its representation on disk.  This means, for example, that a VACUUM
or similar data-preserving transformation does not change the hash.

The ".sha3sum" command supports options "--sha3-224", "--sha3-256", 
"--sha3-384", and "--sha3-512" to define which variety of SHA3 to use
for the hash.  The default is SHA3-256.

The database schema (in the sqlite_schema table) is not normally
included in the hash, but can be added by the "--schema" option.

The ".sha3sum" command takes a single optional argument which is a
LIKE pattern.  If this option is present, only tables whose names match
the LIKE pattern will be hashed.

The ".sha3sum" command is implemented with the help of the
extension function "sha3_query()"
that is included with the command-line shell.


c2: Command Line Shell For SQLite
c3: 14. Database Content Self-Tests
c5: cli.html#database_content_self_tests
c4:
The ".selftest" command attempts to verify that a database is
intact and is not corrupt.  
The .selftest command looks for a table in schema named "selftest"
and defined as follows:

CREATE TABLE selftest(
  tno INTEGER PRIMARY KEY,  -- Test number
  op TEXT,                  -- 'run' or 'memo'
  cmd TEXT,                 -- SQL command to run, or text of "memo"
  ans TEXT                  -- Expected result of the SQL command
);


The .selftest command reads the rows of the selftest table in
selftest.tno order.
For each 'memo' row, it writes the text in 'cmd' to the output.  For
each 'run' row, it runs the 'cmd' text as SQL and compares the result
to the value in 'ans', and shows an error message if the results differ.

If there is no selftest table, the ".selftest" command runs
PRAGMA integrity_check.

The ".selftest --init" command creates the selftest table if it
does not already exists, then appends entries that check the SHA3
hash of the content of all tables.  Subsequent runs of ".selftest"
will verify that the database has not been changed in any way.  To
generate tests to verify that a subset of the tables is unchanged,
simply run ".selftest --init" then DELETE the selftest rows that
refer to tables that are not constant.


c2: Command Line Shell For SQLite
c3: 15. SQLite Archive Support
c5: cli.html#sqlite_archive_support
c4:
The ".archive" dot-command and the "-A" command-line option
provide built-in support for the 
SQLite Archive format. The interface is similar to
that of the "tar" command on unix systems. Each invocation of the ".ar"
command must specify a single command option. The following commands
are available for ".archive":


  OptionLong&nbsp;OptionPurpose
  -c--createCreate a new archive containing specified files.
  -x--extractExtract specified files from archive.
  -i--insertAdd files to existing archive.
  -r--removeRemove files from the archive.
  -t--listList the files in the archive.
  -u--updateAdd files to existing archive if they have changed.


As well as the command option, each invocation of ".ar" may specify
one or more modifier options. Some modifier options require an argument,
some do not. The following modifier options are available:


  OptionLong&nbsp;OptionPurpose
  -v--verboseList each file as it is processed.
  -f FILE--file FILEIf specified, use file FILE as the
  archive. Otherwise, assume that the current "main" database is the 
  archive to be operated on.
  -a FILE--append FILELike --file, use file FILE as the
  archive, but open the file using the 
  apndvfs VFS so that
  the archive will be appended to the end of FILE if FILE already exists.
  -C DIR--directory DIRIf specified, interpret all relative
  paths as relative to DIR, instead of the current working directory.
  -g--globUse glob(Y,X) to match arguments
  against names in the archive.
  -n--dryrunShow the SQL that would be run to carry out the
                       archive operation, but do not actually change anything.
  ----All subsequent command line words are command arguments,
  not options.



For command-line usage, add the short style command-line options immediately
following the "-A", without an intervening space.  All subsequent arguments
are considered to be part of the .archive command.  For example, the following 
commands are equivalent:

sqlite3 new_archive.db -Acv file1 file2 file3
sqlite3 new_archive.db ".ar -cv file1 file2 file3"



Long and short style options may be mixed. For example, the following are
equivalent:

-- Two ways to create a new archive named "new_archive.db" containing
-- files "file1", "file2" and "file3".
.ar -c --file new_archive.db file1 file2 file3
.ar -f new_archive.db --create file1 file2 file3


Alternatively, the first argument following to ".ar" may be the concatenation
of the short form of all required options (without the "-" characters). In 
this case arguments for options requiring them are read from the command line
next, and any remaining words are considered command arguments. For example:

-- Create a new archive "new_archive.db" containing files "file1" and
-- "file2" from directory "dir1".
.ar cCf dir1 new_archive.db file1 file2 file3


c2: Command Line Shell For SQLite
c3: 15.1. SQLite Archive Create Command
c5: cli.html#_sqlite_archive_create_command_
c4:
Create a new archive, overwriting any existing archive (either in the current
"main" db or in the file specified by a --file option). Each argument following
the options is a file to add to the archive. Directories are imported
recursively. See above for examples.


c2: Command Line Shell For SQLite
c3: 15.2. SQLite Archive Extract Command
c5: cli.html#_sqlite_archive_extract_command_
c4:
Extract files from the archive (either to the current working directory or
to the directory specified by a --directory option). 
Files or directories whose names match the arguments,
as affected by the --glob option, are extracted. 
Or, if no arguments follow the options, all files and directories are extracted.
Any specified directories are extracted recursively. It is an error if any
specified names or match patterns cannot be found in the archive.

-- Extract all files from the archive in the current "main" db to the
-- current working directory. List files as they are extracted. 
.ar --extract --verbose

-- Extract file "file1" from archive "ar.db" to directory "dir1".
.ar fCx ar.db dir1 file1

-- Extract files with ".h" extension to directory "headers".
.ar -gCx headers *.h


c2: Command Line Shell For SQLite
c3: 15.3. SQLite Archive List Command
c5: cli.html#_sqlite_archive_list_command_
c4:
List the contents of the archive. If no arguments are specified, then all
files are listed. Otherwise, only those which match the arguments,
as affected by the --glob option, are listed. Currently,
the --verbose option does not change the behaviour of this command. That may
change in the future.

-- List contents of archive in current "main" db..
.ar --list


c2: Command Line Shell For SQLite
c3: 15.4. SQLite Archive Insert And Update Commands
c5: cli.html#_sqlite_archive_insert_and_update_commands_
c4:
The --update and --insert commands work like --create command, except that 
they do not delete the current archive before commencing. New versions of
files silently replace existing files with the same names, but otherwise
the initial contents of the archive (if any) remain intact.

 For the --insert command, all files listed are inserted into the archive.
For the --update command, files are only inserted if they do not previously
exist in the archive, or if their "mtime" or "mode" is different from what
is currently in the archive.

 Compatibility node:  Prior to SQLite version 3.28.0 (2019-04-16) only
the --update option was supported but that option worked like --insert in that
it always reinserted every file regardless of whether or not it had changed.


c2: Command Line Shell For SQLite
c3: 15.5. SQLite Archive Remove Command
c5: cli.html#_sqlite_archive_remove_command_
c4:
The --remove command deletes files and directories which match the
provided arguments (if any) as affected by the --glob option.
It is an error to provide arguments which match nothing in the archive.


c2: Command Line Shell For SQLite
c3: 15.6. Operations On ZIP Archives
c5: cli.html#_operations_on_zip_archives_
c4:
If FILE is a ZIP archive rather than an SQLite Archive, the ".archive"
command and the "-A" command-line option still work.  This is accomplished
using of the zipfile extension.
Hence, the following commands are roughly equivalent,
differing only in output formatting:


  Traditional CommandEquivalent sqlite3.exe Command
  unzip archive.zipsqlite3 -Axf archive.zip
  unzip -l archive.zipsqlite3 -Atvf archive.zip
  zip -r archive2.zip dirsqlite3 -Acf archive2.zip dir


c2: Command Line Shell For SQLite
c3: 15.7. SQL Used To Implement SQLite Archive Operations
c5: cli.html#_sql_used_to_implement_sqlite_archive_operations_
c4:
The various SQLite Archive Archive commands are implemented using SQL statements.
Application developers can easily add SQLite Archive Archive reading and writing
support to their own projects by running the appropriate SQL.

To see what SQL statements are used to implement an SQLite Archive
operation, add the --dryrun or -n option.  This causes the SQL to be
displayed but inhibits the execution of the SQL.

The SQL statements used to implement SQLite Archive operations make use of
various loadable extensions.  These extensions are all available in
the SQLite source tree in the
ext/misc/ subfolder.
The extensions needed for full SQLite Archive support include:



fileio.c &mdash;
This extension adds SQL functions readfile() and writefile() for
reading and writing content from files on disk.  The fileio.c
extension also includes fsdir() table-valued function for listing
the contents of a directory and the lsmode() function for converting
numeric st_mode integers from the stat() system call into human-readable
strings after the fashion of the "ls -l" command.


sqlar.c &mdash;
This extension adds the sqlar_compress() and sqlar_uncompress()
functions that are needed to compress and uncompress file content
as it is inserted and extracted from an SQLite Archive.


zipfile.c &mdash;
This extension implements the "zipfile(FILE)" table-valued function
which is used to read ZIP archives.  This extension is only needed
when reading ZIP archives instead of SQLite archives.


appendvfs.c &mdash;
This extension implements a new VFS that allows an SQLite database
to be appended to some other file, such as an executable.  This
extension is only needed if the --append option to the .archive
command is used.


c2: Command Line Shell For SQLite
c3: 16. SQL Parameters
c5: cli.html#sql_parameters
c4:
SQLite allows bound parameters to appear in an SQL statement anywhere
that a literal value is allowed.  The values for these parameters are set
using the sqlite3_bind_...() family of APIs.

Parameters can be either named or unnamed.  An unnamed parameter is a single
question mark ("?").  Named parameters are a "?" followed immediately by a number
(ex: "?15" or "?123") or one of the characters "$", ":", or "@" followed by an
alphanumeric name (ex: "$var1", ":xyz", "@bingo").

This command-line shell leaves unnamed parameters unbound, meaning that they
will have a value of an SQL NULL, but named parameters might be assigned values.
If there exists a TEMP table named "sqlite_parameters" with a schema like this:

CREATE TEMP TABLE sqlite_parameters(
  key TEXT PRIMARY KEY,
  value
) WITHOUT ROWID;


And if there is an entry in that table where the key column exactly matches
the name of parameter (including the initial "?", "$", ":", or "@" character)
then the parameter is assigned the value of the value column.  If no entry exists,
the parameter defaults to NULL.

The ".parameter" command exists to simplify managing this table.  The
".parameter init" command (often abbreviated as just ".param init") creates
the temp.sqlite_parameters table if it does not already exist.  The ".param list"
command shows all entries in the temp.sqlite_parameters table.  The ".param clear"
command drops the temp.sqlite_parameters table.  The ".param set KEY VALUE" and
".param unset KEY" commands create or delete entries from the 
temp.sqlite_parameters table.

The VALUE passed to ".param set KEY VALUE" can be either a SQL literal
or any other SQL expression or query which can be evaluated to yield a value.
This allows values of differing types to be set.
If such evaluation fails, the provided VALUE is instead quoted and inserted
as text.
Because such initial evaluation may or may not fail depending upon
the VALUE content, the reliable way to get a text value is to enclose it
with single-quotes protected from the above-described command-tail parsing.
For example, (unless one intends a value of -1365):
.parameter init
.parameter set @phoneNumber "'202-456-1111'"

Note that the double-quotes serve to protect the single-quotes
and ensure that the quoted text is parsed as one argument.

The temp.sqlite_parameters table only provides values for parameters in the
command-line shell.  The temp.sqlite_parameter table has no effect on queries
that are run directly using the SQLite C-language API.  Individual applications
are expected to implement their own parameter binding.  You can search for 
"sqlite_parameters" in the 
command-line shell source code
to see how the command-line shell does parameter binding, and use that as
a hint for how to implement it yourself.


c2: Command Line Shell For SQLite
c3: 17. Index Recommendations (SQLite Expert)
c5: cli.html#index_recommendations_sqlite_expert_
c4:
Note: This command is experimental. It may be removed or the 
interface modified in incompatible ways at some point in the future.

For most non-trivial SQL databases, the key to performance is creating
the right SQL indexes. In this context "the right SQL indexes" means those
that cause the queries that an application needs to optimize run fast. The
".expert" command can assist with this by proposing indexes that might
assist with specific queries, were they present in the database.

The ".expert" command is issued first, followed by the SQL query 
on a separate line. For example, consider the following session:

sqlite&gt; CREATE TABLE x1(a, b, c);                  -- Create table in database 
sqlite&gt; .expert
sqlite&gt; SELECT * FROM x1 WHERE a=? AND b&gt;?;        -- Analyze this SELECT 
CREATE INDEX x1_idx_000123a7 ON x1(a, b);

0|0|0|SEARCH TABLE x1 USING INDEX x1_idx_000123a7 (a=? AND b&gt;?)

sqlite&gt; CREATE INDEX x1ab ON x1(a, b);             -- Create the recommended index 
sqlite&gt; .expert
sqlite&gt; SELECT * FROM x1 WHERE a=? AND b&gt;?;        -- Re-analyze the same SELECT 
(no new indexes)

0|0|0|SEARCH TABLE x1 USING INDEX x1ab (a=? AND b&gt;?)


In the above, the user creates the database schema (a single table - "x1"),
and then uses the ".expert" command to analyze a query, in this case 
"SELECT * FROM x1 WHERE a=? AND b&gt;?". The shell tool recommends that the
user create a new index (index "x1_idx_000123a7") and outputs the plan
that the query would use in EXPLAIN QUERY PLAN format. The user then creates
an index with an equivalent schema and runs the analysis on the same query
again. This time the shell tool does not recommend any new indexes, and 
outputs the plan that SQLite will use for the query given the existing 
indexes.

The ".expert" command accepts the following options:


 Option  Purpose
 &#8209;&#8209;verbose
     If present, output a more verbose report for each query analyzed.
 &#8209;&#8209;sample&nbsp;PERCENT 
     This parameter defaults to 0, causing the ".expert" command to
         recommend indexes based on the query and database schema alone.
         This is similar to the way the SQLite query planner selects
         indexes for queries if the user has not run the ANALYZE command
         on the database to generate data distribution statistics. 
         
         If this option is passed a non-zero argument, the ".expert" command
         generates similar data distribution statistics for all indexes
         considered based on PERCENT percent of the rows currently stored in
         each database table. For databases with unusual data distributions,
         this may lead to better index recommendations, particularly if the
         application intends to run ANALYZE.
         
         For small databases and modern CPUs, there is usually no reason not
         to pass "--sample 100". However, gathering data distribution
         statistics can be expensive for large database tables. If the
         operation is too slow, try passing a smaller value for the --sample
         option.


The functionality described in this section may be integrated into other
applications or tools using the 

SQLite expert extension code.

A database schema which incorporate SQL custom functions made available
via the extension load mechanism may need special provision to work with
the .expert feature. Because the feature uses additional connections to
implement its functionality, those custom functions must be made available
to those additional connections. This can be done by means of the extension
load/usage options described at 

Automatically Load Statically Linked Extensions
and 
Persistent Loadable Extensions.


c2: Command Line Shell For SQLite
c3: 18. Working With Multiple Database Connections
c5: cli.html#working_with_multiple_database_connections
c4:
Beginning with version 3.37.0 (2021-11-27), the CLI has the ability to
hold multiple database connections open at once.  Only one database connection
is active at a time.  The inactive connections are still open but are idle.


Use the ".connection" dot-command (often abbreviated as just ".conn") to see a
list of database connections and an indication of which one is currently active.
Each database connection is identified by an integer between 0 and 9.  (There
can be at most 10 simultaneously open connections.)  Change to another database
connection, creating it if it does not already exist, by typing the ".conn"
command followed by its number.  Close a database connection by typing
".conn close N" where N is the connection number.


Though the underlying SQLite database connections are completely independent
of one another, many of the CLI settings, such as the output format, are
shared across all database connections.  Thus, changing the output mode in
one connection will change it in them all.  On the other hand, some
dot-commands such as .open only affect the current connection.


c2: Command Line Shell For SQLite
c3: 19. Miscellaneous Extension Features
c5: cli.html#miscellaneous_extension_features
c4:
The CLI is built with several SQLite extensions that are not
included with the SQLite library. A few add features
not described in the preceding sections, namely:

the UINT collating sequence which treats
unsigned integers embedded in text according to
their value, along with other text, for ordering;
decimal arithmetic as provided by the decimal extension;
the generate_series() table-valued function; and
support for POSIX extended regular expressions
bound to the REGEXP operator.


c2: Command Line Shell For SQLite
c3: 20. Other Dot Commands
c5: cli.html#other_dot_commands
c4:
There are many other dot-commands available in the command-line
shell.  See the ".help" command for a complete list for any particular
version and build of SQLite.


c2: Command Line Shell For SQLite
c3: 21. Using sqlite3 in a shell script
c5: cli.html#using_sqlite3_in_a_shell_script
c4:
One way to use sqlite3 in a shell script is to use "echo" or
"cat" to generate a sequence of commands in a file, then invoke sqlite3
while redirecting input from the generated command file.  This
works fine and is appropriate in many circumstances.  But as
an added convenience, sqlite3 allows a single SQL command to be
entered on the command line as a second argument after the
database name.  When the sqlite3 program is launched with two
arguments, the second argument is passed to the SQLite library
for processing, the query results are printed on standard output
in list mode, and the program exits.  This mechanism is designed
to make sqlite3 easy to use in conjunction with programs like
"awk".  For example:

$ sqlite3 ex1 'select * from tbl1' \
&gt;  | awk '{printf "&lt;tr&gt;&lt;td&gt;%s&lt;td&gt;%s\n",$1,$2 }'
&lt;tr&gt;&lt;td&gt;hello&lt;td&gt;10
&lt;tr&gt;&lt;td&gt;goodbye&lt;td&gt;20
$


c2: Command Line Shell For SQLite
c3: 22. Marking The End Of An SQL Statement
c5: cli.html#marking_the_end_of_an_sql_statement
c4:
SQLite commands are normally terminated by a semicolon.  In the CLI
you can also use the word "GO" (case-insensitive) or a slash character 
"/" on a line by itself to end a command.  These are used by SQL Server 
and Oracle, respectively, and are supported by the SQLite CLI for
compatibility.  These won't work in sqlite3_exec(), 
because the CLI translates these inputs into a semicolon before passing 
them down into the SQLite core.


c2: Command Line Shell For SQLite
c3: 23. Command-line Options
c5: cli.html#command_line_options
c4:
There are many command-line options available to the CLI.  Use the --help
command-line option to see a list:

$ sqlite3 --help
Usage: ./sqlite3 &#91;OPTIONS&#93; FILENAME &#91;SQL&#93;
FILENAME is the name of an SQLite database. A new database is created
if the file does not previously exist.
OPTIONS include:
   -A ARGS...           run ".archive ARGS" and exit
   -append              append the database to the end of the file
   -ascii               set output mode to 'ascii'
   -bail                stop after hitting an error
   -batch               force batch I/O
   -box                 set output mode to 'box'
   -column              set output mode to 'column'
   -cmd COMMAND         run "COMMAND" before reading stdin
   -csv                 set output mode to 'csv'
   -deserialize         open the database using sqlite3_deserialize()
   -echo                print commands before execution
   -init FILENAME       read/process named file
   -&#91;no&#93;header          turn headers on or off
   -help                show this message
   -html                set output mode to HTML
   -interactive         force interactive I/O
   -json                set output mode to 'json'
   -line                set output mode to 'line'
   -list                set output mode to 'list'
   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory
   -markdown            set output mode to 'markdown'
   -maxsize N           maximum size for a --deserialize database
   -memtrace            trace all memory allocations and deallocations
   -mmap N              default mmap size set to N
   -newline SEP         set output row separator. Default: '\n'
   -nofollow            refuse to open symbolic links to database files
   -nonce STRING        set the safe-mode escape nonce
   -nullvalue TEXT      set text string for NULL values. Default ''
   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory
   -quote               set output mode to 'quote'
   -readonly            open the database read-only
   -safe                enable safe-mode
   -separator SEP       set output column separator. Default: '|'
   -stats               print memory stats before each finalize
   -table               set output mode to 'table'
   -tabs                set output mode to 'tabs'
   -version             show SQLite version
   -vfs NAME            use NAME as the default VFS
   -zip                 open the file as a ZIP Archive


The CLI is flexible regarding command-line option formatting.
Either one or two leading "-" characters are permitted.
Thus "-box" and "--box" mean the same thing.
Command-line options are processed from left to right.
Hence a "--box" option will override a prior "--quote" option.


Most of the command-line options are self-explanatory, but a few merit additional
discussion below.


c2: Command Line Shell For SQLite
c3: 23.1. The --safe command-line option
c5: cli.html#the_safe_command_line_option
c4:
The --safe command-line option attempts to disable all features of the CLI that
might cause any changes to the host computer other than changes to the specific database
file named on the command-line.  The idea is that if you receive a large SQL script
from an unknown or untrusted source, you can run that script to see what it does without
risking an exploit by using the --safe option.  The --safe option disables (among other
things):


 The .open command, unless the --hexdb option is used or the filename is ":memory:".
     This prevents the script from reading or writing any database files not named on
     the original command-line.
 The ATTACH SQL command.
 SQL functions that have potentially harmful side-effects, such as
     edit(), fts3_tokenizer(), load_extension(), readfile() and writefile().
 The .archive command.
 The .backup and .save commands.
 The .import command.
 The .load command.
 The .log command.
 The .shell and .system commands.
 The .excel, .once and .output commands.
 Other commands that can have deleterious side effects.



Basically, any feature of the CLI that reads or writes from a file on disk other
than the main database file is disabled.


c2: Command Line Shell For SQLite
c3: 23.1.1. Bypassing --safe restrictions for specific commands
c5: cli.html#bypassing_safe_restrictions_for_specific_commands
c4:
If the "--nonce NONCE" option is also included on the command-line, for some
large and arbitrary NONCE string, then the ".nonce NONCE" command (with the
same large nonce string) will permit the next SQL statement or dot-command
to bypass the --safe restrictions.

Suppose you want to run a suspicious script and the script requires one or
two of the features that --safe normally disables.  For example, suppose it
needs to ATTACH one additional database.  Or suppose the script needs to load
a specific extension. This can be accomplished by preceding the (carefully
audited) ATTACH statement or the ".load" command with an appropriate ".nonce"
command and supplying the same nonce value using the "--nonce" command-line
option.  Those specific commands will then be allowed to execute normally,
but all other unsafe commands will still be restricted.

The use of ".nonce" is dangerous in the sense that a mistake can allow a
hostile script to damage your system.  Therefore, use ".nonce" carefully,
sparingly, and as a last resort when there are no other ways to get a
script to run under --safe mode.


c2: Command Line Shell For SQLite
c3: 24. Compiling the sqlite3 program from sources
c5: cli.html#compiling_the_sqlite3_program_from_sources
c4:
To compile the command-line shell on unix systems and on Windows with MinGW,
the usual configure-make command works:

sh configure; make



The configure-make works whether you are building from the canonical sources
from the source tree, or from an amalgamated bundle.  There are few
dependencies.  When building from canonical sources, a working 
tclsh is required.
If using an amalgamation bundle, all the preprocessing work normally 
done by tclsh will have already been carried out and only normal build
tools are required.


A working zlib compression library is
needed in order for the .archive command to operate.


On Windows with MSVC, use nmake with the Makefile.msc:

nmake /f Makefile.msc



For correct operation of the .archive command, make a copy of the
zlib source code into the compat/zlib subdirectory 
of the source tree and compile this way:

nmake /f Makefile.msc USE_ZLIB=1


c2: Command Line Shell For SQLite
c3: 24.1. Do-It-Yourself Builds
c5: cli.html#_do_it_yourself_builds_
c4:
The source code to the sqlite3 command line interface is in a single
file named "shell.c".  The shell.c source file is generated from other
sources, but most of the code for shell.c can be found in
src/shell.c.in.
(Regenerate shell.c by typing "make shell.c" from the canonical source tree.)
Compile the shell.c file (together
with the sqlite3 library source code) to generate
the executable.  For example:

gcc -o sqlite3 shell.c sqlite3.c -ldl -lpthread -lz -lm



The following additional compile-time options are recommended in order to
provide a full-featured command-line shell:


 -DSQLITE_THREADSAFE=0
 -DSQLITE_ENABLE_EXPLAIN_COMMENTS
 -DSQLITE_HAVE_ZLIB
 -DSQLITE_INTROSPECTION_PRAGMAS
 -DSQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
 -DSQLITE_ENABLE_STMTVTAB
 -DSQLITE_ENABLE_DBPAGE_VTAB
 -DSQLITE_ENABLE_DBSTAT_VTAB
 -DSQLITE_ENABLE_OFFSET_SQL_FUNC
 -DSQLITE_ENABLE_JSON1
 -DSQLITE_ENABLE_RTREE
 -DSQLITE_ENABLE_FTS4
 -DSQLITE_ENABLE_FTS5


c2: The SQLite Query Optimizer Overview
c3: 1. Introduction
c5: optoverview.html#introduction
c4:
This document provides an overview of how the query planner and optimizer
  for SQLite works.



  Given a single SQL statement, there might be dozens, hundreds, or even
  thousands of ways to implement that statement, depending on the complexity
  of the statement itself and of the underlying database schema.  The 
  task of the query planner is to select an algorithm from among the many
  choices that provides the answer with a minimum of disk I/O and CPU
  overhead.



  Additional background information is available in the
  indexing tutorial document.



  With release 3.8.0 (2013-08-26),
  the SQLite query planner was reimplemented as the
  Next Generation Query Planner or "NGQP".  All of the features, techniques,
  and algorithms described in this document are applicable to both the
  pre-3.8.0 legacy query planner and to the NGQP.  For further information on
  how the NGQP differs from the legacy query planner, see the 
  detailed description of the NGQP.


c2: The SQLite Query Optimizer Overview
c3: 2. WHERE Clause Analysis
c5: optoverview.html#where_clause_analysis
c4:
The WHERE clause on a query is broken up into "terms" where each term
  is separated from the others by an AND operator.
  If the WHERE clause is composed of constraints separated by the OR
  operator then the entire clause is considered to be a single "term"
  to which the OR-clause optimization is applied.


  All terms of the WHERE clause are analyzed to see if they can be
  satisfied using indexes.
  To be usable by an index a term must be of one of the following
  forms:


  column = expression
  column IS expression
  column &gt; expression
  column &gt;= expression
  column &lt; expression
  column &lt;= expression
  expression = column
  expression &gt; column
  expression &gt;= column
  expression &lt; column
  expression &lt;= column
  column IN (expression-list)
  column IN (subquery)
  column IS NULL



  If an index is created using a statement like this:

CREATE INDEX idx_ex1 ON ex1(a,b,c,d,e,...,y,z);



  Then the index might be used if the initial columns of the index
  (columns a, b, and so forth) appear in WHERE clause terms.
  The initial columns of the index must be used with
  the = or IN or IS operators.  
  The right-most column that is used can employ inequalities.  
  For the right-most
  column of an index that is used, there can be up to two inequalities
  that must sandwich the allowed values of the column between two extremes.


  It is not necessary for every column of an index to appear in a
  WHERE clause term in order for that index to be used. 
  However, there cannot be gaps in the columns of the index that are used.
  Thus for the example index above, if there is no WHERE clause term
  that constrains column c, then terms that constrain columns a and b can
  be used with the index but not terms that constrain columns d through z.
  Similarly, index columns will not normally be used (for indexing purposes)
  if they are to the right of a 
  column that is constrained only by inequalities.
  (See the skip-scan optimization below for the exception.)


  In the case of indexes on expressions, whenever the word "column" is
  used in the foregoing text, one can substitute "indexed expression"
  (meaning a copy of the expression that appears in the CREATE INDEX
  statement) and everything will work the same.


c2: The SQLite Query Optimizer Overview
c3: 2.1. Index Term Usage Examples
c5: optoverview.html#index_term_usage_examples
c4:
For the index above and WHERE clause like this:

... WHERE a=5 AND b IN (1,2,3) AND c IS NULL AND d='hello'


  The first four columns a, b, c, and d of the index would be usable since
  those four columns form a prefix of the index and are all bound by
  equality constraints.


  For the index above and WHERE clause like this:

... WHERE a=5 AND b IN (1,2,3) AND c>12 AND d='hello'


  Only columns a, b, and c of the index would be usable.  The d column
  would not be usable because it occurs to the right of c and c is
  constrained only by inequalities.


  For the index above and WHERE clause like this:

... WHERE a=5 AND b IN (1,2,3) AND d='hello'


  Only columns a and b of the index would be usable.  The d column
  would not be usable because column c is not constrained and there can
  be no gaps in the set of columns that usable by the index.


  For the index above and WHERE clause like this:

... WHERE b IN (1,2,3) AND c NOT NULL AND d='hello'


  The index is not usable at all because the left-most column of the
  index (column "a") is not constrained.  Assuming there are no other
  indexes, the query above would result in a full table scan.


  For the index above and WHERE clause like this:

... WHERE a=5 OR b IN (1,2,3) OR c NOT NULL OR d='hello'


  The index is not usable because the WHERE clause terms are connected
  by OR instead of AND. This query would result in a full table scan.
  However, if three additional indexes where added that contained columns
  b, c, and d as their left-most columns, then the
  OR-clause optimization might apply.


c2: The SQLite Query Optimizer Overview
c3: 3. The BETWEEN Optimization
c5: optoverview.html#the_between_optimization
c4:
If a term of the WHERE clause is of the following form:


  expr1 BETWEEN expr2 AND expr3


  Then two "virtual" terms are added as follows:


  expr1 &gt;= expr2 AND expr1 &lt;= expr3


  Virtual terms are used for analysis only and do not cause any byte-code
  to be generated.
  If both virtual terms end up being used as constraints on an index,
  then the original BETWEEN term is omitted and the corresponding test
  is not performed on input rows.
  Thus if the BETWEEN term ends up being used as an index constraint
  no tests are ever performed on that term.
  On the other hand, the
  virtual terms themselves never causes tests to be performed on
  input rows.
  Thus if the BETWEEN term is not used as an index constraint and
  instead must be used to test input rows, the expr1 expression is
  only evaluated once.


c2: The SQLite Query Optimizer Overview
c3: 4. OR Optimizations
c5: optoverview.html#or_optimizations
c4:
WHERE clause constraints that are connected by OR instead of AND can
  be handled in two different ways.
  If a term consists of multiple subterms containing a common column
  name and separated by OR, like this:


  column = expr1 OR column = expr2 OR column = expr3 OR ...


  Then that term is rewritten as follows:


  column IN (expr1,expr2,expr3,...)


  The rewritten term then might go on to constrain an index using the
  normal rules for IN operators.  Note that column must be
  the same column in every OR-connected subterm,
  although the column can occur on either the left or the right side of
  the = operator.


  If and only if the previously described conversion of OR to an IN operator
  does not work, the second OR-clause optimization is attempted.
  Suppose the OR clause consists of multiple subterms as follows:


  expr1 OR expr2 OR expr3


  Individual subterms might be a single comparison expression like
  a=5 or x&gt;y or they can be 
  LIKE or BETWEEN expressions, or a subterm
  can be a parenthesized list of AND-connected sub-subterms.
  Each subterm is analyzed as if it were itself the entire WHERE clause
  in order to see if the subterm is indexable by itself.
  If every subterm of an OR clause is separately indexable
  then the OR clause might be coded such that a separate index is used
  to evaluate each term of the OR clause.  One way to think about how
  SQLite uses separate indexes for each OR clause term is to imagine
  that the WHERE clause where rewritten as follows:


  rowid IN (SELECT rowid FROM table WHERE expr1
            UNION SELECT rowid FROM table WHERE expr2
            UNION SELECT rowid FROM table WHERE expr3)


  The rewritten expression above is conceptual; WHERE clauses containing
  OR are not really rewritten this way.
  The actual implementation of the OR clause uses a mechanism that is
  more efficient and that works even for WITHOUT ROWID tables or 
  tables in which the "rowid" is inaccessible.  Nevertheless,
  the essence of the implementation is captured by the statement
  above:  Separate indexes are used to find candidate result rows
  from each OR clause term and the final result is the union of
  those rows.


  Note that in most cases, SQLite will only use a single index for each
  table in the FROM clause of a query.  The second OR-clause optimization
  described here is the exception to that rule.  With an OR-clause,
  a different index might be used for each subterm in the OR-clause.


  For any given query, the fact that the OR-clause optimization described
  here can be used does not guarantee that it will be used.
  SQLite uses a cost-based query planner that estimates the CPU and
  disk I/O costs of various competing query plans and chooses the plan
  that it thinks will be the fastest.  If there are many OR terms in
  the WHERE clause or if some of the indexes on individual OR-clause 
  subterms are not very selective, then SQLite might decide that it is
  faster to use a different query algorithm, or even a full-table scan.
  Application developers can use the
  EXPLAIN QUERY PLAN prefix on a statement to get a
  high-level overview of the chosen query strategy.


c2: The SQLite Query Optimizer Overview
c3: 5. The LIKE Optimization
c5: optoverview.html#the_like_optimization
c4:
A WHERE-clause term that uses the LIKE or GLOB operator
  can sometimes be used with an index to do a range search, 
  almost as if the LIKE or GLOB were an alternative to a BETWEEN
  operator.
  There are many conditions on this optimization:


  
  The right-hand side of the LIKE or GLOB must be either a string literal
      or a parameter bound to a string literal
      that does not begin with a wildcard character.
  It must not be possible to make the LIKE or GLOB operator true by
      having a numeric value (instead of a string or blob) on the
      left-hand side. This means that either:
      
       the left-hand side of the LIKE or GLOB operator is the name
           of an indexed column with TEXT affinity, or
       the right-hand side pattern argument does not begin with a
           minus sign ("-") or a digit.
      
      This constraint arises from the fact that numbers do not sort in
      lexicographical order.  For example: 9&lt;10 but '9'&gt;'10'.
  The built-in functions used to implement LIKE and GLOB must not
      have been overloaded using the sqlite3_create_function() API.
  For the GLOB operator, the column must be indexed using the 
      built-in BINARY collating sequence.
  For the LIKE operator, if case_sensitive_like mode is enabled then
      the column must indexed using BINARY collating sequence, or if
      case_sensitive_like mode is disabled then the column must indexed
      using built-in NOCASE collating sequence.
  If the ESCAPE option is used, the ESCAPE character must be ASCII,
      or a single-byte character in UTF-8.
  


  The LIKE operator has two modes that can be set by a
  pragma.  The
  default mode is for LIKE comparisons to be insensitive to differences
  of case for latin1 characters.  Thus, by default, the following
  expression is true:

'a' LIKE 'A'


  If the case_sensitive_like pragma is enabled as follows:

PRAGMA case_sensitive_like=ON;


  Then the LIKE operator pays attention to case and the example above would
  evaluate to false.  Note that case insensitivity only applies to
  latin1 characters - basically the upper and lower case letters of English
  in the lower 127 byte codes of ASCII.  International character sets
  are case sensitive in SQLite unless an application-defined
  collating sequence and like() SQL function are provided that
  take non-ASCII characters into account.
  If an application-defined collating sequence and/or like() SQL
  function are provided, the LIKE optimization described here will never
  be taken.


  The LIKE operator is case insensitive by default because this is what
  the SQL standard requires.  You can change the default behavior at
  compile time by using the SQLITE_CASE_SENSITIVE_LIKE command-line option
  to the compiler.


  The LIKE optimization might occur if the column named on the left of the
  operator is indexed using the built-in BINARY collating sequence and
  case_sensitive_like is turned on.  Or the optimization might occur if
  the column is indexed using the built-in NOCASE collating sequence and the 
  case_sensitive_like mode is off.  These are the only two combinations
  under which LIKE operators will be optimized.


  The GLOB operator is always case sensitive.  The column on the left side
  of the GLOB operator must always use the built-in BINARY collating sequence
  or no attempt will be made to optimize that operator with indexes.


  The LIKE optimization will only be attempted if
  the right-hand side of the GLOB or LIKE operator is either
  literal string or a parameter that has been bound
  to a string literal.  The string literal must not
  begin with a wildcard; if the right-hand side begins with a wildcard
  character then this optimization is not attempted.  If the right-hand side 
  is a parameter that is bound to a string, then this optimization is
  only attempted if the prepared statement containing the expression
  was compiled with sqlite3_prepare_v2() or sqlite3_prepare16_v2().
  The LIKE optimization is not attempted if the
  right-hand side is a parameter and the statement was prepared using
  sqlite3_prepare() or sqlite3_prepare16().


  Suppose the initial sequence of non-wildcard characters on the right-hand
  side of the LIKE or GLOB operator is x.  We are using a single 
  character to denote this non-wildcard prefix but the reader should
  understand that the prefix can consist of more than 1 character.
  Let y be the smallest string that is the same length as /x/ but which
  compares greater than x.  For example, if x is
  'hello' then
  y would be 'hellp'.
  The LIKE and GLOB optimizations consist of adding two virtual terms
  like this:


  column &gt;= x AND column &lt; y


  Under most circumstances, the original LIKE or GLOB operator is still
  tested against each input row even if the virtual terms are used to
  constrain an index.  This is because we do not know what additional
  constraints may be imposed by characters to the right
  of the x prefix.  However, if there is only a single
  global wildcard to the right of x, then the original LIKE or 
  GLOB test is disabled.
  In other words, if the pattern is like this:


  column LIKE x%
  column GLOB x*


  then the original LIKE or GLOB tests are disabled when the virtual
  terms constrain an index because in that case we know that all of the
  rows selected by the index will pass the LIKE or GLOB test.


  Note that when the right-hand side of a LIKE or GLOB operator is
  a parameter and the statement is prepared using sqlite3_prepare_v2()
  or sqlite3_prepare16_v2() then the statement is automatically reparsed
  and recompiled on the first sqlite3_step() call of each run if the binding
  to the right-hand side parameter has changed since the previous run.
  This reparse and recompile is essentially the same action that occurs
  following a schema change.  The recompile is necessary so that the query
  planner can examine the new value bound to the right-hand side of the
  LIKE or GLOB operator and determine whether or not to employ the
  optimization described above.


c2: The SQLite Query Optimizer Overview
c3: 6. The Skip-Scan Optimization
c5: optoverview.html#the_skip_scan_optimization
c4:
The general rule is that indexes are only useful if there are 
  WHERE-clause constraints on the left-most columns of the index.
  However, in some cases,
  SQLite is able to use an index even if the first few columns of
  the index are omitted from the WHERE clause but later columns 
  are included.



  Consider a table such as the following:

CREATE TABLE people(
  name TEXT PRIMARY KEY,
  role TEXT NOT NULL,
  height INT NOT NULL, -- in cm
  CHECK( role IN ('student','teacher') )
);
CREATE INDEX people_idx1 ON people(role, height);



  The people table has one entry for each person in a large
  organization.  Each person is either a "student" or a "teacher",
  as determined by the "role" field.  The table also records the height in
  centimeters of each person.  The role and height are indexed.
  Notice that the left-most column of the index is not very
  selective - it only contains two possible values.



  Now consider a query to find the names of everyone in the
  organization that is 180cm tall or taller:


SELECT name FROM people WHERE height>=180;



  Because the left-most column of the index does not appear in the
  WHERE clause of the query, one is tempted to conclude that the
  index is not usable here.  However, SQLite is able to use the index.
  Conceptually, SQLite uses the index as if the query were more
  like the following:


SELECT name FROM people
 WHERE role IN (SELECT DISTINCT role FROM people)
   AND height>=180;



  Or this:

SELECT name FROM people WHERE role='teacher' AND height>=180
UNION ALL
SELECT name FROM people WHERE role='student' AND height>=180;



  The alternative query formulations shown above are conceptual only.
  SQLite does not really transform the query. 
  The actual query plan is like this:
  SQLite locates the first possible value for "role", which it
  can do by rewinding the "people_idx1" index to the beginning and reading
  the first record.  SQLite stores this first "role" value in an
  internal variable that we will here call "$role".  Then SQLite
  runs a query like: "SELECT name FROM people WHERE role=$role AND height>=180".
  This query has an equality constraint on the left-most column of the
  index and so the index can be used to resolve that query.  Once
  that query is finished, SQLite then uses the "people_idx1" index to
  locate the next value of the "role" column, using code that is logically
  similar to "SELECT role FROM people WHERE role>$role LIMIT 1".
  This new "role" value overwrites the $role variable, and the process
  repeats until all possible values for "role" have been examined.


  We call this kind of index usage a "skip-scan" because the database
  engine is basically doing a full scan of the index but it optimizes the
  scan (making it less than "full") by occasionally skipping ahead to the
  next candidate value.


  SQLite might use a skip-scan on an index if it knows that the first
  one or more columns contain many duplication values.
  If there are too few duplicates
  in the left-most columns of the index, then it would
  be faster to simply step ahead to the next value, and thus do
  a full table scan, than to do a binary search on an index to locate
  the next left-column value.


  The only way that SQLite can know that there are many duplicates
  in the left-most columns of an index
  is if the ANALYZE command has been run
  on the database.
  Without the results of ANALYZE, SQLite has to guess at the "shape" of
  the data in the table, and the default guess is that there are an average
  of 10 duplicates for every value in the left-most column of the index.
  Skip-scan only becomes profitable (it only gets to be faster than
  a full table scan) when the number of duplicates is about 18 or more.
  Hence, a skip-scan is never used on a database that has not been analyzed.


c2: The SQLite Query Optimizer Overview
c3: 7. Joins
c5: optoverview.html#joins
c4:
The ON and USING clauses of an inner join are converted into additional
  terms of the WHERE clause prior to WHERE clause analysis described
  above in paragraph 2.0.
  Thus with SQLite, there is no computational
  advantage to use the newer SQL92 join syntax
  over the older SQL89 comma-join syntax.  They both end up accomplishing
  exactly the same thing on inner joins.


  For an OUTER JOIN the situation is more complex.  The following
  two queries are not equivalent:

SELECT * FROM tab1 LEFT JOIN tab2 ON tab1.x=tab2.y;
SELECT * FROM tab1 LEFT JOIN tab2 WHERE tab1.x=tab2.y;


  For an inner join, the two queries above would be identical.  However,
  special processing applies to the ON and USING clauses of an OUTER join:
  specifically, the constraints in an ON or USING clause do not apply if
  the right table of the join is on a null row, but the constraints do apply
  in the WHERE clause.  The net effect is that putting the ON or USING
  clause expressions for a LEFT JOIN in the WHERE clause effectively converts
  the query to an
  ordinary INNER JOIN - albeit an inner join that runs more slowly.


c2: The SQLite Query Optimizer Overview
c3: 7.1. Order of Tables in a Join
c5: optoverview.html#order_of_tables_in_a_join
c4:
The current implementation of 
  SQLite uses only loop joins.  That is to say, joins are implemented as
  nested loops.


  The default order of the nested loops in a join is for the left-most
  table in the FROM clause to form the outer loop and the right-most
  table to form the inner loop.
  However, SQLite will nest the loops in a different order if doing so
  will help it to select better indexes.


  Inner joins can be freely reordered.  However a left outer join is
  neither commutative nor associative and hence will not be reordered.
  Inner joins to the left and right of the outer join might be reordered
  if the optimizer thinks that is advantageous but the outer joins are
  always evaluated in the order in which they occur.


  SQLite treats the CROSS JOIN operator specially.
  The CROSS JOIN operator is commutative, in theory.  However, SQLite chooses to
  never reorder tables in a CROSS JOIN.  This provides a mechanism
  by which the programmer can force SQLite to choose a particular loop nesting
  order.  


  When selecting the order of tables in a join, SQLite uses an efficient
  polynomial-time algorithm.  Because of this,
  SQLite is able to plan queries with 50- or 60-way joins in a matter of
  microseconds


  Join reordering is automatic and usually works well enough that
  programmers do not have to think about it, especially if ANALYZE
  has been used to gather statistics about the available indexes,
  though occasionally some hints from the programmer are needed.
  Consider, for example, the following schema:

CREATE TABLE node(
   id INTEGER PRIMARY KEY,
   name TEXT
);
CREATE INDEX node_idx ON node(name);
CREATE TABLE edge(
   orig INTEGER REFERENCES node,
   dest INTEGER REFERENCES node,
   PRIMARY KEY(orig, dest)
);
CREATE INDEX edge_idx ON edge(dest,orig);


  The schema above defines a directed graph with the ability to store a
  name at each node. Now consider a query against this schema:

SELECT *
  FROM edge AS e,
       node AS n1,
       node AS n2
 WHERE n1.name = 'alice'
   AND n2.name = 'bob'
   AND e.orig = n1.id
   AND e.dest = n2.id;


  This query asks for is all information about edges that go from
  nodes labeled "alice" to nodes labeled "bob".
  The query optimizer in SQLite has basically two choices on how to
  implement this query.  (There are actually six different choices, but
  we will only consider two of them here.)
  Pseudocode below demonstrating these two choices.



Option 1:
foreach n1 where n1.name='alice' do:
  foreach n2 where n2.name='bob' do:
    foreach e where e.orig=n1.id and e.dest=n2.id
      return n1.*, n2.*, e.*
    end
  end
end



Option 2:
foreach n1 where n1.name='alice' do:
  foreach e where e.orig=n1.id do:
    foreach n2 where n2.id=e.dest and n2.name='bob' do:
      return n1.*, n2.*, e.*
    end
  end
end


  The same indexes are used to speed up every loop in both implementation
  options.
  The only difference in these two query plans is the order in which
  the loops are nested.


  So which query plan is better? It turns out that the answer depends on
  what kind of data is found in the node and edge tables.


  Let the number of alice nodes be M and the number of bob nodes be N.
  Consider two scenarios. In the first scenario, M and N are both 2 but
  there are thousands of edges on each node. In this case, option 1 is
  preferred. With option 1, the inner loop checks for the existence of
  an edge between a pair of nodes and outputs the result if found. 
  Because there are only 2 alice and bob nodes each, the inner loop
  only has to run four times and the query is very quick. Option 2 would
  take much longer here. The outer loop of option 2 only executes twice,
  but because there are a large number of edges leaving each alice node,
  the middle loop has to iterate many thousands of times. It will be
  much slower. So in the first scenario, we prefer to use option 1.


  Now consider the case where M and N are both 3500. Alice nodes are
  abundant.  This time suppose each of these nodes is connected by only one
  or two edges. Now option 2 is preferred. With option 2,
  the outer loop still has to run 3500 times, but the middle loop only
  runs once or twice for each outer loop and the inner loop will only
  run once for each middle loop, if at all. So the total number of
  iterations of the inner loop is around 7000. Option 1, on the other
  hand, has to run both its outer loop and its middle loop 3500 times
  each, resulting in 12 million iterations of the middle loop.
  Thus in the second scenario, option 2 is nearly 2000 times faster
  than option 1.


  So you can see that depending on how the data is structured in the table,
  either query plan 1 or query plan 2 might be better.  Which plan does
  SQLite choose by default?  As of version 3.6.18, without running ANALYZE,
  SQLite will choose option 2.
  If the ANALYZE command is run in order to gather statistics,
  a different choice might be made if the statistics indicate that the
  alternative is likely to run faster.


c2: The SQLite Query Optimizer Overview
c3: 7.2. Manual Control Of Query Plans Using SQLITE_STAT Tables
c5: optoverview.html#manual_control_of_query_plans_using_sqlite_stat_tables
c4:
SQLite provides the ability for advanced programmers to exercise control
  over the query plan chosen by the optimizer. One method for doing this
  is to fudge the ANALYZE results in the sqlite_stat1, 
  sqlite_stat3, and/or sqlite_stat4 tables.  This is not
  recommended for most situations.


c2: The SQLite Query Optimizer Overview
c3: 7.3. Manual Control of Query Plans using CROSS JOIN
c5: optoverview.html#manual_control_of_query_plans_using_cross_join
c4:
Programmers can force SQLite to use a particular loop nesting order
  for a join by using the CROSS JOIN operator instead of just JOIN, 
  INNER JOIN, NATURAL JOIN, or a "," join.  Though CROSS JOINs are
  commutative in theory, SQLite chooses to never reorder the tables in
  a CROSS JOIN.  Hence, the left table of a CROSS JOIN will always be
  in an outer loop relative to the right table.


  In the following query, the optimizer is free to reorder the 
  tables of FROM clause any way it sees fit:

SELECT *
  FROM node AS n1,
       edge AS e,
       node AS n2
 WHERE n1.name = 'alice'
   AND n2.name = 'bob'
   AND e.orig = n1.id
   AND e.dest = n2.id;


  In the following logically equivalent formulation of the same query,
  the substitution of "CROSS JOIN" for the "," means that the order
  of tables must be N1, E, N2.

SELECT *
  FROM node AS n1 CROSS JOIN
       edge AS e CROSS JOIN
       node AS n2
 WHERE n1.name = 'alice'
   AND n2.name = 'bob'
   AND e.orig = n1.id
   AND e.dest = n2.id;


  In the latter query, the query plan must be 
  option 2.  Note that
  you must use the keyword "CROSS" in order to disable the table reordering
  optimization; INNER JOIN, NATURAL JOIN, JOIN, and other similar
  combinations work just like a comma join in that the optimizer is
  free to reorder tables as it sees fit. (Table reordering is also
  disabled on an outer join, but that is because outer joins are not
  associative or commutative. Reordering tables in OUTER JOIN changes
  the result.)


  See "The Fossil NGQP Upgrade Case Study" for another real-world example
  of using CROSS JOIN to manually control the nesting order of a join.
  The query planner checklist found later in the same document provides
  further guidance on manual control of the query planner.


c2: The SQLite Query Optimizer Overview
c3: 8. Choosing Between Multiple Indexes
c5: optoverview.html#choosing_between_multiple_indexes
c4:
Each table in the FROM clause of a query can use at most one index
  (except when the OR-clause optimization comes into
  play)
  and SQLite strives to use at least one index on each table.  Sometimes,
  two or more indexes might be candidates for use on a single table.
  For example:

CREATE TABLE ex2(x,y,z);
CREATE INDEX ex2i1 ON ex2(x);
CREATE INDEX ex2i2 ON ex2(y);
SELECT z FROM ex2 WHERE x=5 AND y=6;


  For the SELECT statement above, the optimizer can use the ex2i1 index
  to lookup rows of ex2 that contain x=5 and then test each row against
  the y=6 term.  Or it can use the ex2i2 index to lookup rows
  of ex2 that contain y=6 then test each of those rows against the
  x=5 term.


  When faced with a choice of two or more indexes, SQLite tries to estimate
  the total amount of work needed to perform the query using each option.
  It then selects the option that gives the least estimated work.


  To help the optimizer get a more accurate estimate of the work involved
  in using various indexes, the user may optionally run the ANALYZE command.
  The ANALYZE command scans all indexes of database where there might
  be a choice between two or more indexes and gathers statistics on the
  selectiveness of those indexes.  The statistics gathered by
  this scan are stored in special database tables names shows names all
  begin with "sqlite_stat".
  The content of these tables is not updated as the database
  changes so after making significant changes it might be prudent to
  rerun ANALYZE.
  The results of an ANALYZE command are only available to database connections
  that are opened after the ANALYZE command completes.


  The various sqlite_statN tables contain information on how
  selective the various indexes are.  For example, the sqlite_stat1
  table might indicate that an equality constraint on column x reduces the
  search space to 10 rows on average, whereas an equality constraint on
  column y reduces the search space to 3 rows on average.  In that case,
  SQLite would prefer to use index ex2i2 since that index is more selective.


c2: The SQLite Query Optimizer Overview
c3: 8.1. Disqualifying WHERE Clause Terms using Unary-"+"
c5: optoverview.html#disqualifying_where_clause_terms_using_unary_
c4:
Terms of the WHERE clause can be manually disqualified for use with
  indexes by prepending a unary + operator to the column name.  The
  unary + is a no-op and will not generate any byte code in the prepared
  statement.
  However, the unary + operator will prevent the term from
  constraining an index.
  So, in the example above, if the query were rewritten as:

SELECT z FROM ex2 WHERE +x=5 AND y=6;


  The + operator on the x column will prevent that term from 
  constraining an index.  This would force the use of the ex2i2 index.


  Note that the unary + operator also removes 
  type affinity from
  an expression, and in some cases this can cause subtle changes in
  the meaning of an expression.
  In the example above,
  if column x has TEXT affinity
  then the comparison "x=5" will be done as text.  The + operator
  removes the affinity.  So the comparison "+x=5" will compare the text
  in column x with the numeric value 5 and will always be false.


c2: The SQLite Query Optimizer Overview
c3: 8.2. Range Queries
c5: optoverview.html#range_queries
c4:
Consider a slightly different scenario:

CREATE TABLE ex2(x,y,z);
CREATE INDEX ex2i1 ON ex2(x);
CREATE INDEX ex2i2 ON ex2(y);
SELECT z FROM ex2 WHERE x BETWEEN 1 AND 100 AND y BETWEEN 1 AND 100;


  Further suppose that column x contains values spread out
  between 0 and 1,000,000 and column y contains values
  that span between 0 and 1,000.  In that scenario,
  the range constraint on column x should reduce the search space by
  a factor of 10,000 whereas the range constraint on column y should
  reduce the search space by a factor of only 10.  So the ex2i1 index
  should be preferred.


  SQLite will make this determination, but only if it has been compiled
  with SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4.
  The SQLITE_ENABLE_STAT3 and SQLITE_ENABLE_STAT4 options causes
  the ANALYZE command to collect a histogram of column content in the
  sqlite_stat3 or sqlite_stat4 tables and to use this histogram to 
  make a better guess at the best query to use for range constraints
  such as the above.  The main difference between STAT3 and STAT4 is
  that STAT3 records histogram data for only the left-most column of
  an index whereas STAT4 records histogram data for all columns of an
  index.  For single-column indexes, STAT3 and STAT4 work the same.


  The histogram data is only useful if the right-hand side of the constraint
  is a simple compile-time constant or parameter and not an expression.


  Another limitation of the histogram data is that it only applies to the
  left-most column on an index.  Consider this scenario:

CREATE TABLE ex3(w,x,y,z);
CREATE INDEX ex3i1 ON ex2(w, x);
CREATE INDEX ex3i2 ON ex2(w, y);
SELECT z FROM ex3 WHERE w=5 AND x BETWEEN 1 AND 100 AND y BETWEEN 1 AND 100;


  Here the inequalities are on columns x and y which are not the
  left-most index columns.  Hence, the histogram data which is collected no
  left-most column of indexes is useless in helping to choose between the
  range constraints on columns x and y.


c2: The SQLite Query Optimizer Overview
c3: 9. Covering Indexes
c5: optoverview.html#covering_indexes
c4:
When doing an indexed lookup of a row, the usual procedure is to
  do a binary search on the index to find the index entry, then extract
  the rowid from the index and use that rowid to do a binary search on
  the original table.  Thus a typical indexed lookup involves two
  binary searches.
  If, however, all columns that were to be fetched from the table are
  already available in the index itself, SQLite will use the values
  contained in the index and will never look up the original table
  row.  This saves one binary search for each row and can make many
  queries run twice as fast.


  When an index contains all of the data needed for a query and when the
  original table never needs to be consulted, we call that index a
  "covering index".


c2: The SQLite Query Optimizer Overview
c3: 10. ORDER BY Optimizations
c5: optoverview.html#order_by_optimizations
c4:
SQLite attempts to use an index to satisfy the ORDER BY clause of a
  query when possible.
  When faced with the choice of using an index to satisfy WHERE clause
  constraints or satisfying an ORDER BY clause, SQLite does the same
  cost analysis described above
  and chooses the index that it believes will result in the fastest answer.


  SQLite will also attempt to use indexes to help satisfy GROUP BY clauses
  and the DISTINCT keyword.  If the nested loops of the join can be arranged
  such that rows that are equivalent for the GROUP BY or for the DISTINCT are
  consecutive, then the GROUP BY or DISTINCT logic can determine if the 
  current row is part of the same group or if the current row is distinct
  simply by comparing the current row to the previous row.
  This can be much faster than the alternative of comparing each row to
  all prior rows.


c2: The SQLite Query Optimizer Overview
c3: 10.1. Partial ORDER BY via Index
c5: optoverview.html#partial_order_by_via_index
c4:
If a query contains an ORDER BY clause with multiple terms, it might
  be that SQLite can use indexes to cause rows to come out in the order
  of some prefix of the terms in the ORDER BY but that later terms in
  the ORDER BY are not satisfied.  In that case, SQLite does block sorting.
  Suppose the ORDER BY clause has four terms and the natural order of the
  query results in rows appearing in order of the first two terms.  As
  each row is output by the query engine and enters the sorter, the 
  outputs in the current row corresponding to the first two terms of 
  the ORDER BY are compared against the previous row.  If they have
  changed, the current sort is finished and output and a new sort is
  started.  This results in a slightly faster sort.  Event bigger
  advantages are that many fewer rows need to be held in memory,
  reducing memory requirements, and outputs can begin to appear before
  the core query has run to completion.


c2: The SQLite Query Optimizer Overview
c3: 11. Subquery Flattening
c5: optoverview.html#subquery_flattening
c4:
When a subquery occurs in the FROM clause of a SELECT, the simplest
  behavior is to evaluate the subquery into a transient table, then run
  the outer SELECT against the transient table.  Such a plan
  can be suboptimal since the transient table will not have any indexes
  and the outer query (which is likely a join) will be forced to do a
  full table scan on the transient table.


  To overcome this problem, SQLite attempts to flatten subqueries in
  the FROM clause of a SELECT.
  This involves inserting the FROM clause of the subquery into the
  FROM clause of the outer query and rewriting expressions in
  the outer query that refer to the result set of the subquery.
  For example:

SELECT t1.a, t2.b FROM t2, (SELECT x+y AS a FROM t1 WHERE z&lt;100) WHERE a&gt;5


  Would be rewritten using query flattening as:

SELECT t1.x+t1.y AS a, t2.b FROM t2, t1 WHERE z&lt;100 AND a&gt;5


  There is a long list of conditions that must all be met in order for
  query flattening to occur.  Some of the constraints are marked as 
  obsolete by italic text.  These extra constraints are retained in the
  documentation to preserve the numbering of the other constraints.


  Casual readers are not expected to understand all of these rules.
  A key take-away from this section is that the rules for determining
  if query flatting is safe or unsafe are subtle and
  complex.  There have been multiple bugs over the years caused by
  over-aggressive query flattening.  On the other hand, performance
  of complex queries and/or queries involving views tends to suffer
  if query flattening is more conservative.


  
    (Obsolete.  Query flattening is no longer
                      attempted for aggregate subqueries.)

    (Obsolete.  Query flattening is no longer
                      attempted for aggregate subqueries.)

  
  If the subquery is the right operand of a LEFT JOIN then
    the subquery may not be a join, and
    the FROM clause of the subquery may
   not contain a virtual table, and
    the outer query may not be an aggregate.

    The subquery is not DISTINCT.

   (Subsumed into constraint 4)

   (Obsolete.  Query flattening is no longer
                      attempted for aggregate subqueries.)

  
  The subquery has a FROM clause.

  
  The subquery does not use LIMIT or the outer query is not a join.

  
  The subquery does not use LIMIT or the outer query does not use
  aggregates.

   (Restriction relaxed in 2005)

  
  The subquery and the outer query do not both have ORDER BY clauses.

   (Subsumed into constraint 3)

    The subquery and outer query do not both use LIMIT.

    The subquery does not use OFFSET.

  
  If the outer query is part of a compound select, then the
  subquery may not have a LIMIT clause.

  
  If the outer query is an aggregate, then the subquery may
  not contain ORDER BY. 

  
  If the sub-query is a compound SELECT, then
  
   all compound operators must be UNION ALL, and
   no terms with the subquery compound may be aggregate
       or DISTINCT, and
   every term within the subquery must have a FROM clause, and
   the outer query may not be an aggregate, DISTINCT query, or join.
  

  The parent and sub-query may contain WHERE clauses. Subject to
  rules (11), (12) and (13), they may also contain ORDER BY,
  LIMIT and OFFSET clauses.

  
  If the sub-query is a compound select, then all terms of the
  ORDER by clause of the parent must be simple references to 
  columns of the sub-query.

  
  If the subquery uses LIMIT then the outer query may not
  have a WHERE clause.

  
  If the sub-query is a compound select, then it must not use
   an ORDER BY clause.

  
  If the subquery uses LIMIT, then the outer query may not be
  DISTINCT.

   The subquery may not be a recursive CTE.

   (Subsumed into constraint 17d.)

   (Obsolete. Query flattening is no longer
                      attempted for aggregate subqueries.)
  



  Query flattening is an important optimization when views are used as
  each use of a view is translated into a subquery.


c2: The SQLite Query Optimizer Overview
c3: 12. Subquery Co-routines
c5: optoverview.html#subquery_co_routines
c4:
Prior to SQLite 3.7.15 (2012-12-12),
  a subquery in the FROM clause would be
  either flattened into the outer query, or else the subquery would be run
  to completion
  before the outer query started, the result set from the subquery
  would be stored in a transient table,
  and then the transient table would be used in the outer query.  Newer
  versions of SQLite have a third option, which is to implement the subquery
  using a co-routine.


  A co-routine is like a subroutine in that it runs in the same thread
  as the caller and eventually returns control back to the caller.  The
  difference is that a co-routine also has the ability to return
  before it has finished, and then resume where it left off the next
  time it is called.


  When a subquery is implemented as a co-routine, byte-code is generated
  to implement the subquery as if it were a standalone query, except
  instead of returning rows of results back to the application, the
  co-routine yields control back to the caller after each row is computed.
  The caller can then use that one computed row as part of its computation,
  then invoke the co-routine again when it is ready for the next row.


  Co-routines are better than storing the complete result set of the subquery
  in a transient table because co-routines use less memory.  With a co-routine,
  only a single row of the result needs to be remembered, whereas all rows of
  the result must be stored for a transient table.  Also, because the
  co-routine does not need to run to completion before the outer query
  begins its work, the first rows of output can appear much sooner, and if
  the overall query is aborted, less work is done overall.


  On the other hand, if the result of the subquery must be scanned multiple
  times (because, for example, it is just one table in a join) then it
  is better to use a transient table to remember the entire result of the
  subquery, in order to avoid computing the subquery more than once.


c2: The SQLite Query Optimizer Overview
c3: 12.1. Using Co-routines to Defer Work until after the Sorting
c5: optoverview.html#using_co_routines_to_defer_work_until_after_the_sorting
c4:
As of SQLite version 3.21.0 (2017-10-24), the query planner will
  always prefer to use a co-routine to implement FROM-clause subqueries 
  that contains an ORDER BY clause and that are not part of a join when
  the result set of the outer query is "complex".  This feature allows
  applications to shift expensive computations from before the
  sorter until after the sorter, which can result in faster operation.
  For example, consider this query:

SELECT expensive_function(a) FROM tab ORDER BY date DESC LIMIT 5;


  The goal of this query is to compute some value for the five most
  recent entries in the table.  In the query above, the
  "expensive_function()" is invoked prior to the sort and thus is
  invoked on every row of the table, even
  rows that are ultimately omitted due to the LIMIT clause.
  A co-routine can be used to work around this:

SELECT expensive_function(a) FROM (
  SELECT a FROM tab ORDER BY date DESC LIMIT 5
);


  In the revised query, the subquery implemented by a co-routine computes
  the five most recent values for "a".  Those five values are passed from the
  co-routine up into the outer query where the "expensive_function()" is
  invoked on only the specific rows that the application cares about.


  The query planner in future versions of SQLite might grow smart enough
  to make transformations such as the above automatically, in both directions.
  That is to say, future versions of SQLite might transform queries of the
  first form into the second, or queries written the second way into the
  first.  As of SQLite version 3.22.0 (2018-01-22), the query planner
  will flatten the subquery if the outer query does not make use of any
  user-defined functions or subqueries in its result set.  For the examples
  shown above, however, SQLite implements each of the queries as
  written.


c2: The SQLite Query Optimizer Overview
c3: 13. The MIN/MAX Optimization
c5: optoverview.html#the_min_max_optimization
c4:
Queries that contain a single MIN() or MAX() aggregate function whose
  argument is the left-most column of an index might be satisfied
  by doing a single index lookup rather than by scanning the entire table.
  Examples:

SELECT MIN(x) FROM table;
SELECT MAX(x)+1 FROM table;


c2: The SQLite Query Optimizer Overview
c3: 14. Automatic Indexes
c5: optoverview.html#automatic_indexes
c4:
When no indexes are available to aid the evaluation of a query, SQLite
  might create an automatic index that lasts only for the duration
  of a single SQL statement.
  Since the cost of constructing the automatic index is
  O(NlogN) (where N is the number of entries in the table) and the cost of
  doing a full table scan is only O(N), an automatic index will
  only be created if SQLite expects that the lookup will be run more than
  logN times during the course of the SQL statement. Consider an example:

CREATE TABLE t1(a,b);
CREATE TABLE t2(c,d);
-- Insert many rows into both t1 and t2
SELECT * FROM t1, t2 WHERE a=c;


  In the query above, if both t1 and t2 have approximately N rows, then
  without any indexes the query will require O(N*N) time.  On the other
  hand, creating an index on table t2 requires O(NlogN) time and using
  that index to evaluate the query requires an additional O(NlogN) time.
  In the absence of ANALYZE information, SQLite guesses that N is one
  million and hence it believes that constructing the automatic index will
  be the cheaper approach.


  An automatic index might also be used for a subquery:

CREATE TABLE t1(a,b);
CREATE TABLE t2(c,d);
-- Insert many rows into both t1 and t2
SELECT a, (SELECT d FROM t2 WHERE c=b) FROM t1;


  In this example, the t2 table is used in a subquery to translate values
  of the t1.b column.  If each table contains N rows, SQLite expects that
  the subquery will run N times, and hence it will believe it is faster
  to construct an automatic, transient index on t2 first and then use
  that index to satisfy the N instances of the subquery.


  The automatic indexing capability can be disabled at run-time using
  the automatic_index pragma.  Automatic indexing is turned on by
  default, but this can be changed so that automatic indexing is off
  by default using the SQLITE_DEFAULT_AUTOMATIC_INDEX compile-time option.
  The ability to create automatic indexes can be completely disabled by
  compiling with the SQLITE_OMIT_AUTOMATIC_INDEX compile-time option.


  In SQLite version 3.8.0 (2013-08-26) and later, 
  an SQLITE_WARNING_AUTOINDEX message is sent
  to the error log every time a statement is prepared that uses an
  automatic index.  Application developers can and should use these warnings
  to identify the need for new persistent indexes in the schema.


  Do not confuse automatic indexes with the internal indexes (having names
  like "sqlite_autoindex_table_N") that are sometimes
  created to implement a PRIMARY KEY constraint or UNIQUE constraint.
  The automatic indexes described here exist only for the duration of a
  single query, are never persisted to disk, and are only visible to a
  single database connection.  Internal indexes are part of the implementation
  of PRIMARY KEY and UNIQUE constraints, are long-lasting and persisted
  to disk, and are visible to all database connections.  The term "autoindex"
  appears in the names of internal indexes for legacy reasons and does
  not indicate that internal indexes and automatic indexes are related.


c2: The SQLite Query Optimizer Overview
c3: 14.1. Hash Joins
c5: optoverview.html#hash_joins
c4:
An automatic index is about the same thing as a
 hash join.  The only difference
 is that a B-Tree is used instead of a hash table.  If you are willing to
 say that the transient B-Tree constructed for an automatic index is
 really just a fancy hash table, then a query that uses an automatic
 index is just a hash join.


 SQLite constructs an transient index instead of a hash table in this
 instance because it already has a robust and high performance B-Tree
 implementation at hand, whereas a hash-table would need to be added.
 Adding a separate hash table implementation to handle this one case
 would increase the size of the library (which is designed for use on
 low-memory embedded devices) for minimal performance gain.  SQLite might
 be enhanced with a hash-table implementation someday, but for now it seems
 better to continue using automatic indexes in cases where client/server
 database engines might use a hash join.


