# page_content

c2: The INDEXED BY Clause
c5: lang_indexedby.html
c4:
1. How INDEXED BY Works

The INDEXED BY phrase forces the SQLite query planner to use a
particular named index on a DELETE, SELECT, or UPDATE statement.
The INDEXED BY phrase is an SQLite extension and
is not portable to other SQL database engines.



 
 



The "INDEXED BY index-name" phrase specifies 
that the named index
must be used in order to look up values on the preceding table.
If index-name does not exist or cannot be used 
for the query, then the preparation of the SQL statement fails.
The "NOT INDEXED" clause specifies that no index shall be used when
accessing the preceding table, including implied indices create by
UNIQUE and PRIMARY KEY constraints.  However, the rowid
can still be used to look up entries even when "NOT INDEXED" is specified.

Some SQL database engines provide non-standard "hint" mechanisms which
can be used to give the query optimizer clues about what indices it should
use for a particular statement.  The INDEX BY clause of SQLite is 
not a hinting mechanism and it should not be used as such.
The INDEXED BY clause does not give the optimizer hints about which index
to use; it gives the optimizer a requirement of which index to use.
If the query optimizer is unable to use the index specified by the
INDEX BY clause, then the query will fail with an error.

The INDEXED BY clause is not intended for use in tuning
the performance of a query.  The intent of the INDEXED BY clause is
to raise a run-time error if a schema change, such as dropping or
creating an index, causes the query plan for a time-sensitive query
to change.  The INDEXED BY clause is designed to help detect
undesirable query plan changes during regression testing.
Application 
developers are admonished to omit all use of INDEXED BY during
application design, implementation, testing, and tuning.  If
INDEXED BY is to be used at all, it should be inserted at the very
end of the development process when "locking down" a design.

2. See Also


The query planner checklist describes steps that application
developers should following to help resolve query planner problems.
Notice the that the use of INDEXED BY is a last resort, to be used only
when all other measures fail.

The unary "+" operator
can be used to disqualify terms in the WHERE clause from use by indices.
Careful use of unary + can sometimes help prevent the query planner from
choosing a poor index without restricting it to using one specific index.
Careful placement of unary + operators is a better method for controlling 
which indices are used by a query.

The sqlite3_stmt_status() C/C++ interface together with the
SQLITE_STMTSTATUS_FULLSCAN_STEP and SQLITE_STMTSTATUS_SORT verbs
can be used to detect at run-time when an SQL statement is not
making effective use of indices.  Many applications may prefer to
use the sqlite3_stmt_status() interface to detect index misuse
rather than the INDEXED BY phrase described here.


c2: REINDEX
c5: lang_reindex.html
c4:
The REINDEX command is used to delete and recreate indices from scratch.
This is useful when the definition of a collation sequence has changed, or
when there are indexes on expressions involving a function whose definition
has changed.


If the REINDEX keyword is not followed by a collation-sequence or database 
object identifier, then all indices in all attached databases are rebuilt.

If the REINDEX keyword is followed by a collation-sequence name, then
all indices in all attached databases that use the named collation sequences
are recreated. 

Or, if the argument attached to the REINDEX identifies a specific 
database table, then all indices attached to the database table are rebuilt. 
If it identifies a specific database index, then just that index is recreated.

For a command of the form "REINDEX name", a match
against collation-name takes precedence over a match
against index-name or table-name.
This ambiguity in the syntax may be avoided by always specifying a
schema-name when reindexing a specific table or index.


c2: SQL Language Expressions
c5: lang_expr.html
c4:
1. Syntax



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 







2. Operators
SQLite understands the following binary operators, in order from
highest to lowest precedence:


||
*    /    %
+    -
&lt;&lt;   &gt;&gt;   &amp;    |
&lt;    &lt;=   &gt;    &gt;=
=    ==   !=   &lt;&gt;   IS   IS NOT   IN   LIKE   GLOB   MATCH   REGEXP
AND   
OR


Supported unary prefix operators are these:


-    +    ~    NOT




The COLLATE operator is a unary postfix
operator that assigns a collating sequence to an expression.
The COLLATE operator has a higher precedence (binds more tightly) than any
binary operator and any unary prefix operator except "~".
(COLLATE and "~" are associative so their binding order does not matter.)
The collating sequence set by the COLLATE operator overrides the
collating sequence determined by the COLLATE clause in a table
column definition.
See the detailed discussion on collating sequences
in the Datatype In SQLite3 document for additional information.



The unary operator + is a no-op.  It can be applied
to strings, numbers, blobs or NULL and it always returns a result
with the same value as the operand.

Note that there are two variations of the equals and not equals
operators.  Equals can be either

= or ==.
The non-equals operator can be either
!= or &lt;&gt;.
The || operator is "concatenate" - it joins together
the two strings of its operands.
The operator % outputs the integer value of its left 
operand modulo its right operand.  In other words, the
operator % works in SQLite the same as it does
in ANSI-C.

The result of any binary operator is either a numeric value or 
NULL, except for the || concatenation operator which always 
evaluates to either NULL or a text value.
The IS and IS NOT operators work
like = and != except when one or both of the
operands are NULL. In this case, if both operands are NULL, then the
IS operator evaluates to 1 (true) and the IS NOT operator evaluates
to 0 (false). If one operand is NULL and the other is not, then the
IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true).
It is not possible for an IS or IS NOT expression to evaluate to NULL.
Operators IS and IS NOT have the same 
precedence as =.

3. Literal Values (Constants)

A literal value represents a constant.
Literal values may be integers, floating point numbers, strings,
BLOBs, or NULLs.

The syntax for integer and floating point literals (collectively
"numeric literals") is shown by the following diagram:


 
 



If a numeric literal has a decimal point or an exponentiation
clause or if its magnitude is less than -9223372036854775808 or
greater than 9223372036854775807, then it is a floating point literal.
Otherwise is it is an  integer literal.
The "E" character that begins the exponentiation
clause of a floating point literal can be either upper or lower case.
The "." character is always used 
as the decimal point even if the locale setting specifies "," for
this role - the use of "," for the decimal point would result in
syntactic ambiguity.



Hexadecimal integer literals follow the C-language notation of
"0x" or "0X" followed by hexadecimal digits.
For example, 0x1234 means the same as 4660
and 0x8000000000000000 means the same as -9223372036854775808.
 Hexadecimal integer literals are interpreted as 64-bit
two's-complement integers and are thus limited
to sixteen significant digits of precision.
Support for hexadecimal integers was added to SQLite
version 3.8.6 (2014-08-15).
For backwards compatibility, the "0x" hexadecimal integer
notation is only understood by the SQL language parser, not by the
type conversions routines.
String variables that
contain text formatted like hexadecimal integers are not
interpreted as hexadecimal integers when coercing the string value
into an integer due to a CAST expression or for a column affinity
transformation or prior to performing a numeric operation or for
any other run-time conversions.  When coercing a
string value in the format of a hexadecimal integer into an integer
value, the conversion process stops when the 'x' character is seen
so the resulting integer value is always zero.
SQLite only understands the hexadecimal integer notation when it
appears in the SQL statement text, not when it appears as
part of the content of the database.

 A string constant is formed by enclosing the
string in single quotes (').  A single quote within the string can
be encoded by putting two single quotes in a row - as in Pascal.
C-style escapes using the backslash character are not supported because
they are not standard SQL.

 BLOB literals are string literals containing hexadecimal data and
preceded by a single "x" or "X" character.  Example: X'53514C697465'


A literal value can also be the token "NULL".




4. Parameters

A "variable" or "parameter" token
specifies a placeholder in the expression for a 
value that is filled in at runtime using the
sqlite3_bind() family of C/C++ interfaces.
Parameters can take several forms:





?NNN
A question mark followed by a number NNN holds a spot for the
NNN-th parameter.  NNN must be between 1 and SQLITE_MAX_VARIABLE_NUMBER.



?
A question mark that is not followed by a number creates a parameter
with a number one greater than the largest parameter number already assigned.
If this means the parameter number is greater than
SQLITE_MAX_VARIABLE_NUMBER, it is an error.
This parameter format is provided for compatibility with other database
engines.  But because it is easy to miscount the question marks, the
use of this parameter format is discouraged.  Programmers are encouraged
to use one of the symbolic formats below or the ?NNN format above instead.



:AAAA
A colon followed by an identifier name holds a spot for a 
named parameter with the name :AAAA.  
Named parameters are also numbered. The number assigned is one greater than
the largest parameter number already assigned. If this means the parameter
would be assigned a number greater than SQLITE_MAX_VARIABLE_NUMBER, it is
an error. To avoid confusion, it is best to avoid mixing named and numbered
parameters.


@AAAA
An "at" sign works exactly like a colon, except that the name of
the parameter created is @AAAA.


$AAAA
A dollar-sign followed by an identifier name also holds a spot for a named
parameter with the name $AAAA.  The identifier name in this case can include
one or more occurrences of "::" and a suffix enclosed in "(...)" containing
any text at all.  This syntax is the form of a variable name in the
Tcl programming language.  The presence
of this syntax results from the fact that SQLite is really a 
Tcl extension that has escaped into the wild.




Parameters that are not assigned values using
sqlite3_bind() are treated
as NULL.  The sqlite3_bind_parameter_index() interface can be used
to translate a symbolic parameter name into its equivalent numeric index.

The maximum parameter number is set at compile-time by
the SQLITE_MAX_VARIABLE_NUMBER macro.  An individual database connection
D can reduce its maximum parameter number below the compile-time maximum
using the sqlite3_limit(D, SQLITE_LIMIT_VARIABLE_NUMBER,...) interface.




5. The LIKE, GLOB, REGEXP, and MATCH operators
The LIKE operator does a pattern matching comparison. The operand
to the right of the LIKE operator contains the pattern and the left hand
operand contains the string to match against the pattern.

A percent symbol ("%") in the LIKE pattern matches any
sequence of zero or more characters in the string.  An underscore
("_") in the LIKE pattern matches any single character in the
string.  Any other character matches itself or its lower/upper case
equivalent (i.e. case-insensitive matching).

Important Note: SQLite only
understands upper/lower case for ASCII characters by default.  The
LIKE operator is case sensitive by default for unicode characters that are
beyond the ASCII range.  For example,
the expression 'a'&nbsp;LIKE&nbsp;'A'
is TRUE but '&aelig;'&nbsp;LIKE&nbsp;'&AElig;' is FALSE.
The ICU extension to SQLite includes an enhanced version of the
LIKE operator that does case folding across all unicode characters.

If the optional ESCAPE clause is present, then the expression
following the ESCAPE keyword must evaluate to a string consisting of
a single character. This character may be used in the LIKE pattern
to include literal percent or underscore characters. The escape
character followed by a percent symbol (%), underscore (_), or a second
instance of the escape character itself matches a
literal percent symbol, underscore, or a single escape character,
respectively.

The infix LIKE operator is implemented by calling the
application-defined SQL functions like(Y,X) or
like(Y,X,Z).

The LIKE operator can be made case sensitive using the
case_sensitive_like pragma.



The GLOB operator is similar to LIKE but uses the Unix
file globbing syntax for its wildcards.  Also, GLOB is case
sensitive, unlike LIKE.  Both GLOB and LIKE may be preceded by
the NOT keyword to invert the sense of the test.  The infix GLOB 
operator is implemented by calling the function
glob(Y,X) and can be modified by overriding
that function.



The REGEXP operator is a special syntax for the regexp()
user function.  No regexp() user function is defined by default
and so use of the REGEXP operator will normally result in an
error message.  If an application-defined SQL function named "regexp"
is added at run-time, then the "X REGEXP Y" operator will
be implemented as a call to "regexp(Y,X)".



The MATCH operator is a special syntax for the match()
application-defined function.  The default match() function implementation
raises an exception and is not really useful for anything.
But extensions can override the match() function with more
helpful logic.



6. The BETWEEN operator
The BETWEEN operator is logically equivalent to a pair of comparisons.
"x BETWEEN y AND z" is 
equivalent to 
"x&gt;=y AND x&lt;=z" except
that with BETWEEN, the x expression is only evaluated once.
The precedence of the BETWEEN operator is the same as the precedence
as operators == and != and LIKE and groups left to right.



7. The CASE expression
A CASE expression serves a role similar to IF-THEN-ELSE in other
programming languages.  

The optional expression that occurs in between the CASE keyword and the
first WHEN keyword is called the "base" expression. There are two
fundamental forms
of the CASE expression: those with a base expression and those without.

In a CASE without a base expression, each WHEN expression is evaluated
and the result treated as a boolean, starting with the leftmost and continuing
to the right. The result of the CASE expression is the evaluation of the THEN
expression that corresponds to the first WHEN expression that evaluates to
true. Or, if none of the WHEN expressions evaluate to true, the result of
evaluating the ELSE expression, if any. If there is no ELSE expression and
none of the WHEN expressions are true, then the overall result is NULL.

A NULL result is considered untrue when evaluating WHEN terms.

In a CASE with a base expression, the base expression is evaluated just
once and the result is compared against the evaluation of each WHEN 
expression from left to right. The result of the CASE expression is the 
evaluation of the THEN expression that corresponds to the first WHEN
expression for which the comparison is true. Or, if none of the WHEN
expressions evaluate to a value equal to the base expression, the result
of evaluating the ELSE expression, if any. If there is no ELSE expression and
none of the WHEN expressions produce a result equal to the base expression,
the overall result is NULL.

When comparing a base expression against a WHEN expression, the same
collating sequence, affinity, and NULL-handling rules apply as if the
base expression and WHEN expression are respectively the left- and
right-hand operands of an = operator. 

If the base 
expression is NULL then the result of the CASE is always the result 
of evaluating the ELSE expression if it exists, or NULL if it does not.

Both forms of the CASE expression use lazy, or short-circuit, 
evaluation.

The only difference between the following two CASE expressions is that 
the x expression is evaluated exactly once in the first example but 
might be evaluated multiple times in the second:


CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END
CASE WHEN x=w1 THEN r1 WHEN x=w2 THEN r2 ELSE r3 END


The built-in iif(x,y,z) SQL function is logically
equivalent to "CASE WHEN x THEN y ELSE z END".  The iif() function
is found in SQL Server and is included in SQLite for compatibility.
Some developers prefer the iif() function because it is more
concise.




8. The IN and NOT IN operators
The IN and NOT IN operators take an expression on the
left and a list of values or a subquery on the right.
When the right operand of an IN or NOT IN operator is a subquery, the
subquery must have the same number of columns as there are columns in
the row value of the left operand.  The subquery on the
right of an IN or NOT IN operator must be a scalar subquery if the left
expression is not a row value expression.
If the right operand of an IN or NOT IN operator is a list of values,
each of those values must be scalars and the left expression must also
be a scalar.
The right-hand side of an IN or NOT IN operator can be a
table name or table-valued function name in which 
case the right-hand side is understood to be subquery of
the form "(SELECT * FROM name)".
When the right operand is an empty set, the result of IN is false and the
result of NOT IN is true, regardless of the left operand and even if the
left operand is NULL.
The result of an IN or NOT IN operator is determined by the following
matrix:




Left operand is NULL
Right operand contains NULL
Right operand is an empty set
Left operand found within right operand
Result of IN operator
Result of NOT IN operator

no
no
no
no
false
true

does not matter
no
yes
no
false
true

no
does not matter
no
yes
true
false

no
yes
no
no
NULL
NULL

yes
does not matter
no
does not matter
NULL
NULL



Note that SQLite allows the parenthesized list of scalar values on
the right-hand side of an IN or NOT IN operator to be an empty list but
most other SQL database database engines and the SQL92 standard require
the list to contain at least one element.

9. Table Column Names

A column name can be any of the names defined in the CREATE TABLE
statement or one of the following special identifiers: "ROWID",
"OID", or "_ROWID_".
The three special identifiers describe the
unique integer key (the rowid) associated with every 
row of every table and so are not available on WITHOUT ROWID tables.
The special identifiers only refer to the row key if the CREATE TABLE
statement does not define a real column with the same name.
The rowid can be used anywhere a regular
column can be used.



10. The EXISTS operator

The EXISTS operator always evaluates to one of the integer values 0 
and 1. If executing the SELECT statement specified as the right-hand 
operand of the EXISTS operator would return one or more rows, then the
EXISTS operator evaluates to 1. If executing the SELECT would return
no rows at all, then the EXISTS operator evaluates to 0. 

The number of columns in each row returned by the SELECT statement
(if any) and the specific values returned have no effect on the results
of the EXISTS operator. In particular, rows containing NULL values are
not handled any differently from rows without NULL values.



11. Subquery Expressions

A SELECT statement enclosed in parentheses is a subquery.
All types of SELECT statement, including
aggregate and compound SELECT queries (queries with keywords like
UNION or EXCEPT) are allowed as scalar subqueries.
The value of a subquery expression is the first row of the result
from the enclosed SELECT statement.
The value of a subquery expression is NULL if the enclosed
SELECT statement returns no rows.

A subquery that returns a single column is a scalar subquery and can
be used most anywhere.
A subquery that returns two or more columns is a row value
subquery and can only be used as the operand of a comparison operator.



12. Correlated Subqueries

A SELECT statement used as either a scalar subquery or as the 
right-hand operand of an IN, NOT IN or EXISTS expression may contain 
references to columns in the outer query. Such a subquery is known as
a correlated subquery. A correlated subquery is reevaluated each time
its result is required. An uncorrelated subquery is evaluated only once
and the result reused as necessary.



13. CAST expressions

A CAST expression of the form "CAST(expr AS type-name)"
is used to convert the value of expr to 
a different storage class specified by type-name.
A CAST conversion is similar to the conversion that takes
place when a column affinity is applied to a value except that with
the CAST operator the conversion always takes place even if the conversion
lossy and irreversible, whereas column affinity only changes the data type
of a value if the change is lossless and reversible.

If the value of expr is NULL, then the result of the CAST
expression is also NULL. Otherwise, the storage class of the result
is determined by applying the rules for determining column affinity to
the type-name.




   Affinity of type-name
   Conversion Processing

   NONE 
   Casting a value to a type-name with no affinity 
  causes the value to
  be converted into a BLOB.  Casting to a BLOB consists of first casting
  the value to TEXT in the encoding of the database connection, then
  interpreting the resulting byte sequence as a BLOB instead of as TEXT.


   TEXT
   To cast a BLOB value to TEXT, the sequence of bytes that make up the
  BLOB is interpreted as text encoded using the database encoding.
  
   Casting an INTEGER or REAL value into TEXT renders the value as if via 
    sqlite3_snprintf() except that the resulting TEXT uses the encoding of
    the database connection.


   REAL
   When casting a BLOB value to a REAL, the value is first converted to
        TEXT.
       When casting a TEXT value to REAL, the longest possible prefix of
        the value that can be interpreted as a real number is extracted from
        the TEXT value and the remainder ignored. Any leading spaces in the
        TEXT value are ignored when converging from TEXT to REAL. If there is
        no prefix that can be interpreted as a real number, the result of the
        conversion is 0.0.


   INTEGER
   When casting a BLOB value to INTEGER, the value is first converted to
        TEXT.
       When casting a TEXT value to INTEGER, the longest possible prefix of
        the value that can be interpreted as an integer number is extracted from
        the TEXT value and the remainder ignored. Any leading spaces in the
        TEXT value when converting from TEXT to INTEGER are ignored. If there
        is no prefix that can be interpreted as an integer number, the result
        of the conversion is 0.  If the prefix integer is greater than
        +9223372036854775807 then the result of the cast is exactly
        +9223372036854775807.  Similarly, if the prefix integer is
        less than -9223372036854775808 then the result of the cast is
        exactly -9223372036854775808.

        When casting to INTEGER, if the text looks like a floating point
        value with an exponent, the exponent will be ignored because it is
        no part of the integer prefix.  For example,
        "(CAST '123e+5' AS INTEGER)" results in 123, not in 12300000.

         The CAST operator understands decimal
        integers only &mdash; conversion of hexadecimal integers stops 
        at the "x" in the "0x" prefix of the hexadecimal integer string 
        and thus result of the CAST is always zero.

      A cast of a REAL value into an INTEGER results in the integer
      between the REAL value and zero that is closest to the REAL value.
      If a REAL is greater than the greatest possible signed
      integer (+9223372036854775807) then the result is the greatest possible
      signed integer and if the REAL is less than the least possible signed
      integer (-9223372036854775808) then the result is the least possible
      signed integer.

      Prior to SQLite version 3.8.2 (2013-12-06),
      casting a REAL value greater than
      +9223372036854775807.0 into an integer resulted in the most negative
      integer, -9223372036854775808.  This behavior was meant to emulate the
      behavior of x86/x64 hardware when doing the equivalent cast.


   NUMERIC
   Casting a TEXT or BLOB value into NUMERIC yields either an INTEGER or
   a REAL result.
   If the input text looks like an integer (there is no decimal point nor
   exponent) and the value is small enough to fit in a 64-bit signed integer,
   then the result will be INTEGER.
   Input text that looks like floating point (there is a decimal point and/or
   an exponent) and the text describes a value that 
   can be losslessly converted back and forth between IEEE 754 64-bit float and a
   51-bit signed integer, then the result is INTEGER.
   (In the previous sentence, a 51-bit integer is specified since that is one
   bit less than the length of the mantissa of an IEEE 754 64-bit float and
   thus provides a 1-bit of margin for the text-to-float conversion operation.)
   Any text input that describes a value outside the range of a 64-bit
   signed integer yields a REAL result.
    Casting a REAL or INTEGER value to NUMERIC is a no-op, even if a real
   value could be losslessly converted to an integer.




Note that the result from casting any non-BLOB value into a 
BLOB and the result from casting any BLOB value into a non-BLOB value
may be different depending on whether the database encoding is UTF-8,
UTF-16be, or UTF-16le.




14. Boolean Expressions

The SQL language features several contexts where an expression is 
evaluated and the result converted to a boolean (true or false) value. These
contexts are:

  
     the WHERE clause of a SELECT, UPDATE or DELETE statement,
     the ON or USING clause of a join in a SELECT statement,
     the HAVING clause of a SELECT statement,
     the WHEN clause of an SQL trigger, and
     the WHEN clause or clauses of some CASE expressions.
  

To convert the results of an SQL expression to a boolean value, SQLite
first casts the result to a NUMERIC value in the same way as a 
CAST expression. A numeric zero value (integer value 0 or real 
value 0.0) is considered to be false.  A NULL value is still NULL.
All other values are considered true.

For example, the values NULL, 0.0, 0, 'english' and '0' are all considered
to be false. Values 1, 1.0, 0.1, -0.1 and '1english' are considered to 
be true.

Beginning with SQLite 3.23.0 (2018-04-02), SQLite recognizes the
identifiers "TRUE" and "FALSE" as boolean literals, if and only if those
identifiers are not already used for some other meaning.  If there already
exists columns or tables or other objects named TRUE or FALSE, then for
the sake of backwards compatibility, the TRUE and FALSE identifiers refer
to those other objects, not to the boolean values.

The boolean identifiers TRUE and FALSE are usually just aliases for
the integer values 1 and 0, respectively.  However, if TRUE or FALSE
occur on the right-hand side of an IS operator, then they form new
unary postfix operators "IS TRUE" and "IS FALSE" which test the boolean
value of the operand on the left.

15. Functions
SQLite supports many simple, aggregate,
and window
SQL functions.  For presentation purposes, simple functions are further
subdivided into core functions, date-time functions,
and JSON functions.
Applications can add new functions, written in C/C++, using the
sqlite3_create_function() interface.



The main expression bubble diagram above shows a single syntax for
all function invocations.  But this is merely to simplify the expression
bubble diagram.  In reality, each type of function has a slightly different
syntax, shown below.  The function invocation syntax shown in the main
expression bubble diagram is the union of the three syntaxes shown here:


 
 

 
 

 
 



The OVER clause is required for window functions and is prohibited
otherwise.  The DISTINCT keyword is only allowed in aggregate functions.
The FILTER clause may not appear on a simple function.

It is possible to have an aggregate function with the same name as a
simple function, as long as the number of arguments for the two forms of the
function are different.  For example, the max() function with a
single argument is an aggregate and the max() function with two or more
arguments is a simple function.  Aggregate functions can usually also
be used as window functions.


c2: Database Object Name Resolution
c5: lang_naming.html
c4:
In SQLite, a database object (a table, index, trigger or view) is identified
  by the name of the object and the name of the database that it resides in. 
  Database objects may reside in the main database, the temp database, or in
  an attached database.


  The syntax of the DROP TABLE, DROP INDEX, DROP VIEW, DROP TRIGGER,
  REINDEX, ALTER TABLE and many other commands all permit the user to
  specify a database object either by its name alone, or by a combination of
  its name and the name of its database. If no database is specified as part
  of the object reference, then SQLite searches the main, temp and all attached
  databases for an object with a matching name. The temp database is searched
  first, followed by the main database, followed all attached databases in the
  order that they were attached. The reference resolves to the first match
  found. For example:


      /* Add a table named 't1' to the temp, main and an attached database */
      ATTACH 'file.db' AS aux;
      CREATE TABLE t1(x, y);
      CREATE TEMP TABLE t1(x, y);
      CREATE TABLE aux.t1(x, y);

      DROP TABLE t1;         /* Drop table in temp database */
      DROP TABLE t1;         /* Drop table in main database */
      DROP TABLE t1;         /* Drop table in aux database */



  If a schema name is specified as part of an object reference, it must be
  either "main", or "temp" or the schema-name of an attached database.
  Like other SQL identifiers, schema names are case-insensitive.
  If a schema name is specified, then only that one schema is searched for
  the named object.


  Most object references may only resolve to a specific type of object (for
  example a reference that is part of a DROP TABLE statement may only resolve
  to a table object, not an index, trigger or view). However in some contexts 
  (e.g. REINDEX) an object reference may be resolve to more than one type
  of object. When searching database schemas for a named object, objects of
  types that cannot be used in the context of the reference are always 
  ignored.


c2: ANALYZE
c5: lang_analyze.html
c4:
1. Overview



 
 



 The ANALYZE command gathers statistics about tables and
indices and stores the collected information
in internal tables of the database where the query optimizer can
access the information and use it to help make better query planning choices.
If no arguments are given, all attached databases are
analyzed.  If a schema name is given as the argument, then all tables
and indices in that one database are analyzed.  
If the argument is a table name, then only that table and the
indices associated with that table are analyzed.  If the argument
is an index name, then only that one index is analyzed.



1.1. Recommended usage pattern

Applications with long-lived databases that use complex
queries should consider running the following commands just prior
to closing each database connection:

PRAGMA analysis_limit=400;
PRAGMA optimize;


The optimize pragma is usually a no-op but it will occasionally
run ANALYZE if it seems like doing so will be useful to the query planner.
The analysis_limit pragma limits the scope of any ANALYZE command that
the optimize pragma runs so that it does not consume too many CPU cycles.
The constant "400" can be adjusted as needed.  Values between 100 and
1000 work well for most applications.

2. Details

 The default implementation stores all statistics in a single
table named "sqlite_stat1".  
 If SQLite is compiled with the
SQLITE_ENABLE_STAT4 option, then additional histogram data is
collected and stored in sqlite_stat4.
Older versions of SQLite would make use of the sqlite_stat2 table
or sqlite_stat3 table
when compiled with SQLITE_ENABLE_STAT2 or SQLITE_ENABLE_STAT3,
but all recent versions of
SQLite ignore the sqlite_stat2 and sqlite_stat3 tables.
Future enhancements may create
additional internal tables with the same name pattern except with
final digit larger than "4".
All of these tables are collectively referred to as "statistics tables".


 The content of the statistics tables can be queried using SELECT
and can be changed using the DELETE, INSERT, and UPDATE commands.
The DROP TABLE command works on statistics tables
as of SQLite version 3.7.9. (2011-11-01)
The ALTER TABLE command does not work on statistics tables.
Appropriate care should be used when changing the content of the statistics
tables as invalid content can cause SQLite to select inefficient
query plans.  Generally speaking, one should not modify the content of
the statistics tables by any mechanism other than invoking the
ANALYZE command.  
See "Manual Control Of Query Plans Using SQLITE_STAT Tables" for
further information.

 Statistics gathered by ANALYZE are not automatically updated as
the content of the database changes.  If the content of the database
changes significantly, or if the database schema changes, then one should
consider rerunning the ANALYZE command in order to update the statistics.

 The query planner loads the content of the statistics tables
into memory when the schema is read.  Hence, when an application
changes the statistics tables directly, SQLite will not immediately
notice the changes. An application
can force the query planner to reread the statistics tables by running
ANALYZE sqlite_schema. 



3. Automatically Running ANALYZE

The PRAGMA optimize command will automatically run ANALYZE on individual
tables on an as-needed basis.  The recommended practice is for applications
to invoke the PRAGMA optimize statement just before closing each database
connection.

Each SQLite database connection records cases when the query planner would
benefit from having accurate results of ANALYZE at hand.  These records
are held in memory and accumulate over the life of a database connection.
The PRAGMA optimize command looks at those records and runs ANALYZE on only
those tables for which new or updated ANALYZE data seems likely to be useful.
In most cases PRAGMA optimize will not run ANALYZE, but it will occasionally
do so either for tables that have never before been analyzed, or for tables
that have grown significantly since they were last analyzed.

Since the actions of PRAGMA optimize are determined to some extent by
prior queries that have been evaluated on the same database connection, it
is recommended that PRAGMA optimize be deferred until the database connection
is closing and has thus had an opportunity to accumulate as much usage information
as possible.  It is also reasonable to set a timer to run PRAGMA optimize
every few hours, or every few days, for database connections that stay open
for a long time.

Applications that desire more control can run PRAGMA optimize(0x03) to 
obtain a list of ANALYZE commands that SQLite thinks are appropriate to run,
but without actually running those commands.  If the returned set is 
non-empty, the application can then make a decision about whether or not
to run the suggested ANALYZE commands, perhaps after prompting the user
for guidance.

The PRAGMA optimize command was first introduced with 
SQLite 3.18.0 (2017-03-28) and is a no-op for all prior releases
of SQLite.



4. Approximate ANALYZE For Large Databases

By default, ANALYZE does a full scan of every index.  This can be slow for
large databases.  So beginning with SQLite version 3.32.0 (2020-05-22), the
PRAGMA analysis_limit command can be used to limit the amount of
scanning performed by ANALYZE, and thus help ANALYZE to run faster,
even on very large database files.  We call this running an
"approximate ANALYZE".

The recommended usage pattern for the analysis_limit pragma is
like this:

PRAGMA analysis_limit=1000;


This pragma tells the ANALYZE command to start a full scan
of the index as it normally would.  But when the number of rows visited
reaches 1000 (or whatever other limit is specified by the pragma), the
ANALYZE command will begin taking actions to stop the scan.  If
the left-most column of the index has changed at least once during the
previous 1000 steps, then the analysis stops immediately.  But if the
left-most column has always been the same, then ANALYZE skips ahead to
the first entry with a different left-most column and reads an additional
1000 rows before terminating.

The details of the effects of the analysis limit described in the previous
paragraph are subject to change in future versions of SQLite.  But the
core idea will remain the same.  An analysis limit of N will strive to
limit the number of rows visited in each index to approximately N.

Values of N between 100 and 1000 are recommended.
Or, to disable the analysis limit, causing ANALYZE to do a
complete scan of each index, set the analysis limit to 0.  The default
value for the analysis limit is 0 for backwards compatibility.

The values placed in the sqlite_stat1 table by an approximate ANALYZE
are not exactly the same as what would be computed by an unrestricted 
analysis.  But they are usually close enough.  The index statistics in
the sqlite_stat1 table are approximations in any case, so the fact that
the results of an approximate ANALYZE are slightly different from
a traditional full scan ANALYZE has little practical impact.  It is
possible to construct a pathological case where an approximate ANALYZE
is noticeably inferior to a full-scan ANALYZE, but such cases rare in
real-world problems.

A good rule of thumb seems to be to always set "PRAGMA analysis_limit=N"
for N between 100 and 1000 prior to running either "ANALYZE" or
"PRAGMA optimize".  The results are not quite as precise, but they
are precise enough, and the fact that the results are computed so much
faster means that developers are more likely to compute them.  An
approximate ANALYZE is better than not running ANALYZE at all.

4.1. Limitations of approximate ANALYZE

The content in the sqlite_stat4 table cannot be computed with
anything less than a full scan.  Hence, if a non-zero analysis limit
is specified, the sqlite_stat4 table is not computed.


c2: DROP TABLE
c5: lang_droptable.html
c4:
The DROP TABLE statement removes a table added with the
CREATE TABLE statement.  The name specified is the
table name.  The dropped table is completely removed from the database 
schema and the disk file.  The table can not be recovered.  
All indices and triggers
associated with the table are also deleted.

The optional IF EXISTS clause suppresses the error that would normally
result if the table does not exist.

If foreign key constraints are enabled, a DROP TABLE command performs an
implicit DELETE FROM command before removing the
table from the database schema. Any triggers attached to the table are
dropped from the database schema before the implicit DELETE FROM
is executed, so this cannot cause any triggers to fire. By contrast, an
implicit DELETE FROM does cause any configured
foreign key actions to take place. 
If the implicit DELETE FROM executed
as part of a DROP TABLE command violates any immediate foreign key constraints,
an error is returned and the table is not dropped. If 
the implicit DELETE FROM causes any 
deferred foreign key constraints to be violated, and the violations still
exist when the transaction is committed, an error is returned at the time
of commit.


c2: SELECT
c5: lang_select.html
c4:
1. Overview


 
 


 
 



 
 



 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 





 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 






The SELECT statement is used to query the database.  The
result of a SELECT is zero or more rows of data where each row
has a fixed number of columns.  A SELECT statement does not make
any changes to the database.

The "" syntax diagram above attempts to show as much of the
SELECT statement syntax as possible in a single diagram, because some readers
find that helpful.  The following "" is an alternative
syntax diagrams that expresses the same syntax but tries to break the syntax 
down into smaller chunks.



 
 


 
 


 
 


 
 


 
 



 
 




 
 



 
 



 
 


 
 






 
 



 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 


 
 



 
 




 
 



 
 



 
 


 
 





 
 


 
 





 
 



 
 


 
 


 
 



 
 




 
 



 
 


 
 




 
 


 
 






Note that there are paths through the syntax diagrams that
are not allowed in practice.  Some examples:

A VALUES clause can be the first element in a compound SELECT
    that uses a WITH clause, but a simple SELECT that consists of
    just a VALUES clause cannot be preceded by a WITH clause.
The WITH clause must occur on the first SELECT of a compound SELECT.
    It cannot follow a .


These and other similar syntax restrictions are described in the text.

The SELECT statement is the most complicated command in the SQL language.
To make the description easier to follow, some of the passages below describe
the way the data returned by a SELECT statement is determined as a series of
steps. It is important to keep in mind that this is purely illustrative -
in practice neither SQLite nor any other SQL engine is required to follow 
this or any other specific process.



2. Simple Select Processing

The core of a SELECT statement is a "simple SELECT" shown by the
 and  syntax diagrams below.  
In practice, most SELECT statements are simple SELECT statements.



 
 


 
 


 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 


 
 






 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 


 
 





 
 


 
 





 
 



 
 


 
 


 
 



 
 




 
 



 
 


 
 


 
 





 
 


 
 






Generating the results of a simple SELECT
statement is presented as a four step process in the description below:


   FROM clause processing: The input data for the simple SELECT is
       determined. The input data is either implicitly a single row with 0
       columns (if there is no FROM clause) or is determined by the FROM
       clause.
   WHERE clause processing: The input data is filtered using the WHERE
       clause expression.  
   GROUP BY, HAVING and result-column expression processing: 
       The set of result rows is computed by aggregating the data according to
       any GROUP BY clause and calculating the result-set expressions for the
       rows of the filtered input dataset.  
   DISTINCT/ALL keyword processing: If the query is a "SELECT
       DISTINCT" query, duplicate rows are removed from the set of result rows.


There are two types of simple SELECT statement - aggregate and 
non-aggregate queries. A simple SELECT statement is an aggregate query if
it contains either a GROUP BY clause or one or more aggregate functions
in the result-set. Otherwise, if a simple SELECT contains no aggregate
functions or a GROUP BY clause, it is a non-aggregate query.

1. Determination of input data (FROM clause processing).




The input data used by a simple SELECT query is a set of N rows 
each M columns wide.

If the FROM clause is omitted from a simple SELECT statement, then the 
input data is implicitly a single row zero columns wide (i.e. N=1 and
M=0).

If a FROM clause is specified, the data on which a simple SELECT query
operates comes from the one or more tables or subqueries (SELECT statements
in parentheses) specified following the FROM keyword. A subquery specified
in the table-or-subquery following the FROM clause in a 
simple SELECT statement is
handled as if it was a table containing the data returned by executing the
subquery statement. Each column of the subquery has the
collation sequence and affinity of the corresponding expression
in the subquery statement.

If there is only a single table or subquery in the FROM
clause, then the input data used by the SELECT statement is the contents of the
named table. If there is more than one table or subquery in FROM clause
then the contents of all tables and/or subqueries
are joined into a single dataset for the simple SELECT statement to operate on.
Exactly how the data is combined depends on the specific  and
 used to connect the tables or subqueries together.

All joins in SQLite are based on the cartesian product of the left and
right-hand datasets. The columns of the cartesian product dataset are, in 
order, all the columns of the left-hand dataset followed by all the columns
of the right-hand dataset. There is a row in the cartesian product dataset
formed by combining each unique combination of a row from the left-hand 
and right-hand datasets. In other words, if the left-hand dataset consists of
Nleft rows of 
Mleft columns, and the right-hand dataset of
Nright rows of
Mright columns, then the cartesian product is a
dataset of 
Nleft&times;Nright
rows, each containing 
Mleft+Mright columns.

If the join-operator is "CROSS JOIN", "INNER JOIN", "JOIN" or a comma
(",") and there is no ON or USING clause, then the result of the join is
simply the cartesian product of the left and right-hand datasets. 
If join-operator does have ON or USING clauses, those are handled according to
the following bullet points:


   If there is an ON clause then the ON expression is
       evaluated for each row of the cartesian product as a 
       boolean expression. Only rows for which the expression evaluates to 
       true are included from the dataset.

   If there is a USING clause
       then each of the column names specified must exist in the datasets to 
       both the left and right of the join-operator. For each pair of named
       columns, the expression "lhs.X = rhs.X" is evaluated for each row of
       the cartesian product as a boolean expression. Only rows for which
       all such expressions evaluates to true are included from the
       result set. When comparing values as a result of a USING clause, the
       normal rules for handling affinities, collation sequences and NULL
       values in comparisons apply. The column from the dataset on the
       left-hand side of the join-operator is considered to be on the left-hand
       side of the comparison operator (=) for the purposes of collation 
       sequence and affinity precedence.

       For each pair of columns identified by a USING clause, the column
       from the right-hand dataset is omitted from the joined dataset. This 
       is the only difference between a USING clause and its equivalent ON
       constraint.

   If the NATURAL keyword is in the join-operator then an
       implicit USING clause is added to the join-constraints. The implicit
       USING clause contains each of the column names that appear in both
       the left and right-hand input datasets. If the left and right-hand
       input datasets feature no common column names, then the NATURAL keyword
       has no effect on the results of the join. A USING or ON clause may
       not be added to a join that specifies the NATURAL keyword.

   If the join-operator is a "LEFT JOIN" or "LEFT OUTER JOIN", then
       after
       the ON or USING filtering clauses have been applied, an extra row is 
       added to the output for each row in the original left-hand input 
       dataset that corresponds to no rows at all in the composite
       dataset (if any). The added rows contain NULL values in the columns
       that would normally contain values copied from the right-hand input
       dataset.  


When more than two tables are joined together as part of a FROM clause,
the join operations are processed in order from left to right. In other 
words, the FROM clause (A join-op-1 B join-op-2 C) is computed as 
((A join-op-1 B) join-op-2 C).



Side note: Special handling of CROSS JOIN.
There is no difference between the "INNER JOIN", "JOIN" and "," join
operators. They are completely interchangeable in SQLite.
The "CROSS JOIN" join operator produces the same result as the 
"INNER JOIN", "JOIN" and "," operators, but is 
handled differently by the query optimizer
in that it prevents the query optimizer from reordering
the tables in the join.  An application programmer can use the CROSS JOIN 
operator to directly influence the algorithm that is chosen to implement
the SELECT statement.  Avoid using CROSS JOIN except in specific situations 
where manual control of the query optimizer is desired.  Avoid using
CROSS JOIN early in the development of an application as doing so is
a premature
optimization.  The special handling of CROSS JOIN is an SQLite-specific
feature and is not a part of standard SQL.
       




2. WHERE clause filtering.

If a WHERE clause is specified, the WHERE expression is evaluated for 
each row in the input data as a boolean expression. Only rows for which the
WHERE clause expression evaluates to true are included from the dataset before
continuing.  Rows are excluded from the result if the WHERE clause
evaluates to either false or NULL.

For a JOIN or INNER JOIN or CROSS JOIN, there is no difference between 
a constraint expression in the WHERE clause and one in the ON clause.  However,
for a LEFT JOIN or LEFT OUTER JOIN, the difference is very important.  
In a LEFT JOIN,
the extra NULL row for the right-hand table is added after ON clause processing
but before WHERE clause processing.  A constraint of the form "left.x=right.y"
in an ON clause will therefore allow through the added all-NULL rows of the
right table.  But if that same constraint is in the WHERE clause a NULL in
"right.y" will prevent the expression "left.x=right.y" from being true, and
thus exclude that row from the output.

3. Generation of the set of result rows.




Once the input data from the FROM clause has been filtered by the
WHERE clause expression (if any), the set of result rows for the simple 
SELECT are calculated. Exactly how this is done depends on whether the simple 
SELECT is an aggregate or non-aggregate query, and whether or not a GROUP
BY clause was specified.

 The list of expressions between the SELECT and FROM keywords is known as
the result expression list.  If a result expression is the special expression
"*" then all columns in the input data are substituted for that one expression.
If the expression is the alias of a table or subquery in the FROM clause
followed by ".*" then all columns from the named table or subquery are
substituted for the single expression. It is an error to use a "*" or
"alias.*" expression in any context other than a result expression list.
It is also an error to use a "*" or "alias.*" expression in a simple SELECT
query that does not have a FROM clause.

 The number of columns in the rows returned by a simple SELECT statement
is equal to the number of expressions in the result expression list after
substitution of * and alias.* expressions. Each result row is calculated by
evaluating the expressions in the result expression list with respect to a
single row of input data or, for aggregate queries, with respect to a group
of rows.


  If the SELECT statement is a non-aggregate query, then 
    each expression in the result expression list is evaluated for each row in
    the dataset filtered by the WHERE clause.

  If the SELECT statement is an aggregate query without a GROUP
    BY clause, then each aggregate expression in the result-set is 
    evaluated once across the entire dataset. Each non-aggregate expression
    in the result-set is evaluated once for an arbitrarily selected row of
    the dataset. The same arbitrarily selected row is used for each
    non-aggregate expression. Or, if the dataset contains zero rows, then 
    each non-aggregate expression is evaluated against a row consisting
    entirely of NULL values.

   The single row of result-set data created by evaluating the aggregate
    and non-aggregate expressions in the result-set forms the result of an
    aggregate query without a GROUP BY clause. An aggregate query without a
    GROUP BY clause always returns exactly one row of data, even if there are
    zero rows of input data.

  If the SELECT statement is an aggregate query with a GROUP
    BY clause, then each of the expressions specified as part of the
    GROUP BY clause is evaluated for each row of the dataset. Each row
    is then assigned to a "group" based on the results; rows for which
    the results of evaluating the GROUP BY expressions are the same get
    assigned to the same group. For the purposes of grouping rows, NULL 
    values are considered equal. The usual rules for selecting a
    collation sequence with which to compare text values apply when evaluating
    expressions in a GROUP BY clause.  The expressions in the GROUP BY clause
    do not have to be expressions that appear in the result. The
    expressions in a GROUP BY clause may not be aggregate expressions.

    If a HAVING clause is specified, it is evaluated once for each group 
    of rows as a boolean expression. If the result of evaluating the
    HAVING clause is false, the group is discarded. If the HAVING clause is
    an aggregate expression, it is evaluated across all rows in the group. If
    a HAVING clause is a non-aggregate expression, it is evaluated with respect
    to an arbitrarily selected row from the group.  The HAVING expression may
    refer to values, even aggregate functions, that are not in the result.

    Each expression in the result-set is then evaluated once for each
    group of rows. If the expression is an aggregate expression, it is 
    evaluated across all rows in the group. Otherwise, it is evaluated against
    a single arbitrarily chosen row from within the group. If there is more
    than one non-aggregate expression in the result-set, then all such
    expressions are evaluated for the same row.

    Each group of input dataset rows contributes a single row to the 
    set of result rows. Subject to filtering associated with the DISTINCT
    keyword, the number of rows returned by an aggregate query with a GROUP
    BY clause is the same as the number of groups of rows produced by applying
    the GROUP BY and HAVING clauses to the filtered input dataset.




Side note: Bare columns in an aggregate queries.
The usual case is that all column names in an aggregate query are either
arguments to aggregate functions or else appear in the GROUP BY clause.
A result column which contains a column name that is not within an
aggregate function and that does not appear in the GROUP BY clause (if
one exists) is called a "bare" column.
Example:

SELECT a, b, sum(c) FROM tab1 GROUP BY a;

In the query above, the "a" column is part of the GROUP BY clause
and so each row of the output contains one of the distinct values for
"a".  The "c" column is contained within the sum() aggregate function
and so that output column is the sum of all "c" values in rows that
have the same value for "a".  But what is the result of the bare 
column "b"? The answer is that the "b" result will be the
value for "b" in one of the input rows that form the aggregate.
The problem is that you usually do not know which input row is used
to compute "b", and so in many cases the value for "b" is undefined.


Special processing occurs when the aggregate function is 
either min() or max().  Example:

SELECT a, b, max(c) FROM tab1 GROUP BY a;


When the min() or max() aggregate functions 
are used in an aggregate query, all bare columns in the result set 
take values from the input
row which also contains the minimum or maximum.  So in the query
above, the value of the "b" column in the output will be the value of
the "b" column in the input row that has the largest "c" value.
There is still an ambiguity if two or more of the input rows have the
same minimum or maximum value or if the query contains more than one
min() and/or max() aggregate function. Only the built-in min() 
and max() functions work this way.


4. Removal of duplicate rows (DISTINCT processing).




One of the ALL or DISTINCT keywords may follow the SELECT keyword in a 
simple SELECT statement. If the simple SELECT is a SELECT ALL, then the
entire set of result rows are returned by the SELECT. If neither ALL or
DISTINCT are present, then the behavior is as if ALL were specified. 
If the simple SELECT is a SELECT DISTINCT, then duplicate rows are removed
from the set of result rows before it is returned. For the purposes of
detecting duplicate rows, two NULL values are considered to be equal. The
usual rules apply for selecting a collation
sequence to compare text values.



3. Compound Select Statements

Two or more simple SELECT statements may be connected together to form
a compound SELECT using the UNION, UNION ALL, INTERSECT or EXCEPT operator,
as shown by the following diagram:



 
 


 
 


 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 


 
 






 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 


 
 





 
 


 
 





 
 



 
 


 
 


 
 



 
 




 
 



 
 


 
 


 
 





 
 


 
 






In a compound SELECT, all the constituent SELECTs must return the same 
number of result columns. As the components of a compound SELECT must
be simple SELECT statements, they may not contain ORDER BY or LIMIT clauses.
ORDER BY and LIMIT clauses may only occur at the end of the entire compound
SELECT, and then only if the final element of the compound is not a VALUES clause.

A compound SELECT created using UNION ALL operator returns all the rows
from the SELECT to the left of the UNION ALL operator, and all the rows
from the SELECT to the right of it. The UNION operator works the same way as
UNION ALL, except that duplicate rows are removed from the final result set.
The INTERSECT operator returns the intersection of the results of the left and
right SELECTs.  The EXCEPT operator returns the subset of rows returned by the
left SELECT that are not also returned by the right-hand SELECT. Duplicate
rows are removed from the results of INTERSECT and EXCEPT operators before the
result set is returned.

For the purposes of determining duplicate rows for the results of compound
SELECT operators, NULL values are considered equal to other NULL values and
distinct from all non-NULL values. The collation sequence used to compare 
two text values is determined as if the columns of the left and right-hand
SELECT statements were the left and right-hand operands of the equals (=)
operator, except that greater precedence is not assigned to a collation 
sequence specified with the postfix COLLATE operator. No affinity
transformations are applied to any values when comparing rows as part of a
compound SELECT. 

When three or more simple SELECTs are connected into a compound SELECT,
they group from left to right. In other words, if "A", "B" and "C" are all
simple SELECT statements, (A op B op C) is processed as ((A op B) op C).





4. The ORDER BY clause

If a SELECT statement that returns more than one row does not have an
ORDER BY clause, the order in which the rows are returned is undefined.
Or, if a SELECT statement does have an ORDER BY clause, then the list of
expressions attached to the ORDER BY determine the order in which rows
are returned to the user.


In a compound SELECT statement, only the last or right-most simple SELECT
may have an ORDER BY clause. That ORDER BY clause will apply across all elements of
the compound. If the right-most element of a compound SELECT is a VALUES clause,
then no ORDER BY clause is allowed on that statement.


Rows are first sorted based on the results of
evaluating the left-most expression in the ORDER BY list, then ties are broken
by evaluating the second left-most expression and so on. The order in which
two rows for which all ORDER BY expressions evaluate to equal values are
returned is undefined. Each ORDER BY expression may be optionally followed
by one of the keywords ASC (smaller values are returned first) or DESC (larger
values are returned first). If neither ASC or DESC are specified, rows
are sorted in ascending (smaller values first) order by default.



SQLite considers NULL values to be smaller than any other values
for sorting purposes.  Hence, NULLs naturally appear at the beginning
of an ASC order-by and at the end of a DESC order-by.  This can be changed
using the "ASC NULLS LAST" or "DESC NULLS FIRST" syntax.

Each ORDER BY expression is processed as follows:


If the ORDER BY expression is a constant integer K then the
expression is considered an alias for the K-th column of the result set
(columns are numbered from left to right starting with 1).

If the ORDER BY expression is an identifier that corresponds to
the alias of one of the output columns, then the expression is considered
an alias for that column.

Otherwise, if the ORDER BY expression is any other expression, it 
is evaluated and the returned value used to order the output rows. If
the SELECT statement is a simple SELECT, then an ORDER BY may contain any
arbitrary expressions. However, if the SELECT is a compound SELECT, then
ORDER BY expressions that are not aliases to output columns must be exactly
the same as an expression used as an output column.


For the purposes of sorting rows, values are compared in the same way
as for comparison expressions. The collation sequence used to compare
two text values is determined as follows:


  If the ORDER BY expression is assigned a collation sequence using
  the postfix COLLATE operator, then the specified collation sequence is
  used.
  Otherwise, if the ORDER BY expression is an alias to an expression
  that has been assigned a collation sequence using the postfix 
  COLLATE operator, then the collation sequence assigned to the aliased
  expression is used.
  Otherwise, if the ORDER BY expression is a column or an alias of
  an expression that is a column, then the default collation sequence for
  the column is used. 
  Otherwise, the BINARY collation sequence is used.


In a compound SELECT statement, all ORDER BY expressions are handled
as aliases for one of the result columns of the compound.
If an ORDER BY expression is not an integer alias, then SQLite searches
the left-most SELECT in the compound for a result column that matches either
the second or third rules above. If a match is found, the search stops and
the expression is handled as an alias for the result column that it has been
matched against. Otherwise, the next SELECT to the right is tried, and so on.
If no matching expression can be found in the result columns of any
constituent SELECT, it is an error. Each term of the ORDER BY clause is
processed separately and may be matched against result columns from different
SELECT statements in the compound.



5. The LIMIT clause

The LIMIT clause is used to place an upper bound on the number of rows
returned by the entire SELECT statement.

In a compound SELECT, only the
last or right-most simple SELECT may contain a LIMIT clause.  
In a compound SELECT, 
the LIMIT clause applies to the entire compound, not just the final SELECT.
If the right-most simple SELECT is a VALUES clause then no LIMIT clause
is allowed.

Any scalar expression may be used in the 
LIMIT clause, so long as it evaluates to an integer or a value that can be
losslessly converted to an integer. If the expression evaluates to a NULL 
value or any other value that cannot be losslessly converted to an integer, an
error is returned. If the LIMIT expression evaluates to a negative value,
then there is no upper bound on the number of rows returned. Otherwise, the
SELECT returns the first N rows of its result set only, where N is the value
that the LIMIT expression evaluates to. Or, if the SELECT statement would
return less than N rows without a LIMIT clause, then the entire result set is
returned. 

The expression attached to the optional OFFSET clause that may follow a
LIMIT clause must also evaluate to an integer, or a value that can be
losslessly converted to an integer. If an expression has an OFFSET clause,
then the first M rows are omitted from the result set returned by the SELECT
statement and the next N rows are returned, where M and N are the values that
the OFFSET and LIMIT clauses evaluate to, respectively. Or, if the SELECT
would return less than M+N rows if it did not have a LIMIT clause, then the
first M rows are skipped and the remaining rows (if any) are returned. If the
OFFSET clause evaluates to a negative value, the results are the same as if it
had evaluated to zero.

Instead of a separate OFFSET clause, the LIMIT clause may specify two
scalar expressions separated by a comma. In this case, the first expression
is used as the OFFSET expression and the second as the LIMIT expression.
This is counter-intuitive, as when using the OFFSET clause the second of
the two expressions is the OFFSET and the first the LIMIT. 
This reversal of the offset and limit is intentional
- it maximizes compatibility with other SQL database systems.
However, to avoid confusion, programmers are strongly encouraged to use
the form of the LIMIT clause that uses the "OFFSET" keyword and avoid
using a LIMIT clause with a comma-separated offset.



6. The VALUES clause

The phrase "VALUES(expr-list)" means the same thing
as "SELECT expr-list".  The phrase
"VALUES(expr-list-1),...,(expr-list-N)" means the same
thing as "SELECT expr-list-1 UNION ALL ... UNION ALL
SELECT expr-list-N".  Both forms are the same, except that
the number of SELECT statements in a compound is limited by
SQLITE_LIMIT_COMPOUND_SELECT whereas the number of rows in a
VALUES clause has no arbitrary limit.

There are some restrictions on the use of a VALUES clause that are
not shown on the syntax diagrams:



A VALUES clause cannot be followed by ORDER BY.


A VALUES clause cannot be followed by LIMIT.



7. The WITH Clause

SELECT statements may be optionally preceded by a single
WITH clause that defines one or more common table expressions
for use within the SELECT statement.



8. Table-valued Functions In The FROM Clause

A virtual table that contains hidden columns can be used like
a table-valued function in the FROM clause.  The arguments to the
table-valued function become constraints on the HIDDEN columns of
the virtual table.  Additional information can be found in the
virtual table documentation.


c2: REPLACE
c5: lang_replace.html
c4:
The REPLACE command is an alias for the "INSERT OR REPLACE"
variant of the INSERT command.  
This alias is provided for compatibility other SQL database engines.  See the 
INSERT command documentation for additional information.


c2: The WITH Clause
c5: lang_with.html
c4:
1. Overview


 
 


 
 



 
 


 
 



 
 



 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 





 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 






Common Table Expressions or CTEs act like temporary views that exist
only for the duration of a single SQL statement.  There are two kinds of
common table expressions: "ordinary" and "recursive". Ordinary 
common table expressions are helpful for making
queries easier to understand by factoring
subqueries out of the main SQL statement.
Recursive common table expressions
provide the ability to do hierarchical or
recursive queries of trees and graphs, a capability
that is not otherwise available in the SQL language.

All common table expressions (ordinary and recursive) are 
created by prepending a WITH clause in front of a SELECT, INSERT, DELETE,
or UPDATE statement.  A single WITH clause can specify one or more
common table expressions, some of which are ordinary and some of which
are recursive.



2. Ordinary Common Table Expressions

An ordinary common table expression works as if it were a view that
exists for the duration of a single statement.  Ordinary common table
expressions are useful for factoring out subqueries and making the overall
SQL statement easier to read and understand.

A WITH clause can contain ordinary common table expressions even if
it includes the RECURSIVE keyword.  The use of RECURSIVE does not force
common table expressions to be recursive.



3. Recursive Common Table Expressions

A recursive common table expression can be used to write a query that
walks a tree or graph.  A recursive common table expression has the same
basic syntax as an ordinary common table expression, but with the following
additional features:


 The ""
     must be a compound select where the right-most  is
     either UNION or UNION ALL.
 The table named on the left-hand side of the AS keyword must appear
     exactly once in the FROM clause of the right-most SELECT statement
     of the compound select, and nowhere else.
 The right-most SELECT of the compound select must not make use of
     aggregate or window functions.


To put it another way, a recursive common table expression must
look like the following:



 
 


 
 




Call the table named by the  in a recursive
common table expression the "recursive table".
In the  bubble diagram above, the recursive
table must appear exactly once in the FROM clause of the 
recursive-select
and must not appear anywhere else in either the
initial-select or the
recursive-select, including subqueries.
The initial-select may be
a compound select, but it may not include an ORDER BY, LIMIT, or OFFSET.
The recursive-select must be a simple select, not a compound.  The
recursive-select is allowed to include an ORDER BY, LIMIT, and/or OFFSET.

The basic algorithm for computing the content of the recursive table
is as follows:


 Run the initial-select and add the results to a queue.
 While the queue is not empty:

 Extract a single row from the queue.
 Insert that single row into the recursive table
 Pretend that the single row just extracted is the only
     row in the recursive table and run the recursive-select,
     adding all results to the queue.



The basic procedure above may modified by the following additional rules:



  If a UNION operator connects the initial-select with the
  recursive-select, then only add rows to the queue if 
  no identical row has
  been previously added to the queue.  Repeated rows are discarded before being
  added to the queue even if the repeated rows have already been extracted
  from the queue by the recursion step.  If the operator is UNION ALL,
  then all rows generated by both the initial-select and the
  recursive-select are always added to the queue even if
  they are repeats.
  When determining if a row is repeated, NULL values compare
  equal to one another and not equal to any other value.

  The LIMIT clause, if present, determines the maximum number of rows that
  will ever be added to the recursive table in step 2b.
  Once the limit is reached, the recursion stops.
  A limit of zero means that no rows are ever added to the
  recursive table, and a negative limit means an unlimited number of rows
  may be added to the recursive table.

  The OFFSET clause, if it is present and has a positive value N, prevents the
  first N rows from being added to the recursive table.
  The first N rows are still processed
  by the recursive-select &mdash; they
  just are not added to the recursive table.  Rows are not counted toward
  fulfilling the LIMIT until all OFFSET rows have been skipped.

  If an ORDER BY clause is present, it determines the order in which rows
  are extracted from the queue in step 2a.  If there is no ORDER BY clause,
  then the order in which rows are extracted is undefined.  (In the current
  implementation, the queue becomes a FIFO if the ORDER BY clause is omitted,
  but applications should not depend on that fact since it might change.)




3.1. Recursive Query Examples

The following query returns all integers between 1 and 1000000:


WITH RECURSIVE
  cnt(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM cnt WHERE x&lt;1000000)
SELECT x FROM cnt;


Consider how this query works.  The initial-select
runs first and returns a single row
with a single column "1".  This one row is added to the queue.  In
step 2a, that one row is extracted from the queue and added to "cnt".
Then the recursive-select is run in accordance with step 2c generating
a single new row with value "2" to add to the queue.  The queue still
has one row, so step 2 repeats.  The "2" row is extracted and added to the
recursive table by steps 2a and 2b.  Then the row containing 2 is used 
as if it were the complete content of the recursive table and the 
recursive-select is run again, resulting in a row with value "3" being added
to the queue.  This repeats 999999 times until finally at step 2a the
only value on the queue is a row containing 1000000.  That row is
extracted and added to the recursive table.  But this time, the
WHERE clause causes the recursive-select to return no rows, so the
queue remains empty and the recursion stops.

Optimization note:
In the discussion above, statements like "insert the row into
the recursive table" should be understood conceptually, not literally.
It sounds as if SQLite is accumulating a huge table
containing one million rows, then going back and scanning that table
from top to bottom to generate the result.  What really happens
is that the query optimizer sees that values in the
"cnt" recursive table are only used once.  So as each row is added to
the recursive table, that row is immediately returned as a result of the main
SELECT statement and then discarded.  SQLite does not accumulate
a temporary table containing a million rows.  Very little memory is
needed to run the above example.  However, if the example had used
UNION instead of UNION ALL, then SQLite would have had to keep around
all previously generated content in order to check for duplicates.
For this reason, programmers should strive to use UNION ALL instead
of UNION when feasible.

Here is a variation on the previous example:


WITH RECURSIVE
  cnt(x) AS (
     SELECT 1
     UNION ALL
     SELECT x+1 FROM cnt
      LIMIT 1000000
  )
SELECT x FROM cnt;


There are two differences in this variation.  The initial-select is
"SELECT 1" instead of "VALUES(1)".  But those are just different
syntaxes for saying exactly the same thing.  The other change is that the
recursion is stopped by a LIMIT rather than a WHERE clause.  The use of
LIMIT means that when the one-millionth row is added to the "cnt" table
(and returned by the main SELECT, thanks to the query optimizer)
then the recursion stops immediately regardless of how many rows might be
left in the queue.  On more complex queries, it can sometimes be
difficult to ensure that the WHERE clause will eventually cause the
queue to drain and the recursion to terminate.  But the LIMIT clause will
always stop the recursion.  So it is good practice to always include a
LIMIT clause as a safety if an upper bound on the size of the recursion 
is known.



3.2. Hierarchical Query Examples

Consider a table that describes the members of an organization as
well as the chain-of-command within that organization:


CREATE TABLE org(
  name TEXT PRIMARY KEY,
  boss TEXT REFERENCES org,
  height INT,
  -- other content omitted
);


Every member in the organization has a name, and most members have
a single boss.  (The head of the whole organization has a NULL
"boss" field.) The rows of the "org" table form a tree.

Here is a query that computes the average height over everyone
in Alice's organization, including Alice:


WITH RECURSIVE
  works_for_alice(n) AS (
    VALUES('Alice')
    UNION
    SELECT name FROM org, works_for_alice
     WHERE org.boss=works_for_alice.n
  )
SELECT avg(height) FROM org
 WHERE org.name IN works_for_alice;


The next example uses two 
common table expressions in a single WITH clause.  
The following table records a family tree:


CREATE TABLE family(
  name TEXT PRIMARY KEY,
  mom TEXT REFERENCES family,
  dad TEXT REFERENCES family,
  born DATETIME,
  died DATETIME, -- NULL if still alive
  -- other content
);


The "family" table is similar to the earlier "org" table except that 
now there are two parents to each member.
We want to know all living ancestors of Alice, from oldest to youngest.
An ordinary common table expression, "parent_of", is defined first.  That
ordinary CTE is a view that can be used to find all parents of any
individual.  That ordinary CTE is then used in the "ancestor_of_alice"
recursive CTE.  The recursive CTE is then used in the final query:


WITH RECURSIVE
  parent_of(name, parent) AS
    (SELECT name, mom FROM family UNION SELECT name, dad FROM family),
  ancestor_of_alice(name) AS
    (SELECT parent FROM parent_of WHERE name='Alice'
     UNION ALL
     SELECT parent FROM parent_of JOIN ancestor_of_alice USING(name))
SELECT family.name FROM ancestor_of_alice, family
 WHERE ancestor_of_alice.name=family.name
   AND died IS NULL
 ORDER BY born;




3.3. Queries Against A Graph

A version control system (VCS) will typically store the evolving
versions of a project as a directed acyclic graph (DAG).  Call each
version of the project a "checkin".  A single
checkin can have zero or more parents.  Most checkins (except the
first) have a single parent, but in the case of a merge, a checkin
might have two or three or more parents.  A schema to keep track of
checkins and the order in which they occur might look something like
this:


CREATE TABLE checkin(
  id INTEGER PRIMARY KEY,
  mtime INTEGER -- timestamp when this checkin occurred
);
CREATE TABLE derivedfrom(
  xfrom INTEGER NOT NULL REFERENCES checkin, -- parent checkin
  xto INTEGER NOT NULL REFERENCES checkin,   -- derived checkin
  PRIMARY KEY(xfrom,xto)
);
CREATE INDEX derivedfrom_back ON derivedfrom(xto,xfrom);


This graph is acyclic.  And we assume that the mtime of every
child checkin is no less than the mtime of all its parents.  But
unlike the earlier examples, this graph might have multiple paths of
differing lengths between any two checkins.

We want to know the twenty most recent ancestors in time (out of
the thousands and thousands of ancestors in the whole DAG) for
checkin "@BASELINE".  (A query similar to this is used
by the Fossil VCS to
show the N most recent ancestors of a check.  For example:
http://www.sqlite.org/src/timeline?p=trunk&n=30.)


WITH RECURSIVE
  ancestor(id,mtime) AS (
    SELECT id, mtime FROM checkin WHERE id=@BASELINE
    UNION
    SELECT derivedfrom.xfrom, checkin.mtime
      FROM ancestor, derivedfrom, checkin
     WHERE ancestor.id=derivedfrom.xto
       AND checkin.id=derivedfrom.xfrom
     ORDER BY checkin.mtime DESC
     LIMIT 20
  )
SELECT * FROM checkin JOIN ancestor USING(id);



The "ORDER BY checkin.mtime DESC" term in the recursive-select makes
the query run much faster by preventing it from following
branches that merge checkins
from long ago.  The ORDER BY forces the recursive-select to focus
on the most recent checkins, the ones we want.  Without the ORDER BY
on the recursive-select, one would be forced to compute the complete set of
thousands of ancestors, sort them all by mtime, then take the top twenty.
The ORDER BY essentially sets up a priority queue that
forces the recursive query to look at the most recent ancestors first,
allowing the use of a LIMIT clause to restrict the scope of the
query to just the checkins of interest.



3.4. Controlling Depth-First Versus Breadth-First Search Of a Tree
Using ORDER BY

An ORDER BY clause on the recursive-select can be used to control
whether the search of a tree is depth-first or breadth-first.  To
illustrate, we will use a variation on the "org" table from an example
above, without the "height" column, and with some real data inserted:


CREATE TABLE org(
  name TEXT PRIMARY KEY,
  boss TEXT REFERENCES org
) WITHOUT ROWID;
INSERT INTO org VALUES('Alice',NULL);
INSERT INTO org VALUES('Bob','Alice');
INSERT INTO org VALUES('Cindy','Alice');
INSERT INTO org VALUES('Dave','Bob');
INSERT INTO org VALUES('Emma','Bob');
INSERT INTO org VALUES('Fred','Cindy');
INSERT INTO org VALUES('Gail','Cindy');


Here is a query to show the tree structure in a breadth-first pattern:


WITH RECURSIVE
  under_alice(name,level) AS (
    VALUES('Alice',0)
    UNION ALL
    SELECT org.name, under_alice.level+1
      FROM org JOIN under_alice ON org.boss=under_alice.name
     ORDER BY 2
  )
SELECT substr('..........',1,level*3) || name FROM under_alice;


The "ORDER BY 2" (which means the same as "ORDER BY under_alice.level+1")
causes higher levels in the organization chart (with smaller "level" values)
to be processed first, resulting in a breadth-first search.  The output is:


Alice
...Bob
...Cindy
......Dave
......Emma
......Fred
......Gail


But if we change the ORDER BY clause to add the "DESC" modifier, that will
cause lower levels in the organization (with larger "level" values) to be
processed first by the recursive-select, resulting in a depth-first search:


WITH RECURSIVE
  under_alice(name,level) AS (
    VALUES('Alice',0)
    UNION ALL
    SELECT org.name, under_alice.level+1
      FROM org JOIN under_alice ON org.boss=under_alice.name
     ORDER BY 2 DESC
  )
SELECT substr('..........',1,level*3) || name FROM under_alice;


The output of this revised query is:


Alice
...Bob
......Dave
......Emma
...Cindy
......Fred
......Gail


When the ORDER BY clause is omitted from the recursive-select, the
queue behaves as a FIFO, which results in a breadth-first search.




3.5. Outlandish Recursive Query Examples

The following query computes an approximation of the Mandelbrot Set
and outputs the result as ASCII-art:


WITH RECURSIVE
  xaxis(x) AS (VALUES(-2.0) UNION ALL SELECT x+0.05 FROM xaxis WHERE x&lt;1.2),
  yaxis(y) AS (VALUES(-1.0) UNION ALL SELECT y+0.1 FROM yaxis WHERE y&lt;1.0),
  m(iter, cx, cy, x, y) AS (
    SELECT 0, x, y, 0.0, 0.0 FROM xaxis, yaxis
    UNION ALL
    SELECT iter+1, cx, cy, x*x-y*y + cx, 2.0*x*y + cy FROM m 
     WHERE (x*x + y*y) &lt; 4.0 AND iter&lt;28
  ),
  m2(iter, cx, cy) AS (
    SELECT max(iter), cx, cy FROM m GROUP BY cx, cy
  ),
  a(t) AS (
    SELECT group_concat( substr(' .+*#', 1+min(iter/7,4), 1), '') 
    FROM m2 GROUP BY cy
  )
SELECT group_concat(rtrim(t),x'0a') FROM a;


In this query, the "xaxis" and "yaxis" CTEs define the grid of points for
which the Mandelbrot Set will be approximated.  Each row in the
"m(iter,cx,cy,x,y)" CTE means that after "iter" iterations, the Mandelbrot
iteration starting at cx,cy has reached point x,y.  The number of iterations
in this example is limited to 28 (which severely limits the resolution of
the computation, but is sufficient for low-resolution ASCII-art output).
The "m2(iter,cx,cy)" CTE holds the maximum number of iterations reached when
starting at point cx,cy.
Finally, each row in the "a(t)" CTE holds a string 
which is a single line of the output ASCII-art.
The SELECT statement at the end just queries the "a" CTE to
retrieve all lines of ASCII-art, one by one.

Running the query above in an SQLite command-line shell results
in the following output:


                                    ....#
                                   ..#*..
                                 ..+####+.
                            .......+####....   +
                           ..##+*##########+.++++
                          .+.##################+.
              .............+###################+.+
              ..++..#.....*#####################+.
             ...+#######++#######################.
          ....+*################################.
 #############################################...
          ....+*################################.
             ...+#######++#######################.
              ..++..#.....*#####################+.
              .............+###################+.+
                          .+.##################+.
                           ..##+*##########+.++++
                            .......+####....   +
                                 ..+####+.
                                   ..#*..
                                    ....#
                                    +.




This next query solves a Sudoku puzzle.  The state of the puzzle is
defined by an 81-character string formed by reading entries from the
puzzle box row by row from left to right and then from top to bottom.
Blank squares in the puzzle are denoted by a "." character.  
Thus the input string:


53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79


Corresponds to a puzzle like this:



53  7   
6  195  
 98    6
8   6   3
4  8 3  1
7   2   6
 6    28
   419  5
    8  79



This is the query that solves the puzzle:


WITH RECURSIVE
  input(sud) AS (
    VALUES('53..7....6..195....98....6.8...6...34..8.3..17...2...6.6....28....419..5....8..79')
  ),
  digits(z, lp) AS (
    VALUES('1', 1)
    UNION ALL SELECT
    CAST(lp+1 AS TEXT), lp+1 FROM digits WHERE lp&lt;9
  ),
  x(s, ind) AS (
    SELECT sud, instr(sud, '.') FROM input
    UNION ALL
    SELECT
      substr(s, 1, ind-1) || z || substr(s, ind+1),
      instr( substr(s, 1, ind-1) || z || substr(s, ind+1), '.' )
     FROM x, digits AS z
    WHERE ind>0
      AND NOT EXISTS (
            SELECT 1
              FROM digits AS lp
             WHERE z.z = substr(s, ((ind-1)/9)*9 + lp, 1)
                OR z.z = substr(s, ((ind-1)%9) + (lp-1)*9 + 1, 1)
                OR z.z = substr(s, (((ind-1)/3) % 3) * 3
                        + ((ind-1)/27) * 27 + lp
                        + ((lp-1) / 3) * 6, 1)
         )
  )
SELECT s FROM x WHERE ind=0;


The "input" CTE defines the input puzzle.
The "digits" CTE defines a table that holds all digits between 1 and 9.
The work of solving the puzzle is undertaken by the "x" CTE.
An entry in x(s,ind) means that the 81-character string "s" is a valid
sudoku puzzle (it has no conflicts) and that the first unknown character
is at position "ind", or ind==0 if all character positions are filled in.
The goal, then, is to compute entries for "x" with an "ind" of 0.

The solver works by adding new entries to the "x" recursive table.
Given prior entries, the recursive-select tries to fill in a single new
position with all values between 1 and 9 that actually work in that
position.  The complicated "NOT EXISTS" subquery is the magic that
figures out whether or not each candidate "s" string is a valid
sudoku puzzle or not.

The final answer is found by looking for a string with ind==0.
If the original sudoku problem did not have a unique solution, then
the query will return all possible solutions.  If the original problem
was unsolvable, then no rows will be returned.  In this case, the unique
answer is:


534678912672195348198342567859761423426853791713924856961537284287419635345286179


The solution was computed in less than 300 milliseconds on a modern
workstation.

4. Limitations And Caveats



The WITH clause cannot be used within a CREATE TRIGGER.

The WITH clause must appear at the beginning of a top-level SELECT statement
or at the beginning of a subquery.  The WITH clause cannot be prepended to
the second or subsequent SELECT statement of a compound select.

The SQL:1999 spec requires that the RECURSIVE keyword follow WITH in any
WITH clause that includes a recursive common table expression.  However, for
compatibility with SqlServer and Oracle, SQLite does not enforce this rule.


c2: UPSERT
c5: lang_upsert.html
c4:
1. Syntax


 
 


 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 





 
 




2. Description

UPSERT is a special syntax addition to INSERT that causes the
INSERT to behave as an UPDATE or a no-op if the INSERT would violate
a uniqueness constraint.
UPSERT is not standard SQL.  UPSERT in SQLite follows the
syntax established by PostgreSQL.
UPSERT syntax was added to SQLite with version 3.24.0 (2018-06-04).

An UPSERT is an ordinary INSERT statement that is followed by
the special ON CONFLICT clause shown above.

The syntax that occurs in between the "ON CONFLICT" and "DO" keywords
is called the "conflict target".  The conflict target specifies a specific
uniqueness constraint that will trigger the upsert.  The conflict target
is required for DO UPDATE upserts, but is optional for DO NOTHING.  When
the conflict target is omitted, the upsert behavior is triggered by a
violation of any uniqueness constraint on the table of the INSERT.

If the insert operation would cause the uniqueness constraint identified
by the conflict-target clause to fail, then the insert is omitted and
either the DO NOTHING or DO UPDATE operation is performed instead.
In the case of a multi-row insert, this decision is made separately
for each row of the insert.

The special UPSERT processing happens only for uniqueness constraint on
the table that is receiving the INSERT. A "uniqueness constraint"
is an explicit UNIQUE or PRIMARY KEY constraint within
the CREATE TABLE statement, or a unique index.
UPSERT does not intervene for failed NOT NULL or foreign key constraints
or for constraints that are implemented using triggers.

Column names in the expressions of a DO UPDATE refer to the original
unchanged value of the column, before the attempted INSERT.  To use the
value that would have been inserted had the constraint not failed,
add the special "excluded." table qualifier to the column name.

Some examples will help illustrate the difference:


CREATE TABLE vocabulary(word TEXT PRIMARY KEY, count INT DEFAULT 1);
INSERT INTO vocabulary(word) VALUES('jovial')
  ON CONFLICT(word) DO UPDATE SET count=count+1;


The upsert above inserts the new vocabulary word "jovial" if that
word is not already in the dictionary, or if it is already in the
dictionary, it increments the counter.  The "count+1" expression
could also be written as "vocabulary.count".  PostgreSQL requires the
second form, but SQLite accepts either.


CREATE TABLE phonebook(name TEXT PRIMARY KEY, phonenumber TEXT);
INSERT INTO phonebook(name,phonenumber) VALUES('Alice','704-555-1212')
  ON CONFLICT(name) DO UPDATE SET phonenumber=excluded.phonenumber;


In the second example, the expression in the DO UPDATE clause is
of the form "excluded.phonenumber".  The "excluded." prefix causes the
"phonenumber" to refer to the value for phonenumber that would have been
inserted had there been no conflict.  Hence, the effect of the upsert
is to insert a phonenumber of Alice if none exists, or to overwrite
any prior phonenumber for Alice with the new one.

Note that the DO UPDATE clause acts only on the single row
that experienced the constraint error during INSERT.  It is not
necessary to include a WHERE clause that restrictions the action
to that one row.  The only use for the WHERE clause at
the end of the DO UPDATE is to optionally change the DO UPDATE
into a no-op depending on the original and/or new values.
For example:


CREATE TABLE phonebook2(
  name TEXT PRIMARY KEY,
  phonenumber TEXT,
  validDate DATE
);
INSERT INTO phonebook2(name,phonenumber,validDate)
  VALUES('Alice','704-555-1212','2018-05-08')
  ON CONFLICT(name) DO UPDATE SET
    phonenumber=excluded.phonenumber,
    validDate=excluded.validDate
  WHERE excluded.validDate>phonebook2.validDate;


In this last example, the phonebook2 entry is only
updated if the validDate for the newly inserted value is
newer than the entry already in the table.  If the table already
contains an entry with the same name and a current validDate,
then the WHERE clause causes the DO UPDATE to become a no-op.




2.1. Parsing Ambiguity

When the INSERT statement to which the UPSERT is attached
takes its values from a SELECT statement, there is a potential
parsing ambiguity.  The parser might not be able to tell if the
"ON" keyword is introducing the UPSERT or if it is the ON clause
of a join.  To work around this, the SELECT statement should always
include a WHERE clause, even if that WHERE clause is just
"WHERE true".

Ambiguous use of ON:


INSERT INTO t1 SELECT * FROM t2
ON CONFLICT(x) DO UPDATE SET y=excluded.y;


Ambiguity resolved using a WHERE clause:


INSERT INTO t1 SELECT * FROM t2 WHERE true
ON CONFLICT(x) DO UPDATE SET y=excluded.y;


3. Limitations

UPSERT does not currently work for virtual tables.


c2: SQLite Keywords
c5: lang_keywords.html
c4:
The SQL standard specifies a large number of keywords which may not
be used as the names of tables, indices, columns, databases, user-defined
functions, collations, virtual table modules, or any other named object.
The list of keywords is so long that few people can remember them all.
For most SQL code, your safest bet is to never use any English language
word as the name of a user-defined object.

If you want to use a keyword as a name, you need to quote it.  There
are four ways of quoting keywords in SQLite:




	'keyword'
	A keyword in single quotes is a string literal.

	"keyword"
	A keyword in double-quotes is an identifier.

	&#91;keyword&#93;
	A keyword enclosed in square brackets is 
        an identifier.  This is not standard SQL.  This quoting mechanism
        is used by MS Access and SQL Server and is included in SQLite for
        compatibility.

	&#96;keyword&#96;
	A keyword enclosed in grave accents (ASCII code 96) is 
        an identifier.  This is not standard SQL.  This quoting mechanism
        is used by MySQL and is included in SQLite for
        compatibility.




For resilience when confronted with historical SQL statements, SQLite
will sometimes bend the quoting rules above:


If a keyword in single
quotes (ex: 'key' or 'glob') is used in a context where
an identifier is allowed but where a string literal is not allowed, then
the token is understood to be an identifier instead of a string literal.


If a keyword in double
quotes (ex: "key" or "glob") is used in a context where
it cannot be resolved to an identifier but where a string literal
is allowed, then the token is understood to be a string literal instead
of an identifier.


Programmers are cautioned not to use the two exceptions described in
the previous bullets.  We emphasize that they exist only so that old
and ill-formed SQL statements will run correctly.  Future versions of
SQLite might raise errors instead of accepting the malformed
statements covered by the exceptions above.


SQLite adds new keywords from time to time when it takes on new features.
So to prevent your code from being broken by future enhancements, you should
normally quote any identifier that is an English language word, even if
you do not have to.



The list below shows all possible keywords used by any build of
SQLite regardless of compile-time options.  
Most reasonable configurations use most or all of these keywords,
but some keywords may be omitted when SQL language features are
disabled.
Applications can use the
sqlite3_keyword_count(), sqlite3_keyword_name(), and
sqlite3_keyword_check() interfaces to determine the keywords
recognized by SQLite at run-time.
Regardless of the compile-time configuration, any identifier that is not on
the following 145 element
list is not a keyword to the SQL parser in SQLite:




ABORT
ACTION
ADD
AFTER
ALL
ALTER
ALWAYS
ANALYZE
AND
AS
ASC
ATTACH
AUTOINCREMENT
BEFORE
BEGIN
BETWEEN
BY
CASCADE
CASE
CAST
CHECK
COLLATE
COLUMN
COMMIT
CONFLICT
CONSTRAINT
CREATE
CROSS
CURRENT
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
DATABASE
DEFAULT
DEFERRABLE
DEFERRED
DELETE
DESC
DETACH
DISTINCT
DO
DROP
EACH
ELSE
END
ESCAPE
EXCEPT
EXCLUDE
EXCLUSIVE
EXISTS
EXPLAIN
FAIL
FILTER
FIRST
FOLLOWING
FOR
FOREIGN
FROM
FULL
GENERATED
GLOB
GROUP
GROUPS
HAVING
IF
IGNORE
IMMEDIATE
IN
INDEX
INDEXED
INITIALLY
INNER
INSERT
INSTEAD
INTERSECT
INTO
IS
ISNULL
JOIN
KEY
LAST
LEFT
LIKE
LIMIT
MATCH
NATURAL
NO
NOT
NOTHING
NOTNULL
NULL
NULLS
OF
OFFSET
ON
OR
ORDER
OTHERS
OUTER
OVER
PARTITION
PLAN
PRAGMA
PRECEDING
PRIMARY
QUERY
RAISE
RANGE
RECURSIVE
REFERENCES
REGEXP
REINDEX
RELEASE
RENAME
REPLACE
RESTRICT
RIGHT
ROLLBACK
ROW
ROWS
SAVEPOINT
SELECT
SET
TABLE
TEMP
TEMPORARY
THEN
TIES
TO
TRANSACTION
TRIGGER
UNBOUNDED
UNION
UNIQUE
UPDATE
USING
VACUUM
VALUES
VIEW
VIRTUAL
WHEN
WHERE
WINDOW
WITH
WITHOUT


c2: Savepoints
c5: lang_savepoint.html
c4:
1. Syntax



 
 



 
 



 
 



2. Savepoints

 SAVEPOINTs are a method of creating transactions, similar to
BEGIN and COMMIT, except that the SAVEPOINT and RELEASE commands
are named and may be nested.

 The SAVEPOINT command starts a new transaction with a name.
The transaction names need not be unique.
A SAVEPOINT can be started either within or outside of
a BEGIN...COMMIT.  When a SAVEPOINT is the outer-most savepoint
and it is not within a BEGIN...COMMIT then the behavior is the
same as BEGIN DEFERRED TRANSACTION.

The ROLLBACK TO command reverts the state of the database back to what
it was just after the corresponding SAVEPOINT.  Note that unlike that
plain ROLLBACK command (without the TO keyword) the ROLLBACK TO command
does not cancel the transaction.  Instead of cancelling the transaction,
the ROLLBACK TO command restarts the transaction again at the beginning.
All intervening SAVEPOINTs are canceled, however.

The RELEASE command is like a COMMIT for a SAVEPOINT.
The RELEASE command causes all savepoints back to and including the 
most recent savepoint with a matching name to be removed from the 
transaction stack.  The RELEASE of an inner transaction
does not cause any changes to be written to the database file; it merely
removes savepoints from the transaction stack such that it is
no longer possible to ROLLBACK TO those savepoints.
If a RELEASE command releases the outermost savepoint, so
that the transaction stack becomes empty, then RELEASE is the same
as COMMIT.
The COMMIT command may be used to release all savepoints and
commit the transaction even if the transaction was originally started
by a SAVEPOINT command instead of a BEGIN command.

If the savepoint-name in a RELEASE command does not match any
savepoint currently in the transaction stack, then no savepoints are
released, the database is unchanged, and the RELEASE command returns
an error.

Note that an inner transaction might commit (using the RELEASE command)
but then later have its work undone by a ROLLBACK in an outer transaction.
A power failure or program crash or OS crash will cause the outer-most
transaction to rollback, undoing all changes that have occurred within
that outer transaction, even changes that have supposedly been "committed"
by the RELEASE command.  Content is not actually committed on the disk 
until the outermost transaction commits.

There are several ways of thinking about the RELEASE command:



Some people view RELEASE as the equivalent of COMMIT for a SAVEPOINT.
This is an acceptable point of view as long as one remembers that the
changes committed by an inner transaction might later be undone by a
rollback in an outer transaction.


Another view of RELEASE is that it merges a named transaction into its
parent transaction, so that the named transaction and its parent become
the same transaction.  After RELEASE, the named transaction and its parent
will commit or rollback together, whatever their fate may be.



One can also think of savepoints as
"marks" in the transaction timeline.  In this view, the SAVEPOINT command
creates a new mark, the ROLLBACK TO command rewinds the timeline back
to a point just after the named mark, and the RELEASE command
erases marks from the timeline without actually making any
changes to the database.





3. Transaction Nesting Rules

The last transaction started will be the first
transaction committed or rolled back.

The BEGIN command only works if the transaction stack is empty, or
in other words if there are no pending transactions.  If the transaction
stack is not empty when the BEGIN command is invoked, then the command
fails with an error.

The COMMIT command commits all outstanding transactions and leaves
the transaction stack empty.

The RELEASE command starts with the most recent addition to the
transaction stack and releases savepoints backwards 
in time until it releases a savepoint with a matching savepoint-name.
Prior savepoints, even savepoints with matching savepoint-names, are
unchanged.
If the RELEASE command causes the
transaction stack to become empty (if the RELEASE command releases the
outermost transaction from the stack) then the transaction commits.

The ROLLBACK command without a TO clause rolls backs all transactions
and leaves the transaction stack empty.

The ROLLBACK command with a TO clause rolls back transactions going
backwards in time back to the most recent SAVEPOINT with a matching name.
The SAVEPOINT with the matching name remains on the transaction stack,
but all database changes that occurred after that SAVEPOINT was created
are rolled back.  If the savepoint-name in a ROLLBACK TO command does not
match any SAVEPOINT on the stack, then the ROLLBACK command fails with an
error and leaves the state of the database unchanged.


c2: INSERT
c5: lang_insert.html
c4:
The INSERT statement comes in three basic forms.  

INSERT INTO table VALUES(...);
The first form (with the "VALUES" keyword) creates one or more
new rows in
an existing table. If the column-name list after
table-name is omitted then the number
of values inserted into each row
must be the same as the number of columns in the table. In this case
the result of evaluating the left-most expression from each term of
the VALUES list is inserted into the left-most column of each new row,
and so forth for each subsequent expression. If a column-name
list is specified, then the number of values in each term of the
VALUE list must match the number of
specified columns. Each of the named columns of the new row is populated
with the results of evaluating the corresponding VALUES expression. Table
columns that do not appear in the column list are populated with the 
default column value (specified as part of the CREATE TABLE statement), or
with NULL if no default value is specified.

INSERT INTO table SELECT ...;
The second form of the INSERT statement contains a SELECT statement
instead of a VALUES clause. A new entry is inserted into the table for each
row of data returned by executing the SELECT statement. If a column-list is
specified, the number of columns in the result of the SELECT must be the same
as the number of items in the column-list. Otherwise, if no column-list is
specified, the number of columns in the result of the SELECT must be the same
as the number of columns in the table. Any SELECT statement, including
compound SELECTs and SELECT statements with ORDER BY and/or LIMIT clauses, 
may be used in an INSERT statement of this form.

To avoid a parsing ambiguity, the SELECT statement should always
contain a WHERE clause, even if that clause is simply "WHERE true",
if the  is present.  Without the WHERE clause, the
parser does not know if the token "ON" is part of a join constraint
on the SELECT, or the beginning of the .

INSERT INTO table DEFAULT VALUES;
The third form of an INSERT statement is with DEFAULT VALUES.
The INSERT ... DEFAULT VALUES statement inserts a single new row into the
named table. Each column of the new row is populated with its 
default value, or with a NULL if no default value is specified 
as part of the column definition in the CREATE TABLE statement.
The  is not supported after DEFAULT VALUES.




The initial "INSERT" keyword can be replaced by
"REPLACE" or "INSERT OR action" to specify an alternative
constraint conflict resolution algorithm to use during 
that one INSERT command.
For compatibility with MySQL, the parser allows the use of the
single keyword REPLACE as an 
alias for "INSERT OR REPLACE".

The optional "schema-name." prefix on the 
table-name
is supported for top-level INSERT statements only.  The table name must be
unqualified for INSERT statements that occur within CREATE TRIGGER statements.
Similarly, the "DEFAULT VALUES" form of the INSERT statement is supported for
top-level INSERT statements only and not for INSERT statements within
triggers.


The optional "AS alias" phrase provides an alternative
name for the table into which content is being inserted.  The alias name
can be used within WHERE and SET clauses of the UPSERT.  If there is no
, then the alias is pointless, but also
harmless.

See the separate UPSERT documentation for the additional trailing
syntax that can cause an INSERT to behave as an UPDATE if the INSERT would
otherwise violate a uniqueness constraint.  The upsert clause is not
allowed on an "INSERT ... DEFAULT VALUES".


c2: CREATE INDEX
c5: lang_createindex.html
c4:
1. Syntax


 
 


 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 





 
 




The CREATE INDEX command consists of the keywords "CREATE INDEX" followed
by the name of the new index, the keyword "ON", the name of a previously
created table that is to be indexed, and a parenthesized list of table column
names and/or expressions that are used for the index key.
If the optional WHERE clause is included, then the index is a "partial index".


If the optional IF NOT EXISTS clause is present and another index
with the same name already exists, then this command becomes a no-op.

There are no arbitrary limits on the number of indices that can be
attached to a single table.  The number of columns in an index is 
limited to the value set by
sqlite3_limit(SQLITE_LIMIT_COLUMN,...).

Indexes are removed with the DROP INDEX command.



1.1. Unique Indexes

If the UNIQUE keyword appears between CREATE and INDEX then duplicate
index entries are not allowed.  Any attempt to insert a duplicate entry
will result in an error.

For the purposes of unique indices, all NULL values
are considered different from all other NULL values and are thus unique.
This is one of the two possible interpretations of the SQL-92 standard
(the language in the standard is ambiguous).  The interpretation used
by SQLite is the same and is the interpretation
followed by PostgreSQL, MySQL, Firebird, and Oracle.  Informix and
Microsoft SQL Server follow the other interpretation of the standard, which
is that all NULL values are equal to one another.



1.2. Indexes on Expressions

Expressions in an index may not reference other tables
and may not use subqueries nor functions whose result might
change (ex: random() or sqlite_version()).
Expressions in an index may only refer to columns in the table
that is being indexed.
Indexes on expression will not work with versions of SQLite prior
to version 3.9.0 (2015-10-14).
See the Indexes On Expressions document for additional information
about using general expressions in CREATE INDEX statements.



1.3. Descending Indexes

Each column name or expression can be followed by one
of the "ASC" or "DESC" keywords to indicate sort order.
The sort order may or may not be ignored depending
on the database file format, and in particular the schema format number.
The "legacy" schema format (1) ignores index
sort order.  The descending index schema format (4) takes index sort order
into account.  Only versions of SQLite 3.3.0 (2006-01-11)
and later are able to understand
the descending index format. For compatibility, version of SQLite between 3.3.0
and 3.7.9 use the legacy schema format by default.  The newer schema format is
used by default in version 3.7.10 (2012-01-16) and later.
The legacy_file_format pragma can be used to change set the specific
behavior for any version of SQLite.

1.4. NULLS FIRST and NULLS LAST

The NULLS FIRST and NULLS LAST predicates are not supported
for indexes.  For sorting purposes, SQLite considers NULL values 
to be smaller than all other values.  Hence NULL values always appear at
the beginning of an ASC index and at the end of a DESC index.



1.5. Collations

The COLLATE clause optionally following each column name
or expression defines a
collating sequence used for text entries in that column.
The default collating
sequence is the collating sequence defined for that column in the
CREATE TABLE statement.  Or if no collating sequence is otherwise defined,
the built-in BINARY collating sequence is used.


c2: DROP INDEX
c5: lang_dropindex.html
c4:
The DROP INDEX statement removes an index added
with the CREATE INDEX statement.  The index is completely removed from
the disk.  The only way to recover the index is to reenter the
appropriate CREATE INDEX command.


c2: CREATE TABLE
c5: lang_createtable.html
c4:
1. Syntax



 
 


 
 


 
 


 
 



 
 


 
 



 
 


 
 



 
 




 
 




 
 



 
 



 
 




 
 


 
 





 
 


 
 



 
 



 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 





 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 





 
 



 
 





2. The CREATE TABLE command

The "CREATE TABLE" command is used to create a new table in an SQLite 
database. A CREATE TABLE command specifies the following attributes of the
new table:


  The name of the new table.

   The database in which the new table is created. Tables may be 
      created in the main database, the temp database, or in any attached
      database.

   The name of each column in the table.

   The declared type of each column in the table.

   A default value or expression for each column in the table.

   A default collation sequence to use with each column.

   Optionally, a PRIMARY KEY for the table. Both single column and
       composite (multiple column) primary keys are supported.

   A set of SQL constraints for each table. SQLite supports UNIQUE, NOT
       NULL, CHECK and FOREIGN KEY constraints.

   Optionally, a generated column constraint.

   Whether the table is a WITHOUT ROWID table.


Every CREATE TABLE statement must specify a name for the new table.
  Table names that begin with "sqlite_" are reserved for internal use. It
  is an error to attempt to create a table with a name that starts with
  "sqlite_".

 If a schema-name is specified, it must be either "main", 
  "temp", or the name of an attached database. In this case
  the new table is created in the named database. If the "TEMP" or "TEMPORARY"
  keyword occurs between the "CREATE" and "TABLE" then the new table is
  created in the temp database. It is an error to specify both a 
  schema-name and the TEMP or TEMPORARY keyword, unless the
  schema-name is "temp". 
  If no schema name is specified and the
  TEMP keyword is not present then the table is created in the main
  database.


  It is usually an error to attempt to create a new table in a database that
  already contains a table, index or view of the same name. However, if the
  "IF NOT EXISTS" clause is specified as part of the CREATE TABLE statement and
  a table or view of the same name already exists, the CREATE TABLE command
  simply has no effect (and no error message is returned). An error is still
  returned if the table cannot be created because of an existing index, even 
  if the "IF NOT EXISTS" clause is specified.

It is not an error to create a table that has the same name as an 
  existing trigger.

Tables are removed using the DROP TABLE statement.  



2.1. CREATE TABLE ... AS SELECT Statements

A "CREATE TABLE ... AS SELECT" statement creates and populates a database
table based on the results of a SELECT statement. The table has the same
number of columns as the rows returned by the SELECT statement. The name of
each column is the same as the name of the corresponding column in the result
set of the SELECT statement. The declared type of each column is determined
by the expression affinity of the corresponding expression in the result set
of the SELECT statement, as follows:



  Expression Affinity   Column Declared Type
  TEXT                  "TEXT"
  NUMERIC               "NUM"
  INTEGER               "INT"
  REAL                  "REAL"
  BLOB (a.k.a "NONE")   "" (empty string)


A table created using CREATE TABLE AS has no PRIMARY KEY and no
constraints of any kind. The default value of each column is NULL. The default
collation sequence for each column of the new table is BINARY.

Tables created using CREATE TABLE AS are initially populated with the
rows of data returned by the SELECT statement. Rows are assigned contiguously
ascending rowid values, starting with 1, in the order that they
are returned by the SELECT statement.



3. Column Definitions

Unless it is a CREATE TABLE ... AS SELECT statement, a CREATE TABLE includes
one or more , optionally followed by a list of
.  Each column definition consists of the
name of the column, optionally followed by the declared type of the column,
then one or more optional . Included in
the definition of "column constraints" for the purposes of the previous
statement are the COLLATE and DEFAULT clauses, even though these are not really
constraints in the sense that they do not restrict the data that the table may
contain. The other constraints - NOT NULL, CHECK, UNIQUE, PRIMARY KEY and
FOREIGN KEY constraints - impose restrictions on the table data.

The number of columns in a table is limited by the SQLITE_MAX_COLUMN
compile-time parameter. A single row of a table cannot store more than
SQLITE_MAX_LENGTH bytes of data. Both of these limits can be lowered at
runtime using the sqlite3_limit() C/C++ interface.

3.1. Column Data Types

Unlike most SQL databases, SQLite does not restrict the type of data that
may be inserted into a column based on the columns declared type. Instead,
SQLite uses dynamic typing. The declared type of a column is used to
determine the affinity of the column only.



3.2. The DEFAULT clause
The DEFAULT clause specifies a default value to use for the column if no
value is explicitly provided by the user when doing an INSERT. If there
is no explicit DEFAULT clause attached to a column definition, then the 
default value of the column is NULL. An explicit DEFAULT clause may specify
that the default value is NULL, a string constant, a blob constant, a
signed-number, or any constant expression enclosed in parentheses. A
default value may also be one of the special case-independent keywords
CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. For the purposes of the
DEFAULT clause, an expression is considered constant if it
contains no sub-queries, column or table references, bound parameters,
or string literals enclosed in double-quotes instead of single-quotes.

Each time a row is inserted into the table by an INSERT statement that 
does not provide explicit values for all table columns the values stored in
the new row are determined by their default values, as follows:


  If the default value of the column is a constant NULL, text, blob or
    signed-number value, then that value is used directly in the new row.

  If the default value of a column is an expression in parentheses, then
    the expression is evaluated once for each row inserted and the results
    used in the new row.

  If the default value of a column is CURRENT_TIME, CURRENT_DATE or
    CURRENT_TIMESTAMP, then the value used in the new row is a text
    representation of the current UTC date and/or time. For CURRENT_TIME, the
    format of the value is "HH:MM:SS". For CURRENT_DATE, "YYYY-MM-DD". The
    format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".




3.3. The COLLATE clause
The COLLATE clause specifies the name of a collating sequence to use as
the default collation sequence for the column. If no COLLATE clause is
specified, the default collation sequence is BINARY.

3.4. The GENERATED ALWAYS AS clause
A column that includes a GENERATED ALWAY AS clause is a generated column.
Generated columns are supported beginning with SQLite verison 3.31.0 (2020-01-22).
See the separate documentation for details on the capabilities and
limitations of generated columns.



3.5. The PRIMARY KEY
Each table in SQLite may have at most one PRIMARY KEY. If the
  keywords PRIMARY KEY are added to a column definition, then the primary key
  for the table consists of that single column. Or, if a PRIMARY KEY clause 
  is specified as a , then the primary key of the table
  consists of the list of columns specified as part of the PRIMARY KEY clause.
  The PRIMARY KEY clause must contain only column names &mdash; the use of 
  expressions in an  of a PRIMARY KEY is not supported.
  An error is raised if more than one PRIMARY KEY clause appears in a
  CREATE TABLE statement.  The PRIMARY KEY is optional for ordinary tables
  but is required for WITHOUT ROWID tables.

If a table has a single column primary key and the declared type of that
  column is "INTEGER" and the table is not a WITHOUT ROWID table,
  then the column is known as an INTEGER PRIMARY KEY.
  See below for a description of the special properties and behaviors
  associated with an INTEGER PRIMARY KEY.

Each row in a table with a primary key must have a unique combination
  of values in its primary key columns. For the purposes of determining
  the uniqueness of primary key values, NULL values are considered distinct from
  all other values, including other NULLs. If an INSERT or UPDATE
  statement attempts to modify the table content so that two or more rows
  have identical primary key values, that is a constraint violation.

 According to the SQL standard, PRIMARY KEY should always imply NOT NULL.
  Unfortunately, due to a bug in some early versions, this is not the
  case in SQLite. Unless the column is an INTEGER PRIMARY KEY or
  the table is a WITHOUT ROWID table or the column is declared NOT NULL,
  SQLite allows NULL values in a PRIMARY KEY column.  SQLite could be fixed to
  conform to the standard, but doing so might break legacy applications.
  Hence, it has been decided to merely document the fact that SQLite
  allowing NULLs in most PRIMARY KEY columns.



3.6. UNIQUE constraints
A UNIQUE constraint is similar to a PRIMARY KEY constraint, except
  that a single table may have any number of UNIQUE constraints. For each
  UNIQUE constraint on the table, each row must contain a unique combination
  of values in the columns identified by the UNIQUE constraint. 
  For the purposes of UNIQUE constraints, NULL values
  are considered distinct from all other values, including other NULLs.
  As with PRIMARY KEYs, a UNIQUE  clause must contain
  only column names &mdash; the use of 
  expressions in an  of a UNIQUE 
  is not supported.
  

In most cases, UNIQUE and PRIMARY KEY
  constraints are implemented by creating a unique index in the database.
  (The exceptions are INTEGER PRIMARY KEY and PRIMARY KEYs on 
  WITHOUT ROWID tables.)
  Hence, the following schemas are logically equivalent:

  
  CREATE TABLE t1(a, b UNIQUE);
  CREATE TABLE t1(a, b PRIMARY KEY);
  CREATE TABLE t1(a, b);
         CREATE UNIQUE INDEX t1b ON t1(b);
  



3.7. CHECK constraints
A CHECK constraint may be attached to a column definition or
  specified as a table constraint. In practice it makes no difference. Each
  time a new row is inserted into the table or an existing row is updated,
  the expression associated with each CHECK constraint is evaluated and
  cast to a NUMERIC value in the same way as a CAST expression. If the 
  result is zero (integer value 0 or real value 0.0), then a constraint
  violation has occurred. If the CHECK expression evaluates to NULL, or
  any other non-zero value, it is not a constraint violation.
  The expression of a CHECK constraint may not contain a subquery.



3.8. NOT NULL constraints
A NOT NULL constraint may only be attached to a column definition,
  not specified as a table constraint.  Not surprisingly, a NOT NULL
  constraint dictates that the associated column may not contain a NULL value.
  Attempting to set the column value to NULL when inserting a new row or
  updating an existing one causes a constraint violation.


4. Constraint violations
Exactly how a constraint violation is dealt with is determined by the
  constraint conflict resolution algorithm. Each 
  PRIMARY KEY, UNIQUE, NOT NULL and CHECK constraint has a default conflict
  resolution algorithm. PRIMARY KEY, UNIQUE and NOT NULL constraints may be
  explicitly assigned a default conflict resolution algorithm by including
  a  in their definitions. Or, if a constraint definition
  does not include a  or it is a CHECK constraint, the default
  conflict resolution algorithm is ABORT. Different constraints within the
  same table may have different default conflict resolution algorithms. See
  the section titled ON CONFLICT for additional information.



5. ROWIDs and the INTEGER PRIMARY KEY

Except for WITHOUT ROWID tables, all rows within SQLite tables
have a 64-bit signed integer key that uniquely identifies the row within its table.
This integer is usually
called the "rowid". The rowid value can be accessed using one of the special
case-independent names "rowid", "oid", or "_rowid_" in place of a column name.
If a table contains a user defined column named "rowid", "oid" or "_rowid_",
then that name always refers the explicitly declared column and cannot be used
to retrieve the integer rowid value.

The rowid (and "oid" and "_rowid_") is omitted in WITHOUT ROWID tables.
WITHOUT ROWID tables are only available in SQLite version 3.8.2
(2013-12-06) and later.
A table that lacks the WITHOUT ROWID clause is called a "rowid table".

The data for rowid tables is stored as a B-Tree structure containing
one entry for each table row, using the rowid value as the key. This means that
retrieving or sorting records by rowid is fast. Searching for a record with a
specific rowid, or for all records with rowids within a specified range is
around twice as fast as a similar search made by specifying any other PRIMARY
KEY or indexed value.

 With one exception noted below, if a rowid table has a primary key that consists
of a single column and the declared type of that column is "INTEGER" in any mixture of
upper and lower case, then the column becomes an alias for the rowid. Such a
column is usually referred to as an "integer primary key". A PRIMARY KEY column
only becomes an integer primary key if the declared type name is exactly
"INTEGER".  Other integer type names like "INT" or "BIGINT" or "SHORT INTEGER"
or "UNSIGNED INTEGER" causes the primary key column to behave as an ordinary
table column with integer affinity and a unique index, not as an alias for
the rowid.

 The exception mentioned above is that if the declaration of a column with
declared type "INTEGER" includes an "PRIMARY KEY DESC" clause, it does not
become an alias for the rowid and is not classified as an integer primary key.
This quirk is not by design. It is due to a bug in early versions of SQLite.
But fixing the bug could result in backwards incompatibilities.
Hence, the original behavior has been retained (and documented) because odd
behavior in a corner case is far better than a compatibility break.  This means
that the following three table declarations all cause the column "x" to be an
alias for the rowid (an integer primary key):


CREATE TABLE t(x INTEGER PRIMARY KEY ASC, y, z);
CREATE TABLE t(x INTEGER, y, z, PRIMARY KEY(x ASC));
CREATE TABLE t(x INTEGER, y, z, PRIMARY KEY(x DESC));


But the following declaration does not result in "x" being an alias for
the rowid:

CREATE TABLE t(x INTEGER PRIMARY KEY DESC, y, z);


Rowid values may be modified using an UPDATE statement in the same
way as any other column value can, either using one of the built-in aliases
("rowid", "oid" or "_rowid_") or by using an alias created by an integer
primary key. Similarly, an INSERT statement may provide a value to use as the
rowid for each row inserted. Unlike normal SQLite columns, an integer primary
key or rowid column must contain integer values. Integer primary key or rowid
columns are not able to hold floating point values, strings, BLOBs, or NULLs.

If an UPDATE statement attempts to set an integer primary key or rowid column
to a NULL or blob value, or to a string or real value that cannot be losslessly
converted to an integer, a "datatype mismatch" error occurs and the statement
is aborted. If an INSERT statement attempts to insert a blob value, or a string
or real value that cannot be losslessly converted to an integer into an
integer primary key or rowid column, a "datatype mismatch" error occurs and the
statement is aborted.

If an INSERT statement attempts to insert a NULL value into a rowid or
integer primary key column, the system chooses an integer value to use as the
rowid automatically. A detailed description of how this is done is provided
separately.

The parent key of a foreign key constraint is not allowed to
use the rowid.  The parent key must used named columns only.


c2: Built-In Scalar SQL Functions
c5: lang_corefunc.html
c4:
1. Overview

The core functions shown below are available by default. 
Date &amp; Time functions,
aggregate functions,
window functions, and
JSON functions are documented separately.  An
application may define additional
functions written in C and added to the database engine using
the sqlite3_create_function() API.




abs(X)
changes()
char(X1,X2,...,XN)
coalesce(X,Y,...)
glob(X,Y)
hex(X)
ifnull(X,Y)
iif(X,Y,Z)
instr(X,Y)
last_insert_rowid()
length(X)
like(X,Y)
like(X,Y,Z)
likelihood(X,Y)
likely(X)
load_extension(X)
load_extension(X,Y)
lower(X)
ltrim(X)
ltrim(X,Y)
max(X,Y,...)
min(X,Y,...)
nullif(X,Y)
printf(FORMAT,...)
quote(X)
random()
randomblob(N)
replace(X,Y,Z)
round(X)
round(X,Y)
rtrim(X)
rtrim(X,Y)
soundex(X)
sqlite_compileoption_get(N)
sqlite_compileoption_used(X)
sqlite_offset(X)
sqlite_source_id()
sqlite_version()
substr(X,Y)
substr(X,Y,Z)
total_changes()
trim(X)
trim(X,Y)
typeof(X)
unicode(X)
unlikely(X)
upper(X)
zeroblob(N)




2. Descriptions of built-in scalar SQL functions



abs(X)
  The abs(X) function returns the absolute value of the numeric
  argument X.  Abs(X) returns NULL if X is NULL. 
  Abs(X) returns 0.0 if X is a string or blob
  that cannot be converted to a numeric value.  If X is the 
  integer -9223372036854775808 then abs(X) throws an integer overflow
  error since there is no equivalent positive 64-bit two complement value.


changes()
  The changes() function returns the number of database rows that were changed
  or inserted or deleted by the most recently completed INSERT, DELETE,
  or UPDATE statement, exclusive of statements in lower-level triggers.
  The changes() SQL function is a wrapper around the sqlite3_changes()
  C/C++ function and hence follows the same rules for counting changes.


char(X1,X2,...,XN)
  The char(X1,X2,...,XN) function returns a string composed of characters having the
   unicode code point values of integers X1 through XN, respectively.


coalesce(X,Y,...)
  The coalesce() function returns a copy of its first non-NULL argument, or
  NULL if all arguments are NULL.  Coalesce() must have at least 
  2 arguments.


glob(X,Y)
  The glob(X,Y) function is equivalent to the
  expression "Y GLOB X".
  Note that the X and Y arguments are reversed in the glob() function
  relative to the infix GLOB operator.  Y is the string and X is the
  pattern.  So, for example, the following expressions are equivalent:
  
     name GLOB '*helium*'
     glob('*helium*',name)
  
  If the sqlite3_create_function() interface is used to
  override the glob(X,Y) function with an alternative implementation then
  the GLOB operator will invoke the alternative implementation.


hex(X)
  The hex() function interprets its argument as a BLOB and returns
  a string which is the upper-case hexadecimal rendering of the content of
  that blob.


ifnull(X,Y)
  The ifnull() function returns a copy of its first non-NULL argument, or
  NULL if both arguments are NULL.  Ifnull() must have exactly 2 arguments.
  The ifnull() function is equivalent to coalesce() with two arguments.


iif(X,Y,Z)
  The iif(X,Y,Z) function returns the value Y if X is true, and Z otherwise.
  The iif(X,Y,Z) function is logically equivalent to and generates the same
  bytecode as the CASE expression "CASE WHEN X THEN Y ELSE Z END".


instr(X,Y)
  The instr(X,Y) function finds the first occurrence of string Y within 
  string X and returns the number of prior characters plus 1, or 0 if
  Y is nowhere found within X.
  Or, if X and Y are both BLOBs, then instr(X,Y) returns one
  more than the number bytes prior to the first occurrence of Y, or 0 if
  Y does not occur anywhere within X.
  If both arguments X and Y to instr(X,Y) are non-NULL and are not BLOBs
  then both are interpreted as strings.
  If either X or Y are NULL in instr(X,Y) then the result is NULL.


last_insert_rowid()
  The last_insert_rowid() function returns the ROWID
  of the last row insert from the database connection which invoked the
  function.
  The last_insert_rowid() SQL function is a wrapper around the
  sqlite3_last_insert_rowid() C/C++ interface function.


length(X)
  For a string value X, the length(X) function returns the number of 
  characters (not bytes) in X prior to the first NUL character.
  Since SQLite strings do not normally contain NUL characters, the length(X)
  function will usually return the total number of characters in the string X.
  For a blob value X, length(X) returns the number of bytes in the blob.
  If X is NULL then length(X) is NULL.
  If X is numeric then length(X) returns the length of a string
  representation of X.


like(X,Y)like(X,Y,Z)
  The like() function is used to implement the
  "Y LIKE X &#91;ESCAPE Z&#93;" expression. 
  If the optional ESCAPE clause is present, then the
  like() function is invoked with three arguments.  Otherwise, it is
  invoked with two arguments only. Note that the X and Y parameters are
  reversed in the like() function relative to the infix LIKE operator.
  X is the pattern and Y is the string to match against that pattern.
  Hence, the following expressions are equivalent:
  
     name LIKE '%neon%'
     like('%neon%',name)
  
  The sqlite3_create_function() interface can be used to override the
  like() function and thereby change the operation of the
  LIKE operator.  When overriding the like() function, it may be important
  to override both the two and three argument versions of the like() 
  function. Otherwise, different code may be called to implement the
  LIKE operator depending on whether or not an ESCAPE clause was 
  specified.


likelihood(X,Y)
  The likelihood(X,Y) function returns argument X unchanged.
  The value Y in likelihood(X,Y) must be a floating point constant
  between 0.0 and 1.0, inclusive.
  The likelihood(X) function is a no-op that the code generator
  optimizes away so that it consumes no CPU cycles during run-time
  (that is, during calls to sqlite3_step()).
  The purpose of the likelihood(X,Y) function is to provide a hint
  to the query planner that the argument X is a boolean that is
  true with a probability of approximately Y.
  The unlikely(X) function is short-hand for likelihood(X,0.0625).
  The likely(X) function is short-hand for likelihood(X,0.9375).


likely(X)
  The likely(X) function returns the argument X unchanged.
  The likely(X) function is a no-op that the code generator
  optimizes away so that it consumes no CPU cycles at
  run-time (that is, during calls to sqlite3_step()).
  The purpose of the likely(X) function is to provide a hint
  to the query planner that the argument X is a boolean value
  that is usually true. The likely(X) function is equivalent
  to likelihood(X,0.9375). See also: unlikely(X).


load_extension(X)load_extension(X,Y)
  The load_extension(X,Y) function loads SQLite extensions out of the shared
  library file named X using the entry point Y.  The result of load_extension()
  is always a NULL.  If Y is omitted then the default entry point name is used.
  The load_extension() function raises an exception if the extension fails to
  load or initialize correctly.

  The load_extension() function will fail if the extension attempts to 
  modify or delete an SQL function or collating sequence.  The
  extension can add new functions or collating sequences, but cannot
  modify or delete existing functions or collating sequences because
  those functions and/or collating sequences might be used elsewhere
  in the currently running SQL statement.  To load an extension that
  changes or deletes functions or collating sequences, use the
  sqlite3_load_extension() C-language API.

  For security reasons, extension loaded is turned off by default and must
  be enabled by a prior call to sqlite3_enable_load_extension().


lower(X)
  The lower(X) function returns a copy of string X with all ASCII characters
  converted to lower case.  The default built-in lower() function works
  for ASCII characters only.  To do case conversions on non-ASCII
  characters, load the ICU extension.


ltrim(X)ltrim(X,Y)
  The ltrim(X,Y) function returns a string formed by removing any and all
  characters that appear in Y from the left side of X.
  If the Y argument is omitted, ltrim(X) removes spaces from the left side
  of X.


max(X,Y,...)
  The multi-argument max() function returns the argument with the 
  maximum value, or return NULL if any argument is NULL. 
  The multi-argument max() function searches its arguments from left to right
  for an argument that defines a collating function and uses that collating
  function for all string comparisons.  If none of the arguments to max()
  define a collating function, then the BINARY collating function is used.
  Note that max() is a simple function when
  it has 2 or more arguments but operates as an
  aggregate function if given only a single argument.


min(X,Y,...)
  The multi-argument min() function returns the argument with the
  minimum value.
  The multi-argument min() function searches its arguments from left to right
  for an argument that defines a collating function and uses that collating
  function for all string comparisons.  If none of the arguments to min()
  define a collating function, then the BINARY collating function is used.
  Note that min() is a simple function when
  it has 2 or more arguments but operates as an 
  aggregate function if given
  only a single argument.


nullif(X,Y)
  The nullif(X,Y) function returns its first argument if the arguments are
  different and NULL if the arguments are the same.  The nullif(X,Y) function
  searches its arguments from left to right for an argument that defines a
  collating function and uses that collating function for all string
  comparisons.  If neither argument to nullif() defines a collating function
  then the BINARY is used.


printf(FORMAT,...)
  The printf(FORMAT,...) SQL function works like the sqlite3_mprintf() C-language
  function and the printf() function from the standard C library.
  The first argument is a format string that specifies how to construct the output
  string using values taken from subsequent arguments.  If the FORMAT argument is
  missing or NULL then the result is NULL.  The %n format is silently ignored and
  does not consume an argument.  The %p format is an alias for %X.  The %z format
  is interchangeable with %s.  If there are too few arguments in the argument list,
  missing arguments are assumed to have a NULL value, which is translated into
  0 or 0.0 for numeric formats or an empty string for %s.  See the
  built-in printf() documentation for additional information.


quote(X)
  The quote(X) function returns the text of an SQL literal which
  is the value of its argument suitable for inclusion into an SQL statement.
  Strings are surrounded by single-quotes with escapes on interior quotes
  as needed.  BLOBs are encoded as hexadecimal literals.
  Strings with embedded NUL characters cannot be represented as string
  literals in SQL and hence the returned string literal is truncated prior
  to the first NUL.


random()
  The random() function returns a pseudo-random integer
  between -9223372036854775808 and +9223372036854775807.


randomblob(N)
  The randomblob(N) function return an N-byte blob containing pseudo-random
  bytes. If N is less than 1 then a 1-byte random blob is returned.

  Hint:  applications can generate globally unique identifiers
  using this function together with hex() and/or
  lower() like this:

  
  hex(randomblob(16))
  lower(hex(randomblob(16)))
  


replace(X,Y,Z)
  The replace(X,Y,Z) function returns a string formed by substituting
  string Z for every occurrence of string Y in string X.  The BINARY
  collating sequence is used for comparisons.  If Y is an empty
  string then return X unchanged.  If Z is not initially
  a string, it is cast to a UTF-8 string prior to processing.


round(X)round(X,Y)
  The round(X,Y) function returns a floating-point
  value X rounded to Y digits to the right of the decimal point.
  If the Y argument is omitted, it is assumed to be 0.


rtrim(X)rtrim(X,Y)
  The rtrim(X,Y) function returns a string formed by removing any and all
  characters that appear in Y from the right side of X.
  If the Y argument is omitted, rtrim(X) removes spaces from the right
  side of X.


soundex(X)
  The soundex(X) function returns a string that is the soundex encoding 
  of the string X.
  The string "?000" is returned if the argument is NULL or contains
  no ASCII alphabetic characters.
  This function is omitted from SQLite by default.
  It is only available if the SQLITE_SOUNDEX compile-time option
  is used when SQLite is built.


sqlite_compileoption_get(N)
  The sqlite_compileoption_get() SQL function is a wrapper around the
  sqlite3_compileoption_get() C/C++ function.
  This routine returns the N-th compile-time option used to build SQLite
  or NULL if N is out of range.  See also the compile_options pragma.


sqlite_compileoption_used(X)
  The sqlite_compileoption_used() SQL function is a wrapper around the
  sqlite3_compileoption_used() C/C++ function.
  When the argument X to sqlite_compileoption_used(X) is a string which
  is the name of a compile-time option, this routine returns true (1) or
  false (0) depending on whether or not that option was used during the
  build.


sqlite_offset(X)
  The sqlite_offset(X) function returns the byte offset in the database
  file for the beginning of the record from which value would be read.
  If X is not a column in an ordinary table, then sqlite_offset(X) returns
  NULL.  The value returned by sqlite_offset(X) might reference either the
  original table or an index, depending on the query.  If the value X would
  normally be extracted from an index, the sqlite_offset(X) returns the
  offset to the corresponding index record.  If the value X would be
  extracted from the original table, then sqlite_offset(X) returns the offset
  to the table record.

  The sqlite_offset(X) SQL function is only available if SQLite is built
  using the -DSQLITE_ENABLE_OFFSET_SQL_FUNC compile-time option.


sqlite_source_id()
  The sqlite_source_id() function returns a string that identifies the
  specific version of the source code that was used to build the SQLite
  library.  The string returned by sqlite_source_id() is
  the date and time that the source code was checked in followed by
  the SHA1 hash for that check-in.  This function is
  an SQL wrapper around the sqlite3_sourceid() C interface.


sqlite_version()
  The sqlite_version() function returns the version string for the SQLite
  library that is running.  This function is an SQL
  wrapper around the sqlite3_libversion() C-interface.


substr(X,Y,Z)substr(X,Y)
  The substr(X,Y,Z) function returns a substring of input string X that begins
  with the Y-th character and which is Z characters long.
  If Z is omitted then substr(X,Y) returns all characters through the end
  of the string X beginning with the Y-th.
  The left-most character of X is number 1.  If Y is negative
  then the first character of the substring is found by counting from the
  right rather than the left.  If Z is negative then
  the abs(Z) characters preceding the Y-th character are returned.
  If X is a string then characters indices refer to actual UTF-8 
  characters.  If X is a BLOB then the indices refer to bytes.


total_changes()
  The total_changes() function returns the number of row changes
  caused by INSERT, UPDATE or DELETE
  statements since the current database connection was opened.
  This function is a wrapper around the sqlite3_total_changes()
  C/C++ interface.


trim(X)trim(X,Y)
  The trim(X,Y) function returns a string formed by removing any and all
  characters that appear in Y from both ends of X.
  If the Y argument is omitted, trim(X) removes spaces from both ends of X.


typeof(X)
  The typeof(X) function returns a string that indicates the datatype of
  the expression X: "null", "integer", "real", "text", or "blob".


unicode(X)
  The unicode(X) function returns the numeric unicode code point corresponding to
  the first character of the string X.  If the argument to unicode(X) is not a string
  then the result is undefined.


unlikely(X)
  The unlikely(X) function returns the argument X unchanged.
  The unlikely(X) function is a no-op that the code generator
  optimizes away so that it consumes no CPU cycles at
  run-time (that is, during calls to sqlite3_step()).
  The purpose of the unlikely(X) function is to provide a hint
  to the query planner that the argument X is a boolean value
  that is usually not true. The unlikely(X) function is equivalent
  to likelihood(X, 0.0625).


upper(X)
  The upper(X) function returns a copy of input string X in which all 
  lower-case ASCII characters are converted to their upper-case equivalent.


zeroblob(N)
  The zeroblob(N) function returns a BLOB consisting of N bytes of 0x00.
  SQLite manages these zeroblobs very efficiently.  Zeroblobs can be used to
  reserve space for a BLOB that is later written using 
  incremental BLOB I/O.
  This SQL function is implemented using the sqlite3_result_zeroblob()
  routine from the C/C++ interface.


c2: Date And Time Functions
c5: lang_datefunc.html
c4:
1. Overview


SQLite supports five date and time functions as follows:




 date(timestring, modifier, modifier, ...) 
 time(timestring, modifier, modifier, ...) 
 datetime(timestring, modifier, modifier, ...) 
 julianday(timestring, modifier, modifier, ...) 
 strftime(format, timestring, modifier, modifier, ...) 



All five date and time functions take a time string as an argument. 
The time string is followed by zero or more modifiers. 
The strftime() function also takes a format string as its first argument.



The date and time functions use a subset of
IS0-8601 date and time
formats.
The date() function returns the date in this format: YYYY-MM-DD. 
The time() function returns the time as HH:MM:SS. 
The datetime() function returns "YYYY-MM-DD HH:MM:SS". 
The julianday() function returns the 
Julian day - the
number of days since noon in Greenwich on November 24, 4714 B.C. 
(Proleptic Gregorian calendar).
The strftime() routine returns the date formatted according to 
the format string specified as the first argument.
The format string supports the most common substitutions found in the 
strftime() function
from the standard C library plus two new substitutions, %f and %J.
The following is a complete list of valid strftime() substitutions:






 %d  day of month: 00
 %f  fractional seconds: SS.SSS
 %H  hour: 00-24 
 %j  day of year: 001-366
 %J  Julian day number
 %m  month: 01-12
 %M  minute: 00-59
 %s  seconds since 1970-01-01
 %S  seconds: 00-59
 %w  day of week 0-6 with Sunday==0
 %W  week of year: 00-53
 %Y  year: 0000-9999
 %%  %




Notice that all other date and time functions can be expressed
in terms of strftime():




FunctionEquivalent strftime()
   date(...)        strftime('%Y-%m-%d', ...)
   time(...)        strftime('%H:%M:%S', ...)
   datetime(...)    strftime('%Y-%m-%d %H:%M:%S', ...)
   julianday(...)   strftime('%J', ...)




The only reasons for providing functions other than strftime() is
for convenience and for efficiency.


2. Time Strings

A time string can be in any of the following formats:


 YYYY-MM-DD
 YYYY-MM-DD HH:MM
 YYYY-MM-DD HH:MM:SS
 YYYY-MM-DD HH:MM:SS.SSS
 YYYY-MM-DDTHH:MM
 YYYY-MM-DDTHH:MM:SS
 YYYY-MM-DDTHH:MM:SS.SSS
 HH:MM
 HH:MM:SS
 HH:MM:SS.SSS
 now
 DDDDDDDDDD



In formats 5 through 7, the "T" is a literal character separating 
the date and the time, as required by 
ISO-8601. 
Formats 8 through 10 that specify only a time assume a date of 
2000-01-01. Format 11, the string 'now', is converted into the 
current date and time as obtained from the xCurrentTime method
of the sqlite3_vfs object in use.
The 'now' argument to date and time functions always returns exactly the
same value for multiple invocations within the same sqlite3_step() call.
Universal Coordinated Time (UTC) is used. 
Format 12 is the 
Julian day number
expressed as a floating point value.



Formats 2 through 10 may be optionally followed by a timezone indicator of the form
"&#91;+-&#93;HH:MM" or just "Z".  The date and time functions use UTC or "zulu"
time internally, and so the "Z" suffix is a no-op.  Any non-zero "HH:MM" suffix is
subtracted from the indicated date and time in order to compute zulu time.
For example, all of the following time strings are equivalent:



2013-10-07 08:23:19.120
2013-10-07T08:23:19.120Z
2013-10-07 04:23:19.120-04:00
2456572.84952685



In formats 4, 7, and 10, the fractional seconds value SS.SSS can have
one or more digits following the decimal point.  Exactly three digits are
shown in the examples because only the first three digits are significant
to the result, but the input string can have fewer or more than three digits
and the date/time functions will still operate correctly.
Similarly, format 12 is shown with 10 significant digits, but the date/time
functions will really accept as many or as few digits as are necessary to
represent the Julian day number.


3. Modifiers

The time string can be followed by zero or more modifiers that 
alter date and/or time. Each modifier
is a transformation that is applied to the time value to its left.
Modifiers are applied from left to right; order is important.
The available modifiers are as follows.


 NNN days
 NNN hours
 NNN minutes
 NNN.NNNN seconds
 NNN months
 NNN years
 start of month
 start of year
 start of day
 weekday N
 unixepoch
 localtime
 utc 


The first six modifiers (1 through 6) 
simply add the specified amount of time to the date and time 
specified by the preceding timestring and modifiers.
The 's' character at the end of the modifier names is optional.
Note that "&plusmn;NNN months" works by rendering the original date into
the YYYY-MM-DD format, adding the &plusmn;NNN to the MM month value, then
normalizing the result.  Thus, for example, the data 2001-03-31 modified
by '+1 month' initially yields 2001-04-31, but April only has 30 days
so the date is normalized to 2001-05-01.  A similar effect occurs when
the original date is February 29 of a leapyear and the modifier is
&plusmn;N years where N is not a multiple of four.

The "start of" modifiers (7 through 9) shift the date backwards 
to the beginning of the current month, year or day.

The "weekday" modifier advances the date forward, if necessary,
to the next date where the weekday number is N. Sunday is 0, Monday is 1,
and so forth.
If the date is already on the desired weekday, the "weekday" modifier
leaves the date unchanged.  

The "unixepoch" modifier (11) only works if it immediately follows 
a timestring in the DDDDDDDDDD format. 
This modifier causes the DDDDDDDDDD to be interpreted not 
as a Julian day number as it normally would be, but as
Unix Time - the 
number of seconds since 1970.  If the "unixepoch" modifier does not
follow a timestring of the form DDDDDDDDDD which expresses the number
of seconds since 1970 or if other modifiers
separate the "unixepoch" modifier from prior DDDDDDDDDD then the
behavior is undefined.
For SQLite versions before 3.16.0 (2017-01-02), 
the "unixepoch" modifier only works for
dates between 0000-01-01 00:00:00 and 5352-11-01 10:52:47 (unix times
of -62167219200 through 106751991167).



The "localtime" modifier (12) assumes the time string to its left is in
Universal Coordinated Time (UTC) and adjusts the time
string so that it displays localtime.  If "localtime"
follows a time that is not UTC, then the behavior is undefined.
The "utc" modifier is the opposite of "localtime".  
"utc" assumes that the string
to its left is in the local timezone and adjusts that string to be in UTC.
If the prior string is not in localtime, then the result of "utc" is
undefined.

4. Examples

Compute the current date.

SELECT date('now');

Compute the last day of the current month.

SELECT date('now','start of month','+1 month','-1 day');


Compute the date and time given a unix timestamp 1092941466.


    SELECT datetime(1092941466, 'unixepoch');


Compute the date and time given a unix timestamp 1092941466, and 
compensate for your local timezone.


  SELECT datetime(1092941466, 'unixepoch', 'localtime');


Compute the current unix timestamp.


  SELECT strftime('%s','now');


Compute the number of days since the signing of the US Declaration
of Independence.


  SELECT julianday('now') - julianday('1776-07-04');


Compute the number of seconds since a particular moment in 2004:


  SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56');



Compute the date of the first Tuesday in October
for the current year.



  SELECT date('now','start of year','+9 months','weekday 2');


Compute the time since the unix epoch in seconds 
(like strftime('%s','now') except includes fractional part):


  SELECT (julianday('now') - 2440587.5)*86400.0;


5. Caveats And Bugs

The computation of local time depends heavily on the whim 
of politicians and is thus difficult to get correct for 
all locales. In this implementation, the standard C library 
function localtime_r() is used to assist in the calculation of 
local time.  The 
localtime_r() C function normally only works for years
between 1970 and 2037. For dates outside this range, SQLite 
attempts to map the year into an equivalent year within 
this range, do the calculation, then map the year back.


These functions only work for dates between 0000-01-01 00:00:00
and 9999-12-31 23:59:59 (julian day numbers 1721059.5 through 5373484.5).
For dates outside that range, the results of these
functions are undefined.

Non-Vista Windows platforms only support one set of DST rules. 
Vista only supports two. Therefore, on these platforms, 
historical DST calculations will be incorrect. 
For example, in the US, in 2007 the DST rules changed. 
Non-Vista Windows platforms apply the new 2007 DST rules 
to all previous years as well. Vista does somewhat better
getting results correct back to 1986, when the rules were also changed.

All internal computations assume the 
Gregorian calendar
system.  It is also assumed that every
day is exactly 86400 seconds in duration.


c2: SQL Comment Syntax
c5: lang_comment.html
c4:
Comments are not SQL commands, but can occur within the text of
SQL queries passed to sqlite3_prepare_v2() and related interfaces.
Comments are treated as whitespace by the parser.
Comments can begin anywhere whitespace 
can be found, including inside expressions that span multiple lines.


SQL comments begin with two consecutive "-" characters (ASCII 0x2d)
and extend up to and including the next newline character (ASCII 0x0a)
or until the end of input, whichever comes first.

C-style comments begin
with "/*" and extend up to and including the next "*/" character pair
or until the end of input, whichever comes first.  C-style comments
can span multiple lines. 

Comments can appear anywhere whitespace can occur,
including inside expressions and in the middle of other SQL statements.
Comments do not nest.


c2: UPDATE
c5: lang_update.html
c4:
1. Overview



 
 


 
 



 
 


 
 


 
 



 
 



 
 



 
 


 
 






 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 



 
 


 
 





 
 


 
 





 
 


 
 



 
 




 
 



 
 


 
 


 
 



 
 



 
 



 
 


 
 







An UPDATE statement is used to modify a subset of the values stored in 
zero or more rows of the database table identified by the 
 specified as part of the UPDATE statement.

2. Details

If the UPDATE statement does not have a WHERE clause, all rows in the
table are modified by the UPDATE. Otherwise, the UPDATE affects only those
rows for which the WHERE clause
boolean expression is true. It is not an error if the
WHERE clause does not evaluate to true for any row in the table - this just
means that the UPDATE statement affects zero rows.

The modifications made to each row affected by an UPDATE statement are
determined by the list of assignments following the SET keyword. Each
assignment specifies a column-name to the left of the 
equals sign and a scalar expression to the right. 
For each affected row, the named columns
are set to the values found by evaluating the corresponding scalar 
expressions. If a single column-name appears more than once in the list of
assignment expressions, all but the rightmost occurrence is ignored. Columns
that do not appear in the list of assignments are left unmodified. The scalar
expressions may refer to columns of the row being updated. In this case all
scalar expressions are evaluated before any assignments are made.

Beginning in SQLite version 3.15.0 (2016-10-14), an assignment in
the SET clause can be a 
 on the left and a
row value of the same size on the right.


The optional "OR action" conflict clause that follows the
UPDATE keyword allows the user to nominate a specific
constraint conflict resolution algorithm to use during this one UPDATE command.
Refer to the section entitled ON CONFLICT for additional information.

2.1. Restrictions on UPDATE Statements Within CREATE TRIGGER

The following additional syntax restrictions apply to UPDATE statements that
occur within the body of a CREATE TRIGGER statement.  


  The table-name specified as part of an UPDATE 
      statement within
      a trigger body must be unqualified. In other words, the
      schema-name. prefix on the table name of the UPDATE is
      not allowed within triggers. Unless the table to which the trigger
      is attached is in the TEMP database, the table being updated by the
      trigger program must reside in the same database as it. If the table
      to which the trigger is attached is in the TEMP database, then the
      unqualified name of the table being updated is resolved in the same way
      as it is for a top-level statement (by searching first the TEMP database,
      then the main database, then any other databases in the order they were
      attached).

  The INDEXED BY and NOT INDEXED clauses are not allowed on UPDATE
      statements within triggers.

  The LIMIT and ORDER BY clauses for UPDATE are unsupported within
      triggers, regardless of the compilation options used to build SQLite.




2.2. UPDATE FROM

The UPDATE-FROM idea is an extension to SQL that allows an UPDATE
statement to be driven by other tables in the database. 
The "target" table is the specific table that is being
updated.  With UPDATE-FROM you can join the target table
against other tables in the database in order to help compute which
rows need updating and what the new values should be on those rows.
UPDATE-FROM is supported beginning in SQLite version 3.33.0
(2020-08-14).

Other relation database engines also implement UPDATE-FROM, but
because the construct is not part of the SQL standards, each product
implements UPDATE-FROM differently.  The SQLite implementation strives
to be compatible with PostgreSQL.  The SQL Server and MySQL implementations
of the same idea work a little differently.

As an example of how UPDATE-FROM can be useful, 
suppose you have a point-of-sale application that accumulates
purchases in the SALES table.  At the end of the day, you want to adjust
the INVENTORY table according to the daily sales.  To do this, you can
run an UPDATE against the INVENTORY table that adjusts the quantity by
the aggregated sales for the day.  The statement would look like this:

UPDATE inventory
   SET quantity = quantity - daily.amt
  FROM (SELECT sum(quantity) AS amt, itemId FROM sales GROUP BY 2) AS daily
 WHERE inventory.itemId = daily.itemId;



The subquery in the FROM clause computes the amount by which the
inventory should be reduced for each itemId.  That subquery is joined
against the inventory table and the quantity of each affected inventory
row is reduced by the appropriate amount.


The target table is not included in the FROM clause, unless the intent
is to do a self-join against the target table.  In the event of a self-join,
the table in the FROM clause must be aliased to a different name
than the target table.


If the join between the target table and the FROM clause results in
multiple output rows for the same target table row, then only one of
those output rows is used for updating the target table.  The output
row selected is arbitrary and might change from one release of SQLite
to the next, or from one run to the next.

2.2.1. UPDATE FROM in other SQL database engines

SQL Server also supports UPDATE FROM, but in SQL Server the target
table must be included in the FROM clause.  In other words, the
target table is named twice in the statement.  With SQL Server,
the inventory adjustment statement demonstrated above would be written
like this:

UPDATE inventory
   SET quantity = quantity - daily.amt
  FROM inventory, 
       (SELECT sum(quantity) AS amt, itemId FROM sales GROUP BY 2) AS daily
 WHERE inventory.itemId = daily.itemId;


MySQL supports the UPDATE FROM idea, but it does so without using
a FROM clause.  Instead, the complete join specification is given in between
the UPDATE and SET keywords.  The equivalent MySQL statement would be
like this:

UPDATE inventory JOIN
       (SELECT sum(quantity) AS amt, itemId FROM sales GROUP BY 2) AS daily
       USING( itemId )
   SET inventory.quantity = inventory.quantity - daily.amt;


The MySQL UPDATE statement does not have just one target table like
other systems.  Any of the tables that participate in the join can
be modified in the SET clause.  The MySQL UPDATE syntax allows you to
update multiple tables at once!

2.3. Optional LIMIT and ORDER BY Clauses

If SQLite is built with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT
compile-time option then the syntax of the UPDATE statement is extended
with optional ORDER BY and LIMIT clauses as follows:


 
 


If an UPDATE statement has a LIMIT clause, the maximum number of rows that
will be updated is found by evaluating the accompanying expression and casting
it to an integer value. A negative value is interpreted as "no limit".

If the LIMIT expression evaluates to non-negative value N and the
UPDATE statement has an ORDER BY clause, then all rows that would be updated in
the absence of the LIMIT clause are sorted according to the ORDER BY and the
first N updated. If the UPDATE statement also has an OFFSET clause,
then it is similarly evaluated and cast to an integer value. If the OFFSET
expression evaluates to a non-negative value M, then the first M
rows are skipped and the following N rows updated instead.

If the UPDATE statement has no ORDER BY clause, then all rows that
would be updated in the absence of the LIMIT clause are assembled in an
arbitrary order before applying the LIMIT and OFFSET clauses to determine 
which are actually updated.

The ORDER BY clause on an UPDATE statement is used only to determine which
rows fall within the LIMIT. The order in which rows are modified is arbitrary
and is not influenced by the ORDER BY clause.


c2: CREATE VIEW
c5: lang_createview.html
c4:
1. Syntax



 
 


 
 


 
 



 
 



 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 





 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 






2. Description

The CREATE VIEW command assigns a name to a pre-packaged 
SELECT statement. 
Once the view is created, it can be used in the FROM clause
of another SELECT in place of a table name.


If the "TEMP" or "TEMPORARY" keyword occurs in between "CREATE"
and "VIEW" then the view that is created is only visible to the
database connection that created it and is automatically deleted when
the database connection is closed.

 If a schema-name is specified, then the view 
is created in the specified database.
It is an error to specify both a schema-name
and the TEMP keyword on a VIEW, unless the schema-name 
is "temp".
If no schema name is specified, and the TEMP keyword is not present,
the VIEW is created in the main database.

You cannot DELETE, INSERT, or UPDATE a view.  Views are read-only 
in SQLite.  However, in many cases you can use an
INSTEAD OF trigger on the view to accomplish 
the same thing.  Views are removed 
with the DROP VIEW command.

If a column-name list follows 
the view-name, then that list determines
the names of the columns for the view.  If the column-name
list is omitted, then the names of the columns in the view are derived
from the names of the result-set columns in the .
The use of column-name list is recommended.  Or, if
column-name list is omitted, then the result
columns in the SELECT statement that defines the view should have
well-defined names using the 
"" syntax.
SQLite allows you to create views that depend on automatically 
generated column names, but you should avoid using them since the 
rules used to generate column names are not a defined part of the
interface and might change in future releases of SQLite.

The column-name list syntax was added in
SQLite versions 3.9.0 (2015-10-14).


c2: ALTER TABLE
c5: lang_altertable.html
c4:
1. Overview



 
 


 
 


 
 


 
 



 
 


 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 






 
 



 
 



 
 




 
 


 
 






SQLite supports a limited subset of ALTER TABLE.
The ALTER TABLE command in SQLite allows the user to rename a table,
to rename a column within a table, or to add a new column to an existing table.



2. ALTER TABLE RENAME

 The RENAME TO syntax changes the name of table-name
to new-table-name.
This command 
cannot be used to move a table between attached databases, only to rename 
a table within the same database.
If the table being renamed has triggers or indices, then these remain
attached to the table after it has been renamed.


Compatibility Note:
The behavior of ALTER TABLE when renaming a table was enhanced
in versions 3.25.0 (2018-09-15) and 3.26.0 (2018-12-01)
in order to carry the rename operation forward into triggers and
views that reference the renamed table.  This is considered an
improvement. Applications that depend on the older (and
arguably buggy) behavior can use the
PRAGMA legacy_alter_table=ON statement or the
SQLITE_DBCONFIG_LEGACY_ALTER_TABLE configuration parameter
on sqlite3_db_config() interface to make ALTER TABLE RENAME
behave as it did prior to version 3.25.0.



Beginning with release 3.25.0 (2018-09-15), references to the table
within trigger bodies and view definitions are also renamed.


 Prior to version 3.26.0 (2018-12-01), FOREIGN KEY references
to a table that is renamed were only edited if the
PRAGMA foreign_keys=ON, or in other words if
foreign key constraints were begin enforced.  With
PRAGMA foreign_keys=OFF, FOREIGN KEY constraints would not be changed
when the table that the foreign key referred to (the "parent table")
was renamed.  Beginning with version 3.26.0, FOREIGN KEY constraints
are always converted when a table is renamed, unless the
PRAGMA legacy_alter_table=ON setting is engaged.  The following
table summaries the difference:




PRAGMA foreign_keys
PRAGMA legacy_alter_table
Parent Table
references are updated
SQLite version
OffOffNo&lt; 3.26.0
OffOffYes&gt;= 3.26.0
OnOffYesall
OffOnNoall
OnOnYesall





3. ALTER TABLE RENAME COLUMN

 The RENAME COLUMN TO syntax changes the
column-name of table table-name
into new-column-name.  The column name is changed both
within the table definition itself and also within all indexes, triggers,
and views that reference the column.  If the column name change would
result in a semantic ambiguity in a trigger or view, then the RENAME
COLUMN fails with an error and no changes are applied.



4. ALTER TABLE ADD COLUMN

 The ADD COLUMN syntax
is used to add a new column to an existing table.
The new column is always appended to the end of the list of existing columns.
The  rule defines the characteristics of the new column.
The new column may take any of the forms permissible in a CREATE TABLE
statement, with the following restrictions:

The column may not have a PRIMARY KEY or UNIQUE constraint.
The column may not have a default value of CURRENT_TIME, CURRENT_DATE, 
    CURRENT_TIMESTAMP, or an expression in parentheses.
If a NOT NULL constraint is specified, then the column must have a
    default value other than NULL.
If foreign key constraints are enabled and
    a column with a 
    is added, the column must have a default value of NULL.
The column may not be GENERATED ALWAYS ... STORED,
though VIRTUAL columns are allowed.


Note also that when adding a CHECK constraint, the CHECK constraint
is not tested against preexisting rows of the table.
This can result in a table that contains data that
is in violation of the CHECK constraint.  Future versions of SQLite might
change to validate CHECK constraints as they are added.

The ALTER TABLE command works by modifying the SQL text of the schema
stored in the sqlite_schema table.
No changes are made to table content.
Because of this,
the execution time of the ALTER TABLE command is independent of
the amount of data in the table.  The ALTER TABLE command runs as quickly
on a table with 10 million rows as it does on a table with 1 row.


After ADD COLUMN has been run on a database, that database will not
be readable by SQLite version 3.1.3 (2005-02-20) and earlier.



5. Making Other Kinds Of Table Schema Changes

 The only schema altering commands directly supported by SQLite are the
"rename table", "rename column", and "add column" commands shown above.  
However, applications
can make other arbitrary changes to the format of a table using a simple
sequence of operations.
The steps to make arbitrary changes to the schema design of some table X
are as follows:



If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.


Start a transaction.


Remember the format of all indexes, triggers, and views associated with table X.
This information will be needed in step 8 below.  One way to do this is
to run a query like the following:
SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'.


Use CREATE TABLE to construct a new table "new_X" that is in the desired
revised format of table X.  Make sure that the name "new_X" does not collide
with any existing table name, of course.


Transfer content from X into new_X using a statement
like: INSERT INTO new_X SELECT ... FROM X.


Drop the old table X:  DROP TABLE X.


Change the name of new_X to X using: ALTER TABLE new_X RENAME TO X.


Use CREATE INDEX, CREATE TRIGGER, and CREATE VIEW
to reconstruct indexes, triggers, and views
associated with table X.  Perhaps use the old format of the triggers,
indexes, and views saved from step 3 above as a guide, making changes
as appropriate for the alteration.

If any views refer to table X in a way that is affected by the
schema change, then drop those views using DROP VIEW and recreate them
with whatever changes are necessary to accommodate the schema change
using CREATE VIEW.


If foreign key constraints were originally enabled
then run PRAGMA foreign_key_check to verify that the schema
change did not break any foreign key constraints.



Commit the transaction started in step 2.


If foreign keys constraints were originally enabled, reenable them now.





Caution:
Take care to follow the procedure above precisely.  The boxes below
summarize two procedures for modifying a table definition.  At first
glance, they both appear to accomplish the same thing.  However, the
procedure on the right does not always work, especially with the
enhanced rename table capabilities added by versions 3.25.0 and
3.26.0.  In the procedure on the right, the initial rename of the
table to a temporary name might corrupt references to that table in
triggers, views, and foreign key constraints.  The safe procedure on
the left constructs the revised table definition using a new temporary
name, then renames the table into its final name, which does not break
links.






Create new table
Copy data
Drop old table
Rename new into old



Rename old table
Create new table
Copy data
Drop old table


&uarr;Correct
&uarr;Incorrect



The 12-step generalized ALTER TABLE procedure
above will work even if the
schema change causes the information stored in the table to change.
So the full 12-step procedure above is appropriate for dropping a column,
changing the order of columns, adding or removing a UNIQUE constraint
or PRIMARY KEY, adding CHECK or FOREIGN KEY or NOT NULL constraints,
or changing the datatype for a column, for example.  However, a simpler
and faster procedure can optionally be used for
some changes that do no affect the on-disk content in any way.
The following simpler procedure is appropriate for removing
CHECK or FOREIGN KEY or NOT NULL constraints,
or adding, removing, or changing default values on
a column.


 Start a transaction.

 Run PRAGMA schema_version to determine the current schema
version number.  This number will be needed for step 6 below.

 Activate schema editing using 
PRAGMA writable_schema=ON.

 Run an UPDATE statement to change the definition of table X
in the sqlite_schema table: 
UPDATE sqlite_schema SET sql=... WHERE type='table' AND name='X';
Caution:  Making a change to the sqlite_schema table like this will
render the database corrupt and unreadable if the change contains
a syntax error.  It is suggested that careful testing of the UPDATE
statement be done on a separate blank database prior to using it on
a database containing important data.

 If the change to table X also affects other tables or indexes or
triggers are views within schema, then run UPDATE statements to modify
those other tables indexes and views too.  For example, if the name of
a column changes, all FOREIGN KEY constraints, triggers, indexes, and
views that refer to that column must be modified.
Caution:  Once again, making changes to the sqlite_schema 
table like this will render the database corrupt and unreadable if the 
change contains an error.  Carefully test this entire procedure
on a separate test database prior to using it on
a database containing important data and/or make backup copies of
important databases prior to running this procedure.

 Increment the schema version number using
PRAGMA schema_version=X where X is one
more than the old schema version number found in step 2 above.

 Disable schema editing using 
PRAGMA writable_schema=OFF.

 (Optional) Run PRAGMA integrity_check to verify that the
schema changes did not damage the database.

 Commit the transaction started on step 1 above.


If some future version of SQLite adds new ALTER TABLE capabilities, 
those capabilities will very likely use one of the two procedures
outlined above.



6. Why ALTER TABLE is such a problem for SQLite

Most SQL database engines store the schema already parsed into
various system tables.  On those database engines, ALTER TABLE merely 
has to make modifications to the corresponding system tables.

SQLite is different in that it stores the schema
in the sqlite_schema table as the original text of the CREATE
statements that define the schema.  Hence ALTER TABLE needs
to revise the text of the CREATE statement.  Doing
so can be tricky for certain "creative" schema designs.

The SQLite approach of storing the schema as text has advantages
for an embedded relational database.  For one, it means that the
schema takes up less space in the database file.  This is important
since a common SQLite usage pattern is to have many small,
separate database files instead of putting everything in one
big global database file, which is the usual approach for client/server
database engines.
Since the schema is duplicated in each separate database file, it is
important to keep the schema representation compact.

Storing the schema as text rather than as parsed tables also
give flexibility to the implementation.  Since the internal parse
of the schema is regenerated each time the database is opened, the
internal representation of the schema can change from one release
to the next.  This is important, as sometimes new features require
enhancements to the internal schema representation.  Changing the
internal schema representation would be much more difficult if the
schema representation was exposed in the database file.  So, in other
words, storing the schema as text helps maintain backwards 
compatibility, and helps ensure that older database files can be
read and written by newer versions of SQLite.

Storing the schema as text also makes the 
SQLite database file format easier to define, document, and 
understand. This helps make SQLite database files a
recommended storage format for long-term archiving of data.

The downside of storing schema a text is that it can make
the schema tricky to modify.  And for that reason, the ALTER TABLE
support in SQLite has traditionally lagged behind other SQL
database engines that store their schemas as parsed system tables
that are easier to modify.


c2: Transaction
c5: lang_transaction.html
c4:
1. Transaction Control Syntax



 
 



 
 



 
 



2. Transactions


No reads or writes occur except within a transaction.
Any command that accesses the database (basically, any SQL command,
except a few PRAGMA statements)
will automatically start a transaction if
one is not already in effect.  Automatically started transactions
are committed when the last SQL statement finishes.



Transactions can be started manually using the BEGIN
command.  Such transactions usually persist until the next
COMMIT or ROLLBACK command.  But a transaction will also 
ROLLBACK if the database is closed or if an error occurs
and the ROLLBACK conflict resolution algorithm is specified.
See the documentation on the ON CONFLICT
clause for additional information about the ROLLBACK
conflict resolution algorithm.



END TRANSACTION is an alias for COMMIT.


 Transactions created using BEGIN...COMMIT do not nest.
For nested transactions, use the SAVEPOINT and RELEASE commands.
The "TO SAVEPOINT name" clause of the ROLLBACK command shown
in the syntax diagram above is only applicable to SAVEPOINT
transactions.  An attempt to invoke the BEGIN command within
a transaction will fail with an error, regardless of whether
the transaction was started by SAVEPOINT or a prior BEGIN.
The COMMIT command and the ROLLBACK command without the TO clause
work the same on SAVEPOINT transactions as they do with transactions
started by BEGIN.

2.1. Read transactions versus write transactions

SQLite supports multiple simultaneous read transactions
coming from separate database connections, possibly in separate
threads or processes, but only one simultaneous write transaction.


A read transaction is used for reading only.  A write transaction
allows both reading and writing.  A read transaction is started
by a SELECT statement, and a write transaction is started by 
statements like CREATE, DELETE, DROP, INSERT, or UPDATE (collectively
"write statements").  If a write statement occurs while
a read transaction is active, then the read transaction is upgraded
to a write transaction if possible.  If some other database connection
has already modified the database or is already in the process of
modifying the database, then upgrading to a write transaction is
not possible and the write statement will fail with SQLITE_BUSY.



While a read transaction is active, any changes to the database that
are implemented by separate database connections will not be seen
by the database connection that started the read transaction.  If database
connection X is holding a read transaction, it is possible that some
other database connection Y might change the content of the database
while X's transaction is still open, however X will not be able to see 
those changes until after the transaction ends.  While its read
transaction is active, X will continue to see an historic snapshot of
the database prior to the changes implemented by Y.





2.2. DEFERRED, IMMEDIATE, and EXCLUSIVE transactions


Transactions can be DEFERRED, IMMEDIATE, or EXCLUSIVE.
The default transaction behavior is DEFERRED.



DEFERRED means that the transaction does not actually
start until the database is first accessed.  Internally,
the BEGIN DEFERRED statement merely sets a flag on the database 
connection that turns off the automatic commit that would normally
occur when the last statement finishes.  This causes the transaction
that is automatically started to persist until an explicit
COMMIT or ROLLBACK or until a rollback is provoked by an error
or an ON CONFLICT ROLLBACK clause.  If the first statement after
BEGIN DEFERRED is a SELECT, then a read transaction is started.
Subsequent write statements will upgrade the transaction to a
write transaction if possible, or return SQLITE_BUSY.  If the
first statement after BEGIN DEFERRED is a write statement, then
a write transaction is started.



IMMEDIATE cause the database connection to start a new write
immediately, without waiting for a write statement.  The 
BEGIN IMMEDIATE might fail with SQLITE_BUSY if another write
transaction is already active on another database connection.



EXCLUSIVE is similar to IMMEDIATE in that a write transaction
is started immediately.  EXCLUSIVE and IMMEDIATE are the same
in WAL mode, but in other journaling modes, EXCLUSIVE prevents
other database connections from reading the database while the
transaction is underway.


2.3. Implicit versus explicit transactions


An implicit transaction (a transaction that is started automatically,
not a transaction started by BEGIN) is committed automatically when
the last active statement finishes.  A statement finishes when its
last cursor closes, which is guaranteed to happen when the
prepared statement is reset or
finalized.  Some statements might "finish"
for the purpose of transaction control prior to being reset or finalized,
but there is no guarantee of this.  The only way to ensure that a
statement has "finished" is to invoke sqlite3_reset() or
sqlite3_finalize() on that statement.  An open sqlite3_blob used for
incremental BLOB I/O also counts as an unfinished statement.
The sqlite3_blob finishes when it is closed.



The explicit COMMIT command runs immediately, even if there are
pending SELECT statements.  However, if there are pending
write operations, the COMMIT command
will fail with an error code SQLITE_BUSY.



An attempt to execute COMMIT might also result in an SQLITE_BUSY return code
if an another thread or process has an open read connection.
When COMMIT fails in this
way, the transaction remains active and the COMMIT can be retried later
after the reader has had a chance to clear.



In very old versions of SQLite (before version 3.7.11 - 2012-03-20)
the ROLLBACK will fail with an error code 
SQLITE_BUSY if there are any pending queries.  In more recent
versions of SQLite, the ROLLBACK will proceed and pending statements
will often be aborted, causing them to return an SQLITE_ABORT or
SQLITE_ABORT_ROLLBACK error.
In SQLite version 3.8.8 (2015-01-16) and later,
a pending read will continue functioning
after the ROLLBACK as long as the ROLLBACK does not modify the database
schema.



If PRAGMA journal_mode is set to OFF (thus disabling the rollback journal
file) then the behavior of the ROLLBACK command is undefined.


3. Response To Errors Within A Transaction

 If certain kinds of errors occur within a transaction, the
transaction may or may not be rolled back automatically.  The
errors that can cause an automatic rollback include:


 SQLITE_FULL: database or disk full
 SQLITE_IOERR: disk I/O error
 SQLITE_BUSY: database in use by another process
 SQLITE_NOMEM: out of memory



For all of these errors, SQLite attempts to undo just the one statement
it was working on and leave changes from prior statements within the
same transaction intact and continue with the transaction.  However, 
depending on the statement being evaluated and the point at which the
error occurs, it might be necessary for SQLite to rollback and
cancel the entire transaction.  An application can tell which
course of action SQLite took by using the
sqlite3_get_autocommit() C-language interface.

It is recommended that applications respond to the errors
listed above by explicitly issuing a ROLLBACK command.  If the 
transaction has already been rolled back automatically
by the error response, then the ROLLBACK command will fail with an
error, but no harm is caused by this.

Future versions of SQLite may extend the list of errors which
might cause automatic transaction rollback.  Future versions of
SQLite might change the error response.  In particular, we may
choose to simplify the interface in future versions of SQLite by
causing the errors above to force an unconditional rollback.


c2: DELETE
c5: lang_delete.html
c4:
1. Overview



 
 


 
 


 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 






 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 





 
 




The DELETE command removes records from the table identified by the
   .

If the WHERE clause is not present, all records in the table are deleted.
   If a WHERE clause is supplied, then only those rows for which the
   WHERE clause boolean expression is true are deleted.
   Rows for which the expression is false or NULL are retained.

2. Restrictions on DELETE Statements Within CREATE TRIGGER

The following restrictions apply to DELETE statements that occur within the
   body of a CREATE TRIGGER statement:


  The table-name specified as part of a 
    DELETE statement within
    a trigger body must be unqualified.  In other words, the
    schema-name. prefix on the table name is not allowed 
    within triggers. If the table to which the trigger is attached is
    not in the temp database, then DELETE statements within the trigger
    body must operate on tables within the same database as it. If the table
    to which the trigger is attached is in the TEMP database, then the
    unqualified name of the table being deleted is resolved in the same way as
    it is for a top-level statement (by searching first the TEMP database, then
    the main database, then any other databases in the order they were
    attached).
    
  The INDEXED BY and NOT INDEXED clauses are not allowed on DELETE
    statements within triggers.

  The LIMIT and ORDER BY clauses (described below) are unsupported for
    DELETE statements within triggers.


3. Optional LIMIT and ORDER BY clauses

If SQLite is compiled with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT
compile-time option, then the syntax of the DELETE statement is
extended by the addition of optional ORDER BY and LIMIT clauses:


 
 


If a DELETE statement has a LIMIT clause, the maximum number of rows that
will be deleted is found by evaluating the accompanying expression and casting
it to an integer value. If the result of the evaluating the LIMIT clause
cannot be losslessly converted to an integer value, it is an error. A 
negative LIMIT value is interpreted as "no limit". If the DELETE statement 
also has an OFFSET clause, then it is similarly evaluated and cast to an
integer value. Again, it is an error if the value cannot be losslessly
converted to an integer. If there is no OFFSET clause, or the calculated
integer value is negative, the effective OFFSET value is zero.

If the DELETE statement has an ORDER BY clause, then all rows that would 
be deleted in the absence of the LIMIT clause are sorted according to the 
ORDER BY. The first M rows, where M is the value found by
evaluating the OFFSET clause expression, are skipped, and the following 
N, where N is the value of the LIMIT expression, are deleted.
If there are less than N rows remaining after taking the OFFSET clause
into account, or if the LIMIT clause evaluated to a negative value, then all
remaining rows are deleted.

If the DELETE statement has no ORDER BY clause, then all rows that
would be deleted in the absence of the LIMIT clause are assembled in an
arbitrary order before applying the LIMIT and OFFSET clauses to determine 
the subset that are actually deleted.

The ORDER BY clause on a DELETE statement is used only to determine which
rows fall within the LIMIT. The order in which rows are deleted is arbitrary
and is not influenced by the ORDER BY clause.



4. The Truncate Optimization

When the WHERE is omitted from a DELETE statement and the table
being deleted has no triggers,
SQLite uses an optimization to erase the entire table content
without having to visit each row of the table individually.
This "truncate" optimization makes the delete run much faster.
Prior to SQLite version 3.6.5 (2008-11-12), the truncate optimization
also meant that the sqlite3_changes() and
sqlite3_total_changes() interfaces
and the count_changes pragma
will not actually return the number of deleted rows.  
That problem has been fixed as of version 3.6.5 (2008-11-12).

The truncate optimization can be permanently disabled for all queries
by recompiling
SQLite with the SQLITE_OMIT_TRUNCATE_OPTIMIZATION compile-time switch.

The truncate optimization can also be disabled at runtime using
the sqlite3_set_authorizer() interface.  If an authorizer callback
returns SQLITE_IGNORE for an SQLITE_DELETE action code, then
the DELETE operation will proceed but the truncate optimization will
be bypassed and rows will be deleted one by one.


c2: EXPLAIN
c5: lang_explain.html
c4:
1. Syntax

 
 


2. Description

An SQL statement can be preceded by the keyword "EXPLAIN" or
by the phrase "EXPLAIN QUERY PLAN".  Either modification causes the
SQL statement to behave as a query and to return information about
how the SQL statement would have operated if the EXPLAIN keyword or
phrase had been omitted.

The output from EXPLAIN and EXPLAIN QUERY PLAN is intended for
interactive analysis and troubleshooting only.  The details of the 
output format are subject to change from one release of SQLite to the next.
Applications should not use EXPLAIN or EXPLAIN QUERY PLAN since
their exact behavior is variable and only partially documented.

When the EXPLAIN keyword appears by itself it causes the statement
to behave as a query that returns the sequence of 
virtual machine instructions it would have used to execute the command had
the EXPLAIN keyword not been present. When the EXPLAIN QUERY PLAN phrase
appears, the statement returns high-level information regarding the query
plan that would have been used.

The EXPLAIN QUERY PLAN command is described in 
more detail here.

2.1. EXPLAIN operates at run-time, not at prepare-time

The EXPLAIN and EXPLAIN QUERY PLAN prefixes affect the behavior of
running a prepared statement using sqlite3_step().  The process of
generating a new prepared statement using sqlite3_prepare() or similar
is (mostly) unaffected by EXPLAIN.  (The exception to the previous sentence
is that some special opcodes used by EXPLAIN QUERY PLAN are omitted when
building an EXPLAIN QUERY PLAN prepared statement, as a performance
optimization.)

This means that actions that occur during sqlite3_prepare() are
unaffected by EXPLAIN.



Some PRAGMA statements do their work during sqlite3_prepare() rather
than during sqlite3_step().  Those PRAGMA statements are unaffected
by EXPLAIN.  They operate the same with or without the EXPLAIN prefix.
The set of PRAGMA statements that are unaffected by EXPLAIN can vary
from one release to the next.  Some PRAGMA statements operate during
sqlite3_prepare() depending on their arguments.  For consistent
results, avoid using EXPLAIN on PRAGMA statements.


The authorizer callback is invoked regardless of the presence of
EXPLAIN or EXPLAIN QUERY PLAN.


c2: ATTACH DATABASE
c5: lang_attach.html
c4:
1. Overview


 
 


 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 






 The ATTACH DATABASE statement adds another database 
file to the current database connection. 
Database files that were previously attached can be removed using
the DETACH DATABASE command.

2. Details

The filename for the database to be attached is the value of
the expression that occurs before the AS keyword.
The filename of the database follows the same semantics as the
filename argument to sqlite3_open() and sqlite3_open_v2(); the
special name ":memory:" results in an in-memory database and an
empty string results in a new temporary database.
The filename argument can be a URI filename if URI filename processing
is enable on the database connection.  The default behavior is for
URI filenames to be disabled, however that might change in a future release
of SQLite, so application developers are advised to plan accordingly.

The name that occurs after the AS keyword is the name of the database
used internally by SQLite.
The schema-names 'main' and 
'temp' refer to the main database and the database used for 
temporary tables.  The main and temp databases cannot be attached or
detached.

 Tables in an attached database can be referred to using the syntax 
schema-name.table-name.  If the name of the table is unique
across all attached databases and the main and temp databases, then the
schema-name prefix is not required.  If two or more tables in
different databases have the same name and the 
schema-name prefix is not used on a table reference, then the
table chosen is the one in the database that was least recently attached.


Transactions involving multiple attached databases are atomic,
assuming that the main database is not ":memory:" and the 
journal_mode is not WAL.  If the main
database is ":memory:" or if the journal_mode is WAL, then 
transactions continue to be atomic within each individual
database file. But if the host computer crashes in the middle
of a COMMIT where two or more database files are updated,
some of those files might get the changes where others
might not.


 There is a limit, set using sqlite3_limit() and 
SQLITE_LIMIT_ATTACHED, to the number of databases that can be
simultaneously attached to a single database connection.


c2: VACUUM
c5: lang_vacuum.html
c4:
1. Syntax


 
 



2. Description

  The VACUUM command rebuilds the database file, repacking it into a minimal
  amount of disk space. There are several 
  reasons an application might do this:


    Unless SQLite is running in "auto_vacuum=FULL" mode, when a large
     amount of data is deleted from the database file it leaves behind empty
     space, or "free" database pages. This means the database file might
     be larger than strictly necessary. Running VACUUM to rebuild the 
     database reclaims this space and reduces the size of the database file.

    Frequent inserts, updates, and deletes can cause the database file
     to become fragmented - where data for a single table or index is scattered 
     around the database file. Running VACUUM ensures that each table and
     index is largely stored contiguously within the database file. In some
     cases, VACUUM may also reduce the number of partially filled pages in
     the database, reducing the size of the database file further.

    When content is deleted from an SQLite database, the content is not
     usually erased but rather the space used to hold the content is marked as
     being available for reuse.  This can allow deleted content to be recovered
     by a hacker or by forensic analysis.  Running VACUUM will clean the database
     of all traces of deleted content, thus preventing an adversary from recovering
     deleted content.  Using VACUUM in this way is an alternative to setting
     PRAGMA secure_delete=ON. 

    Normally, the database page_size and whether or not the database
     supports auto_vacuum must be configured before the database file is
     actually created. However, when not in write-ahead log mode, the 
     page_size and/or auto_vacuum properties of an existing database may be
     changed by using the page_size  and/or 
     pragma auto_vacuum pragmas and then immediately VACUUMing
     the database. When in write-ahead log mode, only the auto_vacuum
     support property can be changed using VACUUM.


By default, VACUUM only works only on the main database.
Attached databases can be vacuumed by appending the appropriate
schema-name to the VACUUM statement.

Compatibility Warning: The ability to vacuum attached databases was
added in version 3.15.0 (2016-10-14).  Prior to that, a 
schema-name added to the
VACUUM statement would be silently ignored and the "main" schema would be
vacuumed.



2.1. VACUUM with an INTO clause

If the INTO clause is included, then the original database file is
unchanged and a new database is created in the filename given by the
argument to the INTO clause.  The new database will contain the same
logical content as the original database, fully vacuumed.


The VACUUM command with an INTO clause is an alternative to the
backup API for generating backup copies of a live database.
The advantage of using VACUUM INTO is that the resulting backup
database is minimal in size and hence the amount of filesystem
I/O may be reduced.  Also, all deleted content is purged from the
backup, leaving behind no forensic traces.  On the other hand,
the backup API uses fewer CPU cycles and can be executed
incrementally.


The filename in the INTO clause can be an arbitrary SQL expression
that evaluates to a string.
The file named by the INTO clause must not previously exist, or
else it must be an empty file, or the VACUUM INTO command will
fail with an error.


The argument to INTO can be a URI filename if URI filenames
are enabled.
URL filenames are enabled if any of the following are true:

 The SQLite library was compiled with -DSQLITE_USE_URI=1.
 The sqlite3_config(SQLITE_CONFIG_URI,1) interfaces was
     invoked at start-time.
 The database connection that is running the VACUUM INTO
     statement was originally opened using the
     SQLITE_OPEN_URI flag.



The VACUUM INTO command is transactional in the sense that
the generated output database is a consistent snapshot of the
original database.  However, if the VACUUM INTO command is
interrupted by an unplanned shutdown or power lose, then
the generated output database might be incomplete and corrupt.
Also, SQLite does not invoke fsync() or FlushFileBuffers()
on the generated database to ensure that it has reached
non-volatile storage before completing.




3. How VACUUM works

The VACUUM command works by copying the contents of the database into
a temporary database file and then overwriting the original with the 
contents of the temporary file. When overwriting the original, a rollback
journal or write-ahead log WAL file is used just as it would be for any
other database transaction. This means that when VACUUMing a database, 
as much as twice the size of the original database file is required in free
disk space.

The VACUUM INTO command works the same way except that it uses the file
named on the INTO clause in place of the temporary database and omits the
step of copying the vacuumed database back over top of the original database.

The VACUUM command may change the ROWIDs of entries in any
tables that do not have an explicit INTEGER PRIMARY KEY.


A VACUUM will fail if there is an open transaction on the database
connection that is attempting to run the VACUUM.  Unfinalized SQL
statements typically hold a read transaction open, so the VACUUM
might fail if there are unfinalized SQL statements on the same connection.
VACUUM (but not VACUUM INTO) is a write operation and so if another
database connection is holding a lock that prevents writes, then
the VACUUM will fail.

An alternative to using the VACUUM command to
reclaim space after data has been deleted is auto-vacuum mode, enabled using
the auto_vacuum pragma. When auto_vacuum is enabled for a database
free pages may be reclaimed after deleting data, causing the file to shrink,
without rebuilding the entire database using VACUUM.  However, using
auto_vacuum can lead to extra database file fragmentation.  And auto_vacuum
does not compact partially filled pages of the database as VACUUM does.


c2: CREATE TRIGGER
c5: lang_createtrigger.html
c4:
1. Syntax



 
 


 
 


 
 



 
 




 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 


 
 





 
 


 
 



 
 


 
 



 
 





 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 





2. Description
The CREATE TRIGGER statement is used to add triggers to the 
database schema. Triggers are database operations 
that are automatically performed when a specified database event
occurs.  

Each trigger must specify that it will fire for one of
the following operations: DELETE, INSERT, UPDATE.
The trigger fires once for each row that is deleted, inserted,
or updated.  If the "UPDATE OF column-name"
syntax is used, then the trigger will only fire if
column-name appears on the left-hand side of
one of the terms in the SET clause of the UPDATE statement.

Due to an historical oversight, columns named in the "UPDATE OF"
clause do not actually have to exist in the table being updated.
Unrecognized column names are silently ignored.
It would be more helpful if SQLite would fail the CREATE TRIGGER
statement if any of the names in the "UPDATE OF" clause are not
columns in the table.  However, as this problem was discovered
many years after SQLite was widely deployed, we have resisted
fixing the problem for fear of breaking legacy applications.

At this time SQLite supports only FOR EACH ROW triggers, not FOR EACH
STATEMENT triggers. Hence explicitly specifying FOR EACH ROW is optional.
FOR EACH ROW implies that the SQL statements specified in the trigger
may be executed (depending on the WHEN clause) for each database row being
inserted, updated or deleted by the statement causing the trigger to fire.

Both the WHEN clause and the trigger actions may access elements of 
the row being inserted, deleted or updated using references of the form 
"NEW.column-name" and "OLD.column-name", where
column-name is the name of a column from the table that the trigger
is associated with. OLD and NEW references may only be used in triggers on
events for which they are relevant, as follows:



INSERT
NEW references are valid


UPDATE
NEW and OLD references are valid


DELETE
OLD references are valid




If a WHEN clause is supplied, the SQL statements specified
are only executed if the WHEN clause is true.
If no WHEN clause is supplied, the SQL statements
are executed every time the trigger fires.

The BEFORE or AFTER keyword determines when the trigger actions
will be executed relative to the insertion, modification or removal of the
associated row.  BEFORE is the default when neither keyword is present.

An ON CONFLICT clause may be specified as part of an UPDATE or INSERT
action within the body of the trigger.
However if an ON CONFLICT clause is specified as part of 
the statement causing the trigger to fire, then conflict handling
policy of the outer statement is used instead.

Triggers are automatically dropped
when the table that they are 
associated with (the table-name table) is 
dropped.  However if the trigger actions reference
other tables, the trigger is not dropped or modified if those other
tables are dropped or modified.

Triggers are removed using the DROP TRIGGER statement.

2.1. Syntax Restrictions On UPDATE, DELETE, and INSERT Statements Within
    Triggers

The UPDATE, DELETE, and INSERT
statements within triggers do not support
the full syntax for UPDATE, DELETE, and INSERT statements.  The following
restrictions apply:



  The name of the table to be modified in an UPDATE, DELETE, or INSERT
  statement must be an unqualified table name.  In other words, one must
  use just "tablename" not "database.tablename"
  when specifying the table. 


 For non-TEMP triggers,
  the table to be modified or queried must exist in the
  same database as the table or view to which the trigger is attached.
  TEMP triggers are not subject to the same-database rule.  A TEMP
  trigger is allowed to query or modify any table in any ATTACH-ed database.
  


  The "INSERT INTO table DEFAULT VALUES" form of the INSERT statement
  is not supported.
  


  The INDEXED BY and NOT INDEXED clauses are not supported for UPDATE and
  DELETE statements.
  


  The ORDER BY and LIMIT clauses on UPDATE and DELETE statements are not
  supported.  ORDER BY and LIMIT are not normally supported for UPDATE or
  DELETE in any context but can be enabled for top-level statements
  using the SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option.  However,
  that compile-time option only applies to top-level UPDATE and DELETE
  statements, not UPDATE and DELETE statements within triggers.
  


   are not supported for
  statements inside of triggers.
  




3. INSTEAD OF triggers

Triggers may be created on views, as well as ordinary tables, by
specifying INSTEAD OF in the CREATE TRIGGER statement. 
If one or more ON INSERT, ON DELETE
or ON UPDATE triggers are defined on a view, then it is not an
error to execute an INSERT, DELETE or UPDATE statement on the view, 
respectively.  Instead,
executing an INSERT, DELETE or UPDATE on the view causes the associated
triggers to fire. The real tables underlying the view are not modified
(except possibly explicitly, by a trigger program).

Note that the sqlite3_changes() and sqlite3_total_changes() interfaces
do not count INSTEAD OF trigger firings, but the
count_changes pragma does count INSTEAD OF trigger firing.

4. Some Example Triggers

Assuming that customer records are stored in the "customers" table, and
that order records are stored in the "orders" table, the following
UPDATE trigger
ensures that all associated orders are redirected when a customer changes
his or her address:


CREATE TRIGGER update_customer_address UPDATE OF address ON customers 
  BEGIN
    UPDATE orders SET address = new.address WHERE customer_name = old.name;
  END;


With this trigger installed, executing the statement:


UPDATE customers SET address = '1 Main St.' WHERE name = 'Jack Jones';


causes the following to be automatically executed:


UPDATE orders SET address = '1 Main St.' WHERE customer_name = 'Jack Jones';


For an example of an INSTEAD OF trigger, consider the following schema:


CREATE TABLE customer(
  cust_id INTEGER PRIMARY KEY,
  cust_name TEXT,
  cust_addr TEXT
);
CREATE VIEW customer_address AS
   SELECT cust_id, cust_addr FROM customer;
CREATE TRIGGER cust_addr_chng
INSTEAD OF UPDATE OF cust_addr ON customer_address
BEGIN
  UPDATE customer SET cust_addr=NEW.cust_addr
   WHERE cust_id=NEW.cust_id;
END;


With the schema above, a statement of the form:


UPDATE customer_address SET cust_addr=$new_address WHERE cust_id=$cust_id;


Causes the customer.cust_addr field to be updated for a specific
customer entry that has customer.cust_id equal to the $cust_id parameter.
Note how the values assigned to the view are made available as field
in the special "NEW" table within the trigger body.



5. Cautions On The Use Of BEFORE triggers

If a BEFORE UPDATE or BEFORE DELETE trigger modifies or deletes a row
that was to have been updated or deleted, then the result of the subsequent
update or delete operation is undefined.  Furthermore, if a BEFORE trigger
modifies or deletes a row, then it is undefined whether or not AFTER triggers
that would have otherwise run on those rows will in fact run.


The value of NEW.rowid is undefined in a BEFORE INSERT trigger in which
the rowid is not explicitly set to an integer.

Because of the behaviors described above, programmers are encouraged to
prefer AFTER triggers over BEFORE triggers.



6. The RAISE() function

A special SQL function RAISE() may be used within a trigger-program,
with the following syntax 


 
 


When one of RAISE(ROLLBACK,...), RAISE(ABORT,...) or RAISE(FAIL,...)
is called during trigger-program
execution, the specified ON CONFLICT processing is performed and
the current query terminates.
An error code of SQLITE_CONSTRAINT is returned to the application,
along with the specified error message.

When RAISE(IGNORE) is called, the remainder of the current trigger program,
the statement that caused the trigger program to execute and any subsequent
trigger programs that would have been executed are abandoned. No database
changes are rolled back.  If the statement that caused the trigger program
to execute is itself part of a trigger program, then that trigger program
resumes execution at the beginning of the next step.




7. TEMP Triggers on Non-TEMP Tables

A trigger normally exists in the same database as the table named
after the "ON" keyword in the CREATE TRIGGER statement.  Except, it is
possible to create a TEMP TRIGGER on a table in another database.  
Such a trigger will only fire when changes
are made to the target table by the application that defined the trigger.
Other applications that modify the database will not be able to see the
TEMP trigger and hence cannot run the trigger.

When defining a TEMP trigger on a non-TEMP table, it is important to
specify the database holding the non-TEMP table.  For example,
in the following statement, it is important to say "main.tab1" instead
of just "tab1":


CREATE TEMP TRIGGER ex1 AFTER INSERT ON main.tab1 BEGIN ...


Failure to specify the schema name on the target table could result
in the TEMP trigger being reattached to a table with the same name in
another database whenever any schema change occurs.


c2: DROP VIEW
c5: lang_dropview.html
c4:
The DROP VIEW statement removes a view created by the CREATE VIEW 
  statement. The view definition is removed from the database schema, but 
  no actual data in the underlying base tables is modified.

The view to drop is identified by the view-name and optional 
  schema-name specified as part of the DROP VIEW statement. This 
  reference is resolved using the standard procedure for object resolution.


  If the specified view cannot be found and the IF EXISTS clause is not 
  present, it is an error. If the specified view cannot be found and an IF
  EXISTS clause is present in the DROP VIEW statement, then the statement
  is a no-op.


c2: DETACH
c5: lang_detach.html
c4:
This statement detaches an additional database connection previously 
attached using the ATTACH statement.  
When not in shared cache mode, 
it is possible to have the same database file attached multiple times using 
different names, and detaching one connection to a file will leave the 
others intact.


In shared cache mode, attempting to attach the same database file more
than once results in an error.


c2: Built-in Aggregate Functions
c5: lang_aggfunc.html
c4:
1. Syntax


 
 


 
 


 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 





 
 





The aggregate functions shown below are available by default.  Additional
aggregate functions written in C may be added using the 
sqlite3_create_function()
API.


In any aggregate function that takes a single argument, that argument
can be preceded by the keyword DISTINCT.  In such cases, duplicate
elements are filtered before being passed into the aggregate function.
For example, the function "count(distinct X)" will return the number
of distinct values of column X instead of the total number of non-null
values in column X.





If a FILTER clause is provided, then only rows for which the expr is
true are included in the aggregate.




2. List of built-in aggregate functions



avg(X)
count(*)
count(X)
group_concat(X)
group_concat(X,Y)
max(X)
min(X)
sum(X)
total(X)




3. Descriptions of built-in aggregate functions



avg(X)
  The avg() function
  returns the average value of all non-NULL X within a
  group.  String and BLOB values that do not look like numbers are
  interpreted as 0.
  The result of avg() is always a floating point value as long as
  at there is at least one non-NULL input even if all
  inputs are integers.  The result of avg() is NULL if and only if
  there are no non-NULL inputs.  


count(X)count(*)
  The count(X) function returns
  a count of the number of times
  that X is not NULL in a group.  The count(*) function
  (with no arguments) returns the total number of rows in the group.


group_concat(X)group_concat(X,Y)
  The group_concat() function returns
  a string which is the concatenation of
  all non-NULL values of X.  If parameter Y is present then
  it is used as the separator
  between instances of X.  A comma (",") is used as the separator
  if Y is omitted.  The order of the concatenated elements is
  arbitrary.


max(X)
  The max() aggregate function
  returns the maximum value of all values in the group.
  The maximum value is the value that would be returned last in an
  ORDER BY on the same column.  Aggregate max() returns NULL 
  if and only if there are no non-NULL values in the group.


min(X)
  The min() aggregate function
  returns the minimum non-NULL value of all values in the group.
  The minimum value is the first non-NULL value that would appear
  in an ORDER BY of the column.
  Aggregate min() returns NULL if and only if there are no non-NULL
  values in the group.


sum(X)total(X)
  The sum() and total() aggregate functions
  return sum of all non-NULL values in the group.
  If there are no non-NULL input rows then sum() returns
  NULL but total() returns 0.0.
  NULL is not normally a helpful result for the sum of no rows
  but the SQL standard requires it and most other
  SQL database engines implement sum() that way so SQLite does it in the
  same way in order to be compatible.   The non-standard total() function
  is provided as a convenient way to work around this design problem
  in the SQL language.

  The result of total() is always a floating point value.
  The result of sum() is an integer value if all non-NULL inputs are integers.
  If any input to sum() is neither an integer or a NULL
  then sum() returns a floating point value
  which might be an approximation to the true sum.

  Sum() will throw an "integer overflow" exception if all inputs
  are integers or NULL
  and an integer overflow occurs at any point during the computation.
  Total() never throws an integer overflow.


c2: The ON CONFLICT Clause
c5: lang_conflict.html
c4:
The ON CONFLICT clause is a
non-standard extension specific to SQLite 
that can appear in many other SQL commands.
It is given its own section in this document because it is not
part of standard SQL and therefore might not be familiar.

The ON CONFLICT clause described here has been a part of
SQLite since before version 3.0.0 (2004-06-18).  The phrase
"ON&nbsp;CONFLICT" is also part of UPSERT, which is an extension
to INSERT added in version 3.24.0 (2018-06-04).  Do not
confuse these two separate uses of the "ON&nbsp;CONFLICT" phrase.

The syntax for the ON CONFLICT clause is as shown above for
the CREATE TABLE command.  For the INSERT and
UPDATE commands, the keywords "ON CONFLICT" are replaced by "OR" so that
the syntax reads more naturally.  For example, instead of
"INSERT ON CONFLICT IGNORE" we have "INSERT OR IGNORE".
The keywords change but the meaning of the clause is the same
either way.

The ON CONFLICT clause applies to UNIQUE, NOT NULL,
CHECK, and PRIMARY KEY constraints.
The ON CONFLICT algorithm does not
apply to FOREIGN KEY constraints.
There are five conflict resolution algorithm choices:
ROLLBACK, ABORT, FAIL, IGNORE, and REPLACE.
The default conflict resolution algorithm is ABORT.  This
is what they mean:


ROLLBACK
 When an applicable constraint violation occurs, the ROLLBACK
resolution algorithm aborts the current SQL statement with
an SQLITE_CONSTRAINT error and rolls back the current transaction.
If no transaction is
active (other than the implied transaction that is created on every
command) then the ROLLBACK resolution algorithm works the same as the
ABORT algorithm.

ABORT
 When an applicable constraint violation occurs, the ABORT
resolution algorithm aborts the current SQL statement
with an SQLITE_CONSTRAINT error and backs out any changes
made by the current SQL statement; but changes caused
by prior SQL statements within the same transaction are preserved and the
transaction remains active.
This is the default behavior and the behavior specified by the SQL
standard.

FAIL
 When an applicable constraint violation occurs, the FAIL
resolution algorithm aborts the current SQL statement with an
SQLITE_CONSTRAINT error.  But the FAIL resolution does not
back out prior changes of the SQL statement that failed nor does
it end the transaction.
For example, if an UPDATE
statement encountered a constraint violation on the 100th row that
it attempts to update, then the first 99 row changes are preserved
but changes to rows 100 and beyond never occur.

The FAIL behavior only works for uniqueness, NOT NULL, and CHECK 
constraints.  A foreign key constraint violation causes an ABORT.


IGNORE
 When an applicable constraint violation occurs, 
the IGNORE resolution algorithm skips the one row that contains
the constraint violation and continues processing subsequent rows
of the SQL statement as if nothing went wrong.
Other rows before and after the row that
contained the constraint violation are inserted or updated
normally. No error is returned for uniqueness, NOT NULL, and
UNIQUE constraint errors when the IGNORE conflict resolution
algorithm is used.  However, the IGNORE conflict resolution
algorithm works like ABORT for foreign key constraint errors.



REPLACE
 When a UNIQUE or PRIMARY KEY constraint violation occurs, 
the REPLACE algorithm
deletes pre-existing rows that are causing the constraint violation
prior to inserting or updating the current row and the command continues 
executing normally.
If a NOT NULL constraint violation occurs, the REPLACE conflict
resolution replaces the NULL value with
the default value for that column, or if the column has no default
value, then the ABORT algorithm is used.
If a CHECK constraint or foreign key constraint violation occurs, 
the REPLACE conflict resolution algorithm works like ABORT.

When the REPLACE conflict resolution strategy deletes rows in order to
satisfy a constraint, delete triggers fire if and only if
recursive triggers are enabled.

The update hook is not invoked for rows that
are deleted by the REPLACE conflict resolution strategy.  Nor does
REPLACE increment the change counter.
The exceptional behaviors defined in this paragraph might change 
in a future release.


The algorithm specified in the OR clause of an INSERT or UPDATE
overrides any algorithm specified in a CREATE TABLE.
If no algorithm is specified anywhere, the ABORT algorithm is used.


c2: CREATE VIRTUAL TABLE
c5: lang_createvtab.html
c4:
A virtual table is an interface to an external storage or computation
engine that appears to be a table but does not actually store information
in the database file.

In general, you can do anything with a virtual table that can be done
with an ordinary table, except that you cannot create indices or triggers on a
virtual table.  Some virtual table implementations might impose additional
restrictions.  For example, many virtual tables are read-only.

The module-name is the name of an object that implements
the virtual table.  The module-name must be registered with
the SQLite database connection using
sqlite3_create_module() or sqlite3_create_module_v2()
prior to issuing the CREATE VIRTUAL TABLE statement.
The module takes zero or more comma-separated arguments.
The arguments can be just about any text as long as it has balanced
parentheses.  The argument syntax is sufficiently general that the
arguments can be made to appear as column definitions in a traditional
CREATE TABLE statement.  
SQLite passes the module arguments directly
to the xCreate and xConnect methods of the module implementation
without any interpretation.  It is the responsibility
of the module implementation to parse and interpret its own arguments.

A virtual table is destroyed using the ordinary
DROP TABLE statement.  There is no
DROP VIRTUAL TABLE statement.


c2: DROP TRIGGER
c5: lang_droptrigger.html
c4:
The DROP TRIGGER statement removes a trigger created by the 
CREATE TRIGGER statement. Once removed, the trigger definition is no
longer present in the sqlite_schema (or sqlite_temp_schema) table and is
not fired by any subsequent INSERT, UPDATE or DELETE statements.

Note that triggers are automatically dropped when the associated table is
dropped.


c2: C API: Memory Allocation Subsystem
c5: c3ref/free.html
c0:
sqlite3_malloc(), sqlite3_malloc64(), sqlite3_realloc(), sqlite3_realloc64(), sqlite3_free(), sqlite3_msize()

c4:
The SQLite core uses these three routines for all of its own
internal memory allocation needs. "Core" in the previous sentence
does not include operating-system specific VFS implementation.  The
Windows VFS uses native malloc() and free() for some operations.

The sqlite3_malloc() routine returns a pointer to a block
of memory at least N bytes in length, where N is the parameter.
If sqlite3_malloc() is unable to obtain sufficient free
memory, it returns a NULL pointer.  If the parameter N to
sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
a NULL pointer.

The sqlite3_malloc64(N) routine works just like
sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
of a signed 32-bit integer.

Calling sqlite3_free() with a pointer previously returned
by sqlite3_malloc() or sqlite3_realloc() releases that memory so
that it might be reused.  The sqlite3_free() routine is
a no-op if is called with a NULL pointer.  Passing a NULL pointer
to sqlite3_free() is harmless.  After being freed, memory
should neither be read nor written.  Even reading previously freed
memory might result in a segmentation fault or other severe error.
Memory corruption, a segmentation fault, or other severe error
might result if sqlite3_free() is called with a non-NULL pointer that
was not obtained from sqlite3_malloc() or sqlite3_realloc().

The sqlite3_realloc(X,N) interface attempts to resize a
prior memory allocation X to be at least N bytes.
If the X parameter to sqlite3_realloc(X,N)
is a NULL pointer then its behavior is identical to calling
sqlite3_malloc(N).
If the N parameter to sqlite3_realloc(X,N) is zero or
negative then the behavior is exactly the same as calling
sqlite3_free(X).
sqlite3_realloc(X,N) returns a pointer to a memory allocation
of at least N bytes in size or NULL if insufficient memory is available.
If M is the size of the prior allocation, then min(N,M) bytes
of the prior allocation are copied into the beginning of buffer returned
by sqlite3_realloc(X,N) and the prior allocation is freed.
If sqlite3_realloc(X,N) returns NULL and N is positive, then the
prior allocation is not freed.

The sqlite3_realloc64(X,N) interfaces works the same as
sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
of a 32-bit signed integer.

If X is a memory allocation previously obtained from sqlite3_malloc(),
sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
sqlite3_msize(X) returns the size of that memory allocation in bytes.
The value returned by sqlite3_msize(X) might be larger than the number
of bytes requested when X was allocated.  If X is a NULL pointer then
sqlite3_msize(X) returns zero.  If X points to something that is not
the beginning of memory allocation, or if it points to a formerly
valid memory allocation that has now been freed, then the behavior
of sqlite3_msize(X) is undefined and possibly harmful.

The memory returned by sqlite3_malloc(), sqlite3_realloc(),
sqlite3_malloc64(), and sqlite3_realloc64()
is always aligned to at least an 8 byte boundary, or to a
4 byte boundary if the SQLITE_4_BYTE_ALIGNED_MALLOC compile-time
option is used.

The pointer arguments to sqlite3_free() and sqlite3_realloc()
must be either NULL or else pointers obtained from a prior
invocation of sqlite3_malloc() or sqlite3_realloc() that have
not yet been released.

The application must not read or write any part of
a block of memory after it has been released using
sqlite3_free() or sqlite3_realloc().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_exec()
c2: C API: One-Step Query Execution Interface
c5: c3ref/exec.html
c4:
The sqlite3_exec() interface is a convenience wrapper around
sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize(),
that allows an application to run multiple statements of SQL
without having to use a lot of C code.

The sqlite3_exec() interface runs zero or more UTF-8 encoded,
semicolon-separate SQL statements passed into its 2nd argument,
in the context of the database connection passed in as its 1st
argument.  If the callback function of the 3rd argument to
sqlite3_exec() is not NULL, then it is invoked for each result row
coming out of the evaluated SQL statements.  The 4th argument to
sqlite3_exec() is relayed through to the 1st argument of each
callback invocation.  If the callback pointer to sqlite3_exec()
is NULL, then no callback is ever invoked and result rows are
ignored.

If an error occurs while evaluating the SQL statements passed into
sqlite3_exec(), then execution of the current statement stops and
subsequent statements are skipped.  If the 5th parameter to sqlite3_exec()
is not NULL then any error message is written into memory obtained
from sqlite3_malloc() and passed back through the 5th parameter.
To avoid memory leaks, the application should invoke sqlite3_free()
on error message strings returned through the 5th parameter of
sqlite3_exec() after the error message string is no longer needed.
If the 5th parameter to sqlite3_exec() is not NULL and no errors
occur, then sqlite3_exec() sets the pointer in its 5th parameter to
NULL before returning.

If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
routine returns SQLITE_ABORT without invoking the callback again and
without running any subsequent SQL statements.

The 2nd argument to the sqlite3_exec() callback function is the
number of columns in the result.  The 3rd argument to the sqlite3_exec()
callback is an array of pointers to strings obtained as if from
sqlite3_column_text(), one for each column.  If an element of a
result row is NULL then the corresponding string pointer for the
sqlite3_exec() callback is a NULL pointer.  The 4th argument to the
sqlite3_exec() callback is an array of pointers to strings where each
entry represents the name of corresponding result column as obtained
from sqlite3_column_name().

If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
to an empty string, or a pointer that contains only whitespace and/or
SQL comments, then no SQL statements are evaluated and the database
is not changed.

Restrictions:


 The application must ensure that the 1st parameter to sqlite3_exec()
is a valid and open database connection.
 The application must not close the database connection specified by
the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
 The application must not modify the SQL statement text passed into
the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.

See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_mprintf(), sqlite3_vmprintf(), sqlite3_snprintf(), sqlite3_vsnprintf()
c2: C API: Formatted String Printing Functions
c5: c3ref/mprintf.html
c4:
These routines are work-alikes of the "printf()" family of functions
from the standard C library.
These routines understand most of the common formatting options from
the standard library printf()
plus some additional non-standard formats (%q, %Q, %w, and %z).
See the built-in printf() documentation for details.

The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
results into memory obtained from sqlite3_malloc64().
The strings returned by these two routines should be
released by sqlite3_free().  Both routines return a
NULL pointer if sqlite3_malloc64() is unable to allocate enough
memory to hold the resulting string.

The sqlite3_snprintf() routine is similar to "snprintf()" from
the standard C library.  The result is written into the
buffer supplied as the second parameter whose size is given by
the first parameter. Note that the order of the
first two parameters is reversed from snprintf().  This is an
historical accident that cannot be fixed without breaking
backwards compatibility.  Note also that sqlite3_snprintf()
returns a pointer to its buffer instead of the number of
characters actually written into the buffer.  We admit that
the number of characters written would be a more useful return
value but we cannot change the implementation of sqlite3_snprintf()
now without breaking compatibility.

As long as the buffer size is greater than zero, sqlite3_snprintf()
guarantees that the buffer is always zero-terminated.  The first
parameter "n" is the total size of the buffer, including space for
the zero terminator.  So the longest string that can be completely
written will be n-1 characters.

The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().

See also:  built-in printf(), printf() SQL function
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_io_methods
c2: C API: OS Interface File Virtual Methods Object
c5: c3ref/io_methods.html
c4:
Every file opened by the sqlite3_vfs.xOpen method populates an
sqlite3_file object (or, more commonly, a subclass of the
sqlite3_file object) with a pointer to an instance of this object.
This object defines the methods used to perform various operations
against the open file represented by the sqlite3_file object.

If the sqlite3_vfs.xOpen method sets the sqlite3_file.pMethods element
to a non-NULL pointer, then the sqlite3_io_methods.xClose method
may be invoked even if the sqlite3_vfs.xOpen reported that it failed.  The
only way to prevent a call to xClose following a failed sqlite3_vfs.xOpen
is for the sqlite3_vfs.xOpen to set the sqlite3_file.pMethods element
to NULL.

The flags argument to xSync may be one of SQLITE_SYNC_NORMAL or
SQLITE_SYNC_FULL.  The first choice is the normal fsync().
The second choice is a Mac OS X style fullsync.  The SQLITE_SYNC_DATAONLY
flag may be ORed in to indicate that only the data of the file
and not its inode needs to be synced.

The integer values to xLock() and xUnlock() are one of

 SQLITE_LOCK_NONE,
 SQLITE_LOCK_SHARED,
 SQLITE_LOCK_RESERVED,
 SQLITE_LOCK_PENDING, or
 SQLITE_LOCK_EXCLUSIVE.

xLock() increases the lock. xUnlock() decreases the lock.
The xCheckReservedLock() method checks whether any database connection,
either in this process or in some other process, is holding a RESERVED,
PENDING, or EXCLUSIVE lock on the file.  It returns true
if such a lock exists and false otherwise.

The xFileControl() method is a generic interface that allows custom
VFS implementations to directly control an open file using the
sqlite3_file_control() interface.  The second "op" argument is an
integer opcode.  The third argument is a generic pointer intended to
point to a structure that may contain arguments or space in which to
write return values.  Potential uses for xFileControl() might be
functions to enable blocking locks with timeouts, to change the
locking strategy (for example to use dot-file locks), to inquire
about the status of a lock, or to break stale locks.  The SQLite
core reserves all opcodes less than 100 for its own use.
A list of opcodes less than 100 is available.
Applications that define a custom xFileControl method should use opcodes
greater than 100 to avoid conflicts.  VFS implementations should
return SQLITE_NOTFOUND for file control opcodes that they do not
recognize.

The xSectorSize() method returns the sector size of the
device that underlies the file.  The sector size is the
minimum write that can be performed without disturbing
other bytes in the file.  The xDeviceCharacteristics()
method returns a bit vector describing behaviors of the
underlying device:


 SQLITE_IOCAP_ATOMIC
 SQLITE_IOCAP_ATOMIC512
 SQLITE_IOCAP_ATOMIC1K
 SQLITE_IOCAP_ATOMIC2K
 SQLITE_IOCAP_ATOMIC4K
 SQLITE_IOCAP_ATOMIC8K
 SQLITE_IOCAP_ATOMIC16K
 SQLITE_IOCAP_ATOMIC32K
 SQLITE_IOCAP_ATOMIC64K
 SQLITE_IOCAP_SAFE_APPEND
 SQLITE_IOCAP_SEQUENTIAL
 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
 SQLITE_IOCAP_POWERSAFE_OVERWRITE
 SQLITE_IOCAP_IMMUTABLE
 SQLITE_IOCAP_BATCH_ATOMIC


The SQLITE_IOCAP_ATOMIC property means that all writes of
any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
mean that writes of blocks that are nnn bytes in size and
are aligned to an address which is an integer multiple of
nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
that when data is appended to a file, the data is appended
first then the size of the file is extended, never the other
way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
information is written to disk in the same order as calls
to xWrite().

If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
in the unread portions of the buffer with zeros.  A VFS that
fails to zero-fill short reads might seem to work.  However,
failure to zero-fill short reads will eventually lead to
database corruption.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_mem_methods
c2: C API: Memory Allocation Routines
c5: c3ref/mem_methods.html
c4:
An instance of this object defines the interface between SQLite
and low-level memory allocation routines.

This object is used in only one place in the SQLite interface.
A pointer to an instance of this object is the argument to
sqlite3_config() when the configuration option is
SQLITE_CONFIG_MALLOC or SQLITE_CONFIG_GETMALLOC.
By creating an instance of this object
and passing it to sqlite3_config(SQLITE_CONFIG_MALLOC)
during configuration, an application can specify an alternative
memory allocation subsystem for SQLite to use for all of its
dynamic memory needs.

Note that SQLite comes with several built-in memory allocators
that are perfectly adequate for the overwhelming majority of applications
and that this object is only useful to a tiny minority of applications
with specialized memory allocation requirements.  This object is
also used during testing of SQLite in order to specify an alternative
memory allocator that simulates memory out-of-memory conditions in
order to verify that SQLite recovers gracefully from such
conditions.

The xMalloc, xRealloc, and xFree methods must work like the
malloc(), realloc() and free() functions from the standard C library.
SQLite guarantees that the second argument to
xRealloc is always a value returned by a prior call to xRoundup.

xSize should return the allocated size of a memory allocation
previously obtained from xMalloc or xRealloc.  The allocated size
is always at least as big as the requested size but may be larger.

The xRoundup method returns what would be the allocated size of
a memory allocation given a particular requested size.  Most memory
allocators round up memory allocations at least to the next multiple
of 8.  Some allocators round up to a larger multiple or to a power of 2.
Every memory allocation request coming in through sqlite3_malloc()
or sqlite3_realloc() first calls xRoundup.  If xRoundup returns 0,
that causes the corresponding memory allocation to fail.

The xInit method initializes the memory allocator.  For example,
it might allocate any required mutexes or initialize internal data
structures.  The xShutdown method is invoked (indirectly) by
sqlite3_shutdown() and should deallocate any resources acquired
by xInit.  The pAppData pointer is used as the only parameter to
xInit and xShutdown.

SQLite holds the SQLITE_MUTEX_STATIC_MAIN mutex when it invokes
the xInit method, so the xInit method need not be threadsafe.  The
xShutdown method is only called from sqlite3_shutdown() so it does
not need to be threadsafe either.  For all other methods, SQLite
holds the SQLITE_MUTEX_STATIC_MEM mutex as long as the
SQLITE_CONFIG_MEMSTATUS configuration option is turned on (which
it is by default) and so the methods are automatically serialized.
However, if SQLITE_CONFIG_MEMSTATUS is disabled, then the other
methods must be threadsafe or else make their own arrangements for
serialization.

SQLite will never invoke xInit() more than once without an intervening
call to xShutdown().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_bind_parameter_index()
c2: C API: Index Of A Parameter With A Given Name
c5: c3ref/bind_parameter_index.html
c4:
Return the index of an SQL parameter given its name.  The
index value returned is suitable for use as the second
parameter to sqlite3_bind().  A zero
is returned if no matching parameter is found.  The parameter
name must be given in UTF-8 even if the original statement
was prepared from UTF-16 text using sqlite3_prepare16_v2() or
sqlite3_prepare16_v3().

See also: sqlite3_bind(),
sqlite3_bind_parameter_count(), and
sqlite3_bind_parameter_name().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_stmt
c2: C API: Prepared Statement Object
c5: c3ref/stmt.html
c4:
An instance of this object represents a single SQL statement that
has been compiled into binary form and is ready to be evaluated.

Think of each SQL statement as a separate computer program.  The
original SQL text is source code.  A prepared statement object
is the compiled object code.  All SQL must be converted into a
prepared statement before it can be run.

The life-cycle of a prepared statement object usually goes like this:


 Create the prepared statement object using sqlite3_prepare_v2().
 Bind values to parameters using the sqlite3_bind_*()
interfaces.
 Run the SQL by calling sqlite3_step() one or more times.
 Reset the prepared statement using sqlite3_reset() then go back
to step 2.  Do this zero or more times.
 Destroy the object using sqlite3_finalize().



sqlite3_prepare
sqlite3_prepare16
sqlite3_prepare16_v2
sqlite3_prepare16_v3
sqlite3_prepare_v2
sqlite3_prepare_v3



Destructor: sqlite3_finalize()


sqlite3_bind_blob
sqlite3_bind_blob64
sqlite3_bind_double
sqlite3_bind_int
sqlite3_bind_int64
sqlite3_bind_null
sqlite3_bind_parameter_count
sqlite3_bind_parameter_index
sqlite3_bind_parameter_name
sqlite3_bind_pointer
sqlite3_bind_text
sqlite3_bind_text16
sqlite3_bind_text64
sqlite3_bind_value
sqlite3_bind_zeroblob
sqlite3_bind_zeroblob64
sqlite3_clear_bindings
sqlite3_column_blob
sqlite3_column_bytes
sqlite3_column_bytes16
sqlite3_column_count
sqlite3_column_database_name
sqlite3_column_database_name16
sqlite3_column_decltype
sqlite3_column_decltype16
sqlite3_column_double
sqlite3_column_int
sqlite3_column_int64
sqlite3_column_name
sqlite3_column_name16
sqlite3_column_origin_name
sqlite3_column_origin_name16
sqlite3_column_table_name
sqlite3_column_table_name16
sqlite3_column_text
sqlite3_column_text16
sqlite3_column_type
sqlite3_column_value
sqlite3_data_count
sqlite3_db_handle
sqlite3_expanded_sql
sqlite3_normalized_sql
sqlite3_reset
sqlite3_sql
sqlite3_step
sqlite3_stmt_busy
sqlite3_stmt_isexplain
sqlite3_stmt_readonly
sqlite3_stmt_scanstatus
sqlite3_stmt_scanstatus_reset
sqlite3_stmt_status



See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_data_count()
c2: C API: Number of columns in a result set
c5: c3ref/data_count.html
c4:
The sqlite3_data_count(P) interface returns the number of columns in the
current row of the result set of prepared statement P.
If prepared statement P does not have results ready to return
(via calls to the sqlite3_column() family of
interfaces) then sqlite3_data_count(P) returns 0.
The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
The sqlite3_data_count(P) routine returns 0 if the previous call to
sqlite3_step(P) returned SQLITE_DONE.  The sqlite3_data_count(P)
will return non-zero if previous call to sqlite3_step(P) returned
SQLITE_ROW, except in the case of the PRAGMA incremental_vacuum
where it always returns zero since each step of that multi-step
pragma returns 0 columns of data.

See also: sqlite3_column_count()
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_serialize()
c2: C API: Serialize a database
c5: c3ref/serialize.html
c4:
The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
that is a serialization of the S database on database connection D.
If P is not a NULL pointer, then the size of the database in bytes
is written into *P.

For an ordinary on-disk database file, the serialization is just a
copy of the disk file.  For an in-memory database or a "TEMP" database,
the serialization is the same sequence of bytes which would be written
to disk if that database where backed up to disk.

The usual case is that sqlite3_serialize() copies the serialization of
the database into memory obtained from sqlite3_malloc64() and returns
a pointer to that memory.  The caller is responsible for freeing the
returned value to avoid a memory leak.  However, if the F argument
contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
are made, and the sqlite3_serialize() function will return a pointer
to the contiguous memory representation of the database that SQLite
is currently using for that database, or NULL if the no such contiguous
memory representation of the database exists.  A contiguous memory
representation of the database will usually only exist if there has
been a prior call to sqlite3_deserialize(D,S,...) with the same
values of D and S.
The size of the database is written into *P even if the
SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
of the database exists.

A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
allocation error occurs.

This interface is only available if SQLite is compiled with the
SQLITE_ENABLE_DESERIALIZE option.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Authorizer Action Codes
c5: c3ref/c_alter_table.html
c0:
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE, SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE, SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW, SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW, SQLITE_DELETE, SQLITE_DROP_INDEX, SQLITE_DROP_TABLE, SQLITE_DROP_TEMP_INDEX, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_TEMP_TRIGGER, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_TRIGGER, SQLITE_DROP_VIEW, SQLITE_INSERT, SQLITE_PRAGMA, SQLITE_READ, SQLITE_SELECT, SQLITE_TRANSACTION, SQLITE_UPDATE, SQLITE_ATTACH, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_REINDEX, SQLITE_ANALYZE, SQLITE_CREATE_VTABLE, SQLITE_DROP_VTABLE, SQLITE_FUNCTION, SQLITE_SAVEPOINT, SQLITE_COPY, SQLITE_RECURSIVE

c4:
The sqlite3_set_authorizer() interface registers a callback function
that is invoked to authorize certain SQL statement actions.  The
second parameter to the callback is an integer code that specifies
what action is being authorized.  These are the integer action codes that
the authorizer callback may be passed.

These action code values signify what kind of operation is to be
authorized.  The 3rd and 4th parameters to the authorization
callback function will be parameters or NULL depending on which of these
codes is used as the second parameter.  The 5th parameter to the
authorizer callback is the name of the database ("main", "temp",
etc.) if applicable.  The 6th parameter to the authorizer callback
is the name of the inner-most trigger or view that is responsible for
the access attempt or NULL if this access attempt is directly from
top-level SQL code.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_cancel_auto_extension()
c2: C API: Cancel Automatic Extension Loading
c5: c3ref/cancel_auto_extension.html
c4:
The sqlite3_cancel_auto_extension(X) interface unregisters the
initialization routine X that was registered using a prior call to
sqlite3_auto_extension(X).  The sqlite3_cancel_auto_extension(X)
routine returns 1 if initialization routine X was successfully
unregistered and it returns 0 if X was not on the list of initialization
routines.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_PREPARE_PERSISTENT, SQLITE_PREPARE_NORMALIZE, SQLITE_PREPARE_NO_VTAB
c2: C API: Prepare Flags
c5: c3ref/c_prepare_normalize.html
c4:
These constants define various flags that can be passed into
"prepFlags" parameter of the sqlite3_prepare_v3() and
sqlite3_prepare16_v3() interfaces.

New flags may be added in future releases of SQLite.



 SQLITE_PREPARE_PERSISTENT
The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
that the prepared statement will be retained for a long time and
probably reused many times. Without this flag, sqlite3_prepare_v3()
and sqlite3_prepare16_v3() assume that the prepared statement will
be used just once or at most a few times and then destroyed using
sqlite3_finalize() relatively soon. The current implementation acts
on this hint by avoiding the use of lookaside memory so as not to
deplete the limited store of lookaside memory. Future versions of
SQLite may act on this hint differently.


 SQLITE_PREPARE_NORMALIZE
The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
to be required for any prepared statement that wanted to use the
sqlite3_normalized_sql() interface.  However, the
sqlite3_normalized_sql() interface is now available to all
prepared statements, regardless of whether or not they use this
flag.


 SQLITE_PREPARE_NO_VTAB
The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
to return an error (error code SQLITE_ERROR) if the statement uses
any virtual tables.

See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_compileoption_used(), sqlite3_compileoption_get()
c2: C API: Run-Time Library Compilation Options Diagnostics
c5: c3ref/compileoption_get.html
c4:
The sqlite3_compileoption_used() function returns 0 or 1
indicating whether the specified option was defined at
compile time.  The SQLITE_ prefix may be omitted from the
option name passed to sqlite3_compileoption_used().

The sqlite3_compileoption_get() function allows iterating
over the list of options that were defined at compile time by
returning the N-th compile time option string.  If N is out of range,
sqlite3_compileoption_get() returns a NULL pointer.  The SQLITE_
prefix is omitted from any strings returned by
sqlite3_compileoption_get().

Support for the diagnostic functions sqlite3_compileoption_used()
and sqlite3_compileoption_get() may be omitted by specifying the
SQLITE_OMIT_COMPILEOPTION_DIAGS option at compile time.

See also: SQL functions sqlite_compileoption_used() and
sqlite_compileoption_get() and the compile_options pragma.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Experimental Interfaces
c5: c3ref/experimental.html
c4:
SQLite C Interface

Experimental And Deprecated Interfaces

SQLite interfaces can be subdivided into three categories:


Stable
Experimental
Deprecated


Stable interfaces will be maintained indefinitely in a backwards
compatible way.  An application that uses only stable interfaces
should always be able to relink against a newer version of SQLite
without any changes.

Experimental interfaces are subject to change.  
Applications that use experimental interfaces
may need to be modified when upgrading to a newer SQLite release, though
this is rare.
When new interfaces are added to SQLite, they generally begin
as experimental interfaces.  After an interface has been in use for
a while and the developers are confident that the design of the interface
is sound and worthy of long-term support, the interface is marked
as stable.

Deprecated interfaces have been superceded by better methods of
accomplishing the same thing and should be avoided in new applications.
Deprecated interfaces continue to be supported for the sake of
backwards compatibility.  At some point in the future, it is possible
that deprecated interfaces may be removed.

Key points:


Experimental interfaces are subject to change and/or removal 
at any time.

Deprecated interfaces should not be used in new code and might
be removed in some future release.


c0: SQLITE_VERSION, SQLITE_VERSION_NUMBER, SQLITE_SOURCE_ID
c2: C API: Compile-Time Library Version Numbers
c5: c3ref/c_source_id.html
c4:
The SQLITE_VERSION C preprocessor macro in the sqlite3.h header
evaluates to a string literal that is the SQLite version in the
format "X.Y.Z" where X is the major version number (always 3 for
SQLite3) and Y is the minor version number and Z is the release number.
The SQLITE_VERSION_NUMBER C preprocessor macro resolves to an integer
with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
numbers used in SQLITE_VERSION.
The SQLITE_VERSION_NUMBER for any given release of SQLite will also
be larger than the release from which it is derived.  Either Y will
be held constant and Z will be incremented or else Y will be incremented
and Z will be reset to zero.

Since version 3.6.18 (2009-09-11),
SQLite source code has been stored in the
Fossil configuration management
system.  The SQLITE_SOURCE_ID macro evaluates to
a string which identifies a particular check-in of SQLite
within its configuration management system.  The SQLITE_SOURCE_ID
string contains the date and time of the check-in (UTC) and a SHA1
or SHA3-256 hash of the entire source tree.  If the source code has
been edited in any way since it was last checked in, then the last
four hexadecimal digits of the hash may be modified.

See also: sqlite3_libversion(),
sqlite3_libversion_number(), sqlite3_sourceid(),
sqlite_version() and sqlite_source_id().
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Name Of The Folder Holding Database Files
c5: c3ref/data_directory.html
c4:
If this global variable is made to point to a string which is
the name of a folder (a.k.a. directory), then all database files
specified with a relative pathname and created or accessed by
SQLite when using a built-in windows VFS will be assumed
to be relative to that directory. If this variable is a NULL
pointer, then SQLite assumes that all database files specified
with a relative pathname are relative to the current directory
for the process.  Only the windows VFS makes use of this global
variable; it is ignored by the unix VFS.

Changing the value of this variable while a database connection is
open can result in a corrupt database.

It is not safe to read or modify this variable in more than one
thread at a time.  It is not safe to read or modify this variable
if a database connection is being used at the same time in a separate
thread.
It is intended that this variable be set once
as part of process initialization and before any SQLite interface
routines have been called and that this variable remain unchanged
thereafter.

The data_store_directory pragma may modify this variable and cause
it to point to memory obtained from sqlite3_malloc.  Furthermore,
the data_store_directory pragma always assumes that any string
that this variable points to is held in memory obtained from
sqlite3_malloc and the pragma may attempt to free that memory
using sqlite3_free.
Hence, if this variable is modified directly, either it should be
made NULL or made to point to memory obtained from sqlite3_malloc
or else the use of the data_store_directory pragma should be avoided.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_syscall_ptr(), struct sqlite3_vfs
c2: C API: OS Interface Object
c5: c3ref/vfs.html
c4:
An instance of the sqlite3_vfs object defines the interface between
the SQLite core and the underlying operating system.  The "vfs"
in the name of the object stands for "virtual file system".  See
the VFS documentation for further information.

The VFS interface is sometimes extended by adding new methods onto
the end.  Each time such an extension occurs, the iVersion field
is incremented.  The iVersion value started out as 1 in
SQLite version 3.5.0 on 2007-09-04, then increased to 2
with SQLite version 3.7.0 on 2010-07-21, and then increased
to 3 with SQLite version 3.7.6 on 2011-04-12.  Additional fields
may be appended to the sqlite3_vfs object and the iVersion value
may increase again in future versions of SQLite.
Note that due to an oversight, the structure
of the sqlite3_vfs object changed in the transition from
SQLite version 3.5.9 to version 3.6.0 on 2008-07-16
and yet the iVersion field was not increased.

The szOsFile field is the size of the subclassed sqlite3_file
structure used by this VFS.  mxPathname is the maximum length of
a pathname in this VFS.

Registered sqlite3_vfs objects are kept on a linked list formed by
the pNext pointer.  The sqlite3_vfs_register()
and sqlite3_vfs_unregister() interfaces manage this list
in a thread-safe way.  The sqlite3_vfs_find() interface
searches the list.  Neither the application code nor the VFS
implementation should use the pNext pointer.

The pNext field is the only field in the sqlite3_vfs
structure that SQLite will ever modify.  SQLite will only access
or modify this field while holding a particular static mutex.
The application should never modify anything within the sqlite3_vfs
object once the object has been registered.

The zName field holds the name of the VFS module.  The name must
be unique across all VFS modules.



SQLite guarantees that the zFilename parameter to xOpen
is either a NULL pointer or string obtained
from xFullPathname() with an optional suffix added.
If a suffix is added to the zFilename parameter, it will
consist of a single "-" character followed by no more than
11 alphanumeric and/or "-" characters.
SQLite further guarantees that
the string will be valid and unchanged until xClose() is
called. Because of the previous sentence,
the sqlite3_file can safely store a pointer to the
filename if it needs to remember the filename for some reason.
If the zFilename parameter to xOpen is a NULL pointer then xOpen
must invent its own temporary name for the file.  Whenever the
xFilename parameter is NULL it will also be the case that the
flags parameter will include SQLITE_OPEN_DELETEONCLOSE.

The flags argument to xOpen() includes all bits set in
the flags argument to sqlite3_open_v2().  Or if sqlite3_open()
or sqlite3_open16() is used, then flags includes at least
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE.
If xOpen() opens a file read-only then it sets *pOutFlags to
include SQLITE_OPEN_READONLY.  Other bits in *pOutFlags may be set.

SQLite will also add one of the following flags to the xOpen()
call, depending on the object being opened:


  SQLITE_OPEN_MAIN_DB
  SQLITE_OPEN_MAIN_JOURNAL
  SQLITE_OPEN_TEMP_DB
  SQLITE_OPEN_TEMP_JOURNAL
  SQLITE_OPEN_TRANSIENT_DB
  SQLITE_OPEN_SUBJOURNAL
  SQLITE_OPEN_SUPER_JOURNAL
  SQLITE_OPEN_WAL


The file I/O implementation can use the object type flags to
change the way it deals with files.  For example, an application
that does not care about crash recovery or rollback might make
the open of a journal file a no-op.  Writes to this journal would
also be no-ops, and any attempt to read the journal would return
SQLITE_IOERR.  Or the implementation might recognize that a database
file will be doing page-aligned sector reads and writes in a random
order and set up its I/O subsystem accordingly.

SQLite might also add one of the following flags to the xOpen method:


 SQLITE_OPEN_DELETEONCLOSE
 SQLITE_OPEN_EXCLUSIVE


The SQLITE_OPEN_DELETEONCLOSE flag means the file should be
deleted when it is closed.  The SQLITE_OPEN_DELETEONCLOSE
will be set for TEMP databases and their journals, transient
databases, and subjournals.

The SQLITE_OPEN_EXCLUSIVE flag is always used in conjunction
with the SQLITE_OPEN_CREATE flag, which are both directly
analogous to the O_EXCL and O_CREAT flags of the POSIX open()
API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
SQLITE_OPEN_CREATE, is used to indicate that file should always
be created, and that it is an error if it already exists.
It is not used to indicate the file should be opened
for exclusive access.

At least szOsFile bytes of memory are allocated by SQLite
to hold the sqlite3_file structure passed as the third
argument to xOpen.  The xOpen method does not have to
allocate the structure; it should just fill it in.  Note that
the xOpen method must set the sqlite3_file.pMethods to either
a valid sqlite3_io_methods object or to NULL.  xOpen must do
this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
element will be valid after xOpen returns regardless of the success
or failure of the xOpen call.



The flags argument to xAccess() may be SQLITE_ACCESS_EXISTS
to test for the existence of a file, or SQLITE_ACCESS_READWRITE to
test whether a file is readable and writable, or SQLITE_ACCESS_READ
to test whether a file is at least readable.  The SQLITE_ACCESS_READ
flag is never actually used and is not implemented in the built-in
VFSes of SQLite.  The file is named by the second argument and can be a
directory. The xAccess method returns SQLITE_OK on success or some
non-zero error code if there is an I/O error or if the name of
the file given in the second argument is illegal.  If SQLITE_OK
is returned, then non-zero or zero is written into *pResOut to indicate
whether or not the file is accessible.

SQLite will always allocate at least mxPathname+1 bytes for the
output buffer xFullPathname.  The exact size of the output buffer
is also passed as a parameter to both  methods. If the output buffer
is not large enough, SQLITE_CANTOPEN should be returned. Since this is
handled as a fatal error by SQLite, vfs implementations should endeavor
to prevent this by setting mxPathname to a sufficiently large value.

The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
interfaces are not strictly a part of the filesystem, but they are
included in the VFS structure for completeness.
The xRandomness() function attempts to return nBytes bytes
of good-quality randomness into zOut.  The return value is
the actual number of bytes of randomness obtained.
The xSleep() method causes the calling thread to sleep for at
least the number of microseconds given.  The xCurrentTime()
method returns a Julian Day Number for the current date and time as
a floating point value.
The xCurrentTimeInt64() method returns, as an integer, the Julian
Day Number multiplied by 86400000 (the number of milliseconds in
a 24-hour day).
SQLite will use the xCurrentTimeInt64() method to get the current
date and time if that method is available (if iVersion is 2 or
greater and the function pointer is not NULL) and will fall back
to xCurrentTime() if xCurrentTimeInt64() is unavailable.

The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
are not used by the SQLite core.  These optional interfaces are provided
by some VFSes to facilitate testing of the VFS code. By overriding
system calls with functions under its control, a test program can
simulate faults and error conditions that would otherwise be difficult
or impossible to induce.  The set of system calls that can be overridden
varies from one VFS to another, and from one version of the same VFS to the
next.  Applications that use these interfaces must be prepared for any
or all of these interfaces to be NULL or for their behavior to change
from one release to the next.  Applications must not attempt to access
any of these methods if the iVersion of the VFS is less than 3.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_create_module(), sqlite3_create_module_v2()
c2: C API: Register A Virtual Table Implementation
c5: c3ref/create_module.html
c4:
These routines are used to register a new virtual table module name.
Module names must be registered before
creating a new virtual table using the module and before using a
preexisting virtual table for the module.

The module name is registered on the database connection specified
by the first parameter.  The name of the module is given by the
second parameter.  The third parameter is a pointer to
the implementation of the virtual table module.   The fourth
parameter is an arbitrary client data pointer that is passed through
into the xCreate and xConnect methods of the virtual table module
when a new virtual table is be being created or reinitialized.

The sqlite3_create_module_v2() interface has a fifth parameter which
is a pointer to a destructor for the pClientData.  SQLite will
invoke the destructor function (if it is not NULL) when SQLite
no longer needs the pClientData pointer.  The destructor will also
be invoked if the call to sqlite3_create_module_v2() fails.
The sqlite3_create_module()
interface is equivalent to sqlite3_create_module_v2() with a NULL
destructor.

If the third parameter (the pointer to the sqlite3_module object) is
NULL then no new module is create and any existing modules with the
same name are dropped.

See also: sqlite3_drop_modules()
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_strlike()
c2: C API: String LIKE Matching
c5: c3ref/strlike.html
c4:
The sqlite3_strlike(P,X,E) interface returns zero if and only if
string X matches the LIKE pattern P with escape character E.
The definition of LIKE pattern matching used in
sqlite3_strlike(P,X,E) is the same as for the "X LIKE P ESCAPE E"
operator in the SQL dialect understood by SQLite.  For "X LIKE P" without
the ESCAPE clause, set the E parameter of sqlite3_strlike(P,X,E) to 0.
As with the LIKE operator, the sqlite3_strlike(P,X,E) function is case
insensitive - equivalent upper and lower case ASCII characters match
one another.

The sqlite3_strlike(P,X,E) function matches Unicode characters, though
only ASCII characters are case folded.

Note that this routine returns zero on a match and non-zero if the strings
do not match, the same as sqlite3_stricmp() and sqlite3_strnicmp().

See also: sqlite3_strglob().
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Status Parameters
c5: c3ref/c_status_malloc_count.html
c0:
SQLITE_STATUS_MEMORY_USED, SQLITE_STATUS_PAGECACHE_USED, SQLITE_STATUS_PAGECACHE_OVERFLOW, SQLITE_STATUS_SCRATCH_USED, SQLITE_STATUS_SCRATCH_OVERFLOW, SQLITE_STATUS_MALLOC_SIZE, SQLITE_STATUS_PARSER_STACK, SQLITE_STATUS_PAGECACHE_SIZE, SQLITE_STATUS_SCRATCH_SIZE, SQLITE_STATUS_MALLOC_COUNT

c4:
These integer constants designate various run-time status parameters
that can be returned by sqlite3_status().



 SQLITE_STATUS_MEMORY_USED
This parameter is the current amount of memory checked out
using sqlite3_malloc(), either directly or indirectly.  The
figure includes calls made to sqlite3_malloc() by the application
and internal memory usage by the SQLite library.  Auxiliary page-cache
memory controlled by SQLITE_CONFIG_PAGECACHE is not included in
this parameter.  The amount returned is the sum of the allocation
sizes as reported by the xSize method in sqlite3_mem_methods.


 SQLITE_STATUS_MALLOC_SIZE
This parameter records the largest memory allocation request
handed to sqlite3_malloc() or sqlite3_realloc() (or their
internal equivalents).  Only the value returned in the
*pHighwater parameter to sqlite3_status() is of interest.
The value written into the *pCurrent parameter is undefined.


 SQLITE_STATUS_MALLOC_COUNT
This parameter records the number of separate memory allocations
currently checked out.


 SQLITE_STATUS_PAGECACHE_USED
This parameter returns the number of pages used out of the
pagecache memory allocator that was configured using
SQLITE_CONFIG_PAGECACHE.  The
value returned is in pages, not in bytes.



SQLITE_STATUS_PAGECACHE_OVERFLOW
This parameter returns the number of bytes of page cache
allocation which could not be satisfied by the SQLITE_CONFIG_PAGECACHE
buffer and where forced to overflow to sqlite3_malloc().  The
returned value includes allocations that overflowed because they
where too large (they were larger than the "sz" parameter to
SQLITE_CONFIG_PAGECACHE) and allocations that overflowed because
no space was left in the page cache.


 SQLITE_STATUS_PAGECACHE_SIZE
This parameter records the largest memory allocation request
handed to the pagecache memory allocator.  Only the value returned in the
*pHighwater parameter to sqlite3_status() is of interest.
The value written into the *pCurrent parameter is undefined.


 SQLITE_STATUS_SCRATCH_USED
No longer used.


 SQLITE_STATUS_SCRATCH_OVERFLOW
No longer used.


 SQLITE_STATUS_SCRATCH_SIZE
No longer used.


 SQLITE_STATUS_PARSER_STACK
The *pHighwater parameter records the deepest parser stack.
The *pCurrent value is undefined.  The *pHighwater value is only
meaningful if SQLite is compiled with YYTRACKMAXSTACKDEPTH.


New status parameters may be added from time to time.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_set_last_insert_rowid()
c2: C API: Set the Last Insert Rowid value.
c5: c3ref/set_last_insert_rowid.html
c4:
The sqlite3_set_last_insert_rowid(D, R) method allows the application to
set the value returned by calling sqlite3_last_insert_rowid(D) to R
without inserting a row into the database.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_status(), sqlite3_status64()
c2: C API: SQLite Runtime Status
c5: c3ref/status.html
c4:
These interfaces are used to retrieve runtime status information
about the performance of SQLite, and optionally to reset various
highwater marks.  The first argument is an integer code for
the specific parameter to measure.  Recognized integer codes
are of the form SQLITE_STATUS_....
The current value of the parameter is returned into *pCurrent.
The highest recorded value is returned in *pHighwater.  If the
resetFlag is true, then the highest record value is reset after
*pHighwater is written.  Some parameters do not record the highest
value.  For those parameters
nothing is written into *pHighwater and the resetFlag is ignored.
Other parameters record only the highwater mark and not the current
value.  For these latter parameters nothing is written into *pCurrent.

The sqlite3_status() and sqlite3_status64() routines return
SQLITE_OK on success and a non-zero error code on failure.

If either the current value or the highwater mark is too large to
be represented by a 32-bit integer, then the values returned by
sqlite3_status() are undefined.

See also: sqlite3_db_status()
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_vtab_collation()
c2: C API: Determine The Collation For a Virtual Table Constraint
c5: c3ref/vtab_collation.html
c4:
This function may only be called from within a call to the xBestIndex
method of a virtual table.

The first argument must be the sqlite3_index_info object that is the
first parameter to the xBestIndex() method. The second argument must be
an index into the aConstraint[] array belonging to the sqlite3_index_info
structure passed to xBestIndex. This function returns a pointer to a buffer
containing the name of the collation sequence for the corresponding
constraint.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Prepared Statement Scan Status Opcodes
c5: c3ref/c_scanstat_est.html
c0:
SQLITE_SCANSTAT_NLOOP, SQLITE_SCANSTAT_NVISIT, SQLITE_SCANSTAT_EST, SQLITE_SCANSTAT_NAME, SQLITE_SCANSTAT_EXPLAIN, SQLITE_SCANSTAT_SELECTID

c4:
The following constants can be used for the T parameter to the
sqlite3_stmt_scanstatus(S,X,T,V) interface.  Each constant designates a
different metric for sqlite3_stmt_scanstatus() to return.

When the value returned to V is a string, space to hold that string is
managed by the prepared statement S and will be automatically freed when
S is finalized.



 SQLITE_SCANSTAT_NLOOP
The sqlite3_int64 variable pointed to by the V parameter will be
set to the total number of times that the X-th loop has run.


 SQLITE_SCANSTAT_NVISIT
The sqlite3_int64 variable pointed to by the V parameter will be set
to the total number of rows examined by all iterations of the X-th loop.


 SQLITE_SCANSTAT_EST
The "double" variable pointed to by the V parameter will be set to the
query planner's estimate for the average number of rows output from each
iteration of the X-th loop.  If the query planner's estimates was accurate,
then this value will approximate the quotient NVISIT/NLOOP and the
product of this value for all prior loops with the same SELECTID will
be the NLOOP value for the current loop.


 SQLITE_SCANSTAT_NAME
The "const char *" variable pointed to by the V parameter will be set
to a zero-terminated UTF-8 string containing the name of the index or table
used for the X-th loop.


 SQLITE_SCANSTAT_EXPLAIN
The "const char *" variable pointed to by the V parameter will be set
to a zero-terminated UTF-8 string containing the EXPLAIN QUERY PLAN
description for the X-th loop.


 SQLITE_SCANSTAT_SELECT
The "int" variable pointed to by the V parameter will be set to the
"select-id" for the X-th loop.  The select-id identifies which query or
subquery the loop is part of.  The main query has a select-id of zero.
The select-id is the same value as is output in the first column
of an EXPLAIN QUERY PLAN query.

See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_wal_checkpoint()
c2: C API: Checkpoint a database
c5: c3ref/wal_checkpoint.html
c4:
The sqlite3_wal_checkpoint(D,X) is equivalent to
sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0).

In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
write-ahead log for database X on database connection D to be
transferred into the database file and for the write-ahead log to
be reset.  See the checkpointing documentation for addition
information.

This interface used to be the only way to cause a checkpoint to
occur.  But then the newer and more powerful sqlite3_wal_checkpoint_v2()
interface was added.  This interface is retained for backwards
compatibility and as a convenience for applications that need to manually
start a callback but which do not need the full power (and corresponding
complication) of sqlite3_wal_checkpoint_v2().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_vfs_find(), sqlite3_vfs_register(), sqlite3_vfs_unregister()
c2: C API: Virtual File System Objects
c5: c3ref/vfs_find.html
c4:
A virtual filesystem (VFS) is an sqlite3_vfs object
that SQLite uses to interact
with the underlying operating system.  Most SQLite builds come with a
single default VFS that is appropriate for the host computer.
New VFSes can be registered and existing VFSes can be unregistered.
The following interfaces are provided.

The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
Names are case sensitive.
Names are zero-terminated UTF-8 strings.
If there is no match, a NULL pointer is returned.
If zVfsName is NULL then the default VFS is returned.

New VFSes are registered with sqlite3_vfs_register().
Each new VFS becomes the default VFS if the makeDflt flag is set.
The same VFS can be registered multiple times without injury.
To make an existing VFS into the default VFS, register it again
with the makeDflt flag set.  If two different VFSes with the
same name are registered, the behavior is undefined.  If a
VFS is registered with a name that is NULL or an empty string,
then the behavior is undefined.

Unregister a VFS with the sqlite3_vfs_unregister() interface.
If the default VFS is unregistered, another VFS is chosen as
the default.  The choice for the new VFS is arbitrary.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_STATIC, SQLITE_TRANSIENT
c2: C API: Constants Defining Special Destructor Behavior
c5: c3ref/c_static.html
c4:
These are special values for the destructor that is passed in as the
final argument to routines like sqlite3_result_blob().  If the destructor
argument is SQLITE_STATIC, it means that the content pointer is constant
and will never change.  It does not need to be destroyed.  The
SQLITE_TRANSIENT value means that the content will likely change in
the near future and that SQLite should make its own private copy of
the content before returning.

The typedef is necessary to work around problems in certain
C++ compilers.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_mutex
c2: C API: Mutex Handle
c5: c3ref/mutex.html
c4:
The mutex module within SQLite defines sqlite3_mutex to be an
abstract type for a mutex object.  The SQLite core never looks
at the internal representation of an sqlite3_mutex.  It only
deals with pointers to the sqlite3_mutex object.

Mutexes are created using sqlite3_mutex_alloc().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_step()
c2: C API: Evaluate An SQL Statement
c5: c3ref/step.html
c4:
After a prepared statement has been prepared using any of
sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
or sqlite3_prepare16_v3() or one of the legacy
interfaces sqlite3_prepare() or sqlite3_prepare16(), this function
must be called one or more times to evaluate the statement.

The details of the behavior of the sqlite3_step() interface depend
on whether the statement was prepared using the newer "vX" interfaces
sqlite3_prepare_v3(), sqlite3_prepare_v2(), sqlite3_prepare16_v3(),
sqlite3_prepare16_v2() or the older legacy
interfaces sqlite3_prepare() and sqlite3_prepare16().  The use of the
new "vX" interface is recommended for new applications but the legacy
interface will continue to be supported.

In the legacy interface, the return value will be either SQLITE_BUSY,
SQLITE_DONE, SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
With the "v2" interface, any of the other result codes or
extended result codes might be returned as well.

SQLITE_BUSY means that the database engine was unable to acquire the
database locks it needs to do its job.  If the statement is a COMMIT
or occurs outside of an explicit transaction, then you can retry the
statement.  If the statement is not a COMMIT and occurs within an
explicit transaction then you should rollback the transaction before
continuing.

SQLITE_DONE means that the statement has finished executing
successfully.  sqlite3_step() should not be called again on this virtual
machine without first calling sqlite3_reset() to reset the virtual
machine back to its initial state.

If the SQL statement being executed returns any data, then SQLITE_ROW
is returned each time a new row of data is ready for processing by the
caller. The values may be accessed using the column access functions.
sqlite3_step() is called again to retrieve the next row of data.

SQLITE_ERROR means that a run-time error (such as a constraint
violation) has occurred.  sqlite3_step() should not be called again on
the VM. More information may be found by calling sqlite3_errmsg().
With the legacy interface, a more specific error code (for example,
SQLITE_INTERRUPT, SQLITE_SCHEMA, SQLITE_CORRUPT, and so forth)
can be obtained by calling sqlite3_reset() on the
prepared statement.  In the "v2" interface,
the more specific error code is returned directly by sqlite3_step().

SQLITE_MISUSE means that the this routine was called inappropriately.
Perhaps it was called on a prepared statement that has
already been finalized or on one that had
previously returned SQLITE_ERROR or SQLITE_DONE.  Or it could
be the case that the same database connection is being used by two or
more threads at the same moment in time.

For all versions of SQLite up to and including 3.6.23.1, a call to
sqlite3_reset() was required after sqlite3_step() returned anything
other than SQLITE_ROW before any subsequent invocation of
sqlite3_step().  Failure to reset the prepared statement using
sqlite3_reset() would result in an SQLITE_MISUSE return from
sqlite3_step().  But after version 3.6.23.1 (2010-03-26,
sqlite3_step() began
calling sqlite3_reset() automatically in this circumstance rather
than returning SQLITE_MISUSE.  This is not considered a compatibility
break because any application that ever receives an SQLITE_MISUSE error
is broken by definition.  The SQLITE_OMIT_AUTORESET compile-time option
can be used to restore the legacy behavior.

Goofy Interface Alert: In the legacy interface, the sqlite3_step()
API always returns a generic error code, SQLITE_ERROR, following any
error other than SQLITE_BUSY and SQLITE_MISUSE.  You must call
sqlite3_reset() or sqlite3_finalize() in order to find one of the
specific error codes that better describes the error.
We admit that this is a goofy design.  The problem has been fixed
with the "v2" interface.  If you prepare all of your SQL statements
using sqlite3_prepare_v3() or sqlite3_prepare_v2()
or sqlite3_prepare16_v2() or sqlite3_prepare16_v3() instead
of the legacy sqlite3_prepare() and sqlite3_prepare16() interfaces,
then the more specific error codes are returned directly
by sqlite3_step().  The use of the "vX" interfaces is recommended.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_overload_function()
c2: C API: Overload A Function For A Virtual Table
c5: c3ref/overload_function.html
c4:
Virtual tables can provide alternative implementations of functions
using the xFindFunction method of the virtual table module.
But global versions of those functions
must exist in order to be overloaded.

This API makes sure a global version of a function with a particular
name and number of parameters exists.  If no such function exists
before this API is called, a new function is created.  The implementation
of the new function always causes an exception to be thrown.  So
the new function is not good for anything by itself.  Its only
purpose is to be a placeholder function that can be overloaded
by a virtual table.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Deprecated Functions
c5: c3ref/aggregate_count.html
c0:
sqlite3_aggregate_count(), sqlite3_expired(), sqlite3_transfer_bindings(), sqlite3_global_recover(), sqlite3_thread_cleanup(), sqlite3_memory_alarm()

c4:
These functions are deprecated.  In order to maintain
backwards compatibility with older code, these functions continue
to be supported.  However, new applications should avoid
the use of these functions.  To encourage programmers to avoid
these functions, we will not explain what they do.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_str_new()
c2: C API: Create A New Dynamic String Object
c5: c3ref/str_new.html
c4:
The sqlite3_str_new(D) interface allocates and initializes
a new sqlite3_str object.  To avoid memory leaks, the object returned by
sqlite3_str_new() must be freed by a subsequent call to
sqlite3_str_finish(X).

The sqlite3_str_new(D) interface always returns a pointer to a
valid sqlite3_str object, though in the event of an out-of-memory
error the returned object might be a special singleton that will
silently reject new text, always return SQLITE_NOMEM from
sqlite3_str_errcode(), always return 0 for
sqlite3_str_length(), and always return NULL from
sqlite3_str_finish(X).  It is always safe to use the value
returned by sqlite3_str_new(D) as the sqlite3_str parameter
to any of the other sqlite3_str methods.

The D parameter to sqlite3_str_new(D) may be NULL.  If the
D parameter in sqlite3_str_new(D) is not NULL, then the maximum
length of the string contained in the sqlite3_str object will be
the value set for sqlite3_limit(D,SQLITE_LIMIT_LENGTH) instead
of SQLITE_MAX_LENGTH.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_config()
c2: C API: Configuring The SQLite Library
c5: c3ref/config.html
c4:
The sqlite3_config() interface is used to make global configuration
changes to SQLite in order to tune SQLite to the specific needs of
the application.  The default configuration is recommended for most
applications and so this routine is usually not necessary.  It is
provided to support rare applications with unusual needs.

The sqlite3_config() interface is not threadsafe. The application
must ensure that no other SQLite interfaces are invoked by other
threads while sqlite3_config() is running.

The sqlite3_config() interface
may only be invoked prior to library initialization using
sqlite3_initialize() or after shutdown by sqlite3_shutdown().
If sqlite3_config() is called after sqlite3_initialize() and before
sqlite3_shutdown() then it will return SQLITE_MISUSE.
Note, however, that sqlite3_config() can be called as part of the
implementation of an application-defined sqlite3_os_init().

The first argument to sqlite3_config() is an integer
configuration option that determines
what property of SQLite is to be configured.  Subsequent arguments
vary depending on the configuration option
in the first argument.

When a configuration option is set, sqlite3_config() returns SQLITE_OK.
If the option is unknown or SQLite is unable to set the option
then this routine returns a non-zero error code.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_authorizer(), SQLITE_ROLLBACK, SQLITE_IGNORE, SQLITE_FAIL, SQLITE_ABORT, SQLITE_REPLACE
c2: C API: Conflict resolution modes
c5: c3ref/c_fail.html
c4:
These constants are returned by sqlite3_vtab_on_conflict() to
inform a virtual table implementation what the ON CONFLICT mode
is for the SQL statement being evaluated.

Note that the SQLITE_IGNORE constant is also used as a potential
return value from the sqlite3_set_authorizer() callback and that
SQLITE_ABORT is also a result code.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_mutex_methods
c2: C API: Mutex Methods Object
c5: c3ref/mutex_methods.html
c4:
An instance of this structure defines the low-level routines
used to allocate and use mutexes.

Usually, the default mutex implementations provided by SQLite are
sufficient, however the application has the option of substituting a custom
implementation for specialized deployments or systems for which SQLite
does not provide a suitable implementation. In this case, the application
creates and populates an instance of this structure to pass
to sqlite3_config() along with the SQLITE_CONFIG_MUTEX option.
Additionally, an instance of this structure can be used as an
output variable when querying the system for the current mutex
implementation, using the SQLITE_CONFIG_GETMUTEX option.

The xMutexInit method defined by this structure is invoked as
part of system initialization by the sqlite3_initialize() function.
The xMutexInit routine is called by SQLite exactly once for each
effective call to sqlite3_initialize().

The xMutexEnd method defined by this structure is invoked as
part of system shutdown by the sqlite3_shutdown() function. The
implementation of this method is expected to release all outstanding
resources obtained by the mutex methods implementation, especially
those obtained by the xMutexInit method.  The xMutexEnd()
interface is invoked exactly once for each call to sqlite3_shutdown().

The remaining seven methods defined by this structure (xMutexAlloc,
xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
xMutexNotheld) implement the following interfaces (respectively):


  sqlite3_mutex_alloc() 
  sqlite3_mutex_free() 
  sqlite3_mutex_enter() 
  sqlite3_mutex_try() 
  sqlite3_mutex_leave() 
  sqlite3_mutex_held() 
  sqlite3_mutex_notheld() 


The only difference is that the public sqlite3_XXX functions enumerated
above silently ignore any invocations that pass a NULL pointer instead
of a valid mutex handle. The implementations of the methods defined
by this structure are not required to handle this case. The results
of passing a NULL pointer instead of a valid mutex handle are undefined
(i.e. it is acceptable to provide an implementation that segfaults if
it is passed a NULL pointer).

The xMutexInit() method must be threadsafe.  It must be harmless to
invoke xMutexInit() multiple times within the same process and without
intervening calls to xMutexEnd().  Second and subsequent calls to
xMutexInit() must be no-ops.

xMutexInit() must not use SQLite memory allocation (sqlite3_malloc()
and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
allocation for a static mutex.  However xMutexAlloc() may use SQLite
memory allocation for a fast or recursive mutex.

SQLite will invoke the xMutexEnd() method when sqlite3_shutdown() is
called, but only if the prior call to xMutexInit returned SQLITE_OK.
If xMutexInit fails in any way, it is expected to clean up after itself
prior to returning.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_file
c2: C API: OS Interface Open File Handle
c5: c3ref/file.html
c4:
An sqlite3_file object represents an open file in the
OS interface layer.  Individual OS interface
implementations will
want to subclass this object by appending additional fields
for their own use.  The pMethods entry is a pointer to an
sqlite3_io_methods object that defines methods for performing
I/O operations on the open file.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_blob_close()
c2: C API: Close A BLOB Handle
c5: c3ref/blob_close.html
c4:
This function closes an open BLOB handle. The BLOB handle is closed
unconditionally.  Even if this routine returns an error code, the
handle is still closed.

If the blob handle being closed was opened for read-write access, and if
the database is in auto-commit mode and there are no other open read-write
blob handles or active write statements, the current transaction is
committed. If an error occurs while committing the transaction, an error
code is returned and the transaction rolled back.

Calling this function with an argument that is not a NULL pointer or an
open blob handle results in undefined behaviour. Calling this routine
with a null pointer (such as would be returned by a failed call to
sqlite3_blob_open()) is a harmless no-op. Otherwise, if this function
is passed a valid open blob handle, the values returned by the
sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_changes()
c2: C API: Count The Number Of Rows Modified
c5: c3ref/changes.html
c4:
This function returns the number of rows modified, inserted or
deleted by the most recently completed INSERT, UPDATE or DELETE
statement on the database connection specified by the only parameter.
Executing any other type of SQL statement does not modify the value
returned by this function.

Only changes made directly by the INSERT, UPDATE or DELETE statement are
considered - auxiliary changes caused by triggers,
foreign key actions or REPLACE constraint resolution are not counted.

Changes to a view that are intercepted by
INSTEAD OF triggers are not counted. The value
returned by sqlite3_changes() immediately after an INSERT, UPDATE or
DELETE statement run on a view is always zero. Only changes made to real
tables are counted.

Things are more complicated if the sqlite3_changes() function is
executed while a trigger program is running. This may happen if the
program uses the changes() SQL function, or if some other callback
function invokes sqlite3_changes() directly. Essentially:


 Before entering a trigger program the value returned by
sqlite3_changes() function is saved. After the trigger program
has finished, the original value is restored.

 Within a trigger program each INSERT, UPDATE and DELETE
statement sets the value returned by sqlite3_changes()
upon completion as normal. Of course, this value will not include
any changes performed by sub-triggers, as the sqlite3_changes()
value will be saved and restored after each sub-trigger has run.


This means that if the changes() SQL function (or similar) is used
by the first INSERT, UPDATE or DELETE statement within a trigger, it
returns the value as set when the calling statement began executing.
If it is used by the second or subsequent such statement within a trigger
program, the value returned reflects the number of rows modified by the
previous INSERT, UPDATE or DELETE statement within the same trigger.

If a separate thread makes changes on the same database connection
while sqlite3_changes() is running then the value returned
is unpredictable and not meaningful.

See also:

 the sqlite3_total_changes() interface
 the count_changes pragma
 the changes() SQL function
 the data_version pragma

See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_snapshot_recover()
c2: C API: Recover snapshots from a wal file
c5: c3ref/snapshot_recover.html
c4:
If a WAL file remains on disk after all database connections close
(either through the use of the SQLITE_FCNTL_PERSIST_WAL file control
or because the last process to have the database opened exited without
calling sqlite3_close()) and a new connection is subsequently opened
on that database and WAL file, the sqlite3_snapshot_open() interface
will only be able to open the last transaction added to the WAL file
even though the WAL file contains other valid transactions.

This function attempts to scan the WAL file associated with database zDb
of database handle db and make all valid snapshots available to
sqlite3_snapshot_open(). It is an error if there is already a read
transaction open on the database, or if the database is not a WAL mode
database.

SQLITE_OK is returned if successful, or an SQLite error code otherwise.

This interface is only available if SQLite is compiled with the
SQLITE_ENABLE_SNAPSHOT option.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_get_table(), sqlite3_free_table()
c2: C API: Convenience Routines For Running Queries
c5: c3ref/free_table.html
c4:
This is a legacy interface that is preserved for backwards compatibility.
Use of this interface is not recommended.

Definition: A result table is memory data structure created by the
sqlite3_get_table() interface.  A result table records the
complete query results from one or more queries.

The table conceptually has a number of rows and columns.  But
these numbers are not part of the result table itself.  These
numbers are obtained separately.  Let N be the number of rows
and M be the number of columns.

A result table is an array of pointers to zero-terminated UTF-8 strings.
There are (N+1)*M elements in the array.  The first M pointers point
to zero-terminated strings that  contain the names of the columns.
The remaining entries all point to query results.  NULL values result
in NULL pointers.  All other values are in their UTF-8 zero-terminated
string representation as returned by sqlite3_column_text().

A result table might consist of one or more memory allocations.
It is not safe to pass a result table directly to sqlite3_free().
A result table should be deallocated using sqlite3_free_table().

As an example of the result table format, suppose a query result
is as follows:



There are two columns (M==2) and three rows (N==3).  Thus the
result table has 8 entries.  Suppose the result table is stored
in an array named azResult.  Then azResult holds this content:



The sqlite3_get_table() function evaluates one or more
semicolon-separated SQL statements in the zero-terminated UTF-8
string of its 2nd parameter and returns a result table to the
pointer given in its 3rd parameter.

After the application has finished with the result from sqlite3_get_table(),
it must pass the result table pointer to sqlite3_free_table() in order to
release the memory that was malloced.  Because of the way the
sqlite3_malloc() happens within sqlite3_get_table(), the calling
function must not try to call sqlite3_free() directly.  Only
sqlite3_free_table() is able to release the memory properly and safely.

The sqlite3_get_table() interface is implemented as a wrapper around
sqlite3_exec().  The sqlite3_get_table() routine does not have access
to any internal data structures of SQLite.  It uses only the public
interface defined here.  As a consequence, errors that occur in the
wrapper layer outside of the internal sqlite3_exec() call are not
reflected in subsequent calls to sqlite3_errcode() or
sqlite3_errmsg().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_vtab_config()
c2: C API: Virtual Table Interface Configuration
c5: c3ref/vtab_config.html
c4:
This function may be called by either the xConnect or xCreate method
of a virtual table implementation to configure
various facets of the virtual table interface.

If this interface is invoked outside the context of an xConnect or
xCreate virtual table method then the behavior is undefined.

In the call sqlite3_vtab_config(D,C,...) the D parameter is the
database connection in which the virtual table is being created and
which is passed in as the first argument to the xConnect or xCreate
method that is invoking sqlite3_vtab_config().  The C parameter is one
of the virtual table configuration options.  The presence and meaning
of parameters after C depend on which virtual table configuration option
is used.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_stmt_scanstatus_reset()
c2: C API: Zero Scan-Status Counters
c5: c3ref/stmt_scanstatus_reset.html
c4:
Zero all sqlite3_stmt_scanstatus() related event counters.

This API is only available if the library is built with pre-processor
symbol SQLITE_ENABLE_STMT_SCANSTATUS defined.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_wal_checkpoint_v2()
c2: C API: Checkpoint a database
c5: c3ref/wal_checkpoint_v2.html
c4:
The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
operation on database X of database connection D in mode M.  Status
information is written back into integers pointed to by L and C.
The M parameter must be a valid checkpoint mode:


SQLITE_CHECKPOINT_PASSIVE
Checkpoint as many frames as possible without waiting for any database
readers or writers to finish, then sync the database file if all frames
in the log were checkpointed. The busy-handler callback
is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
On the other hand, passive mode might leave the checkpoint unfinished
if there are concurrent readers or writers.

SQLITE_CHECKPOINT_FULL
This mode blocks (it invokes the
busy-handler callback) until there is no
database writer and all readers are reading from the most recent database
snapshot. It then checkpoints all frames in the log file and syncs the
database file. This mode blocks new database writers while it is pending,
but new database readers are allowed to continue unimpeded.

SQLITE_CHECKPOINT_RESTART
This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
that after checkpointing the log file it blocks (calls the
busy-handler callback)
until all readers are reading from the database file only. This ensures
that the next writer will restart the log file from the beginning.
Like SQLITE_CHECKPOINT_FULL, this mode blocks new
database writer attempts while it is pending, but does not impede readers.

SQLITE_CHECKPOINT_TRUNCATE
This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
addition that it also truncates the log file to zero bytes just prior
to a successful return.


If pnLog is not NULL, then *pnLog is set to the total number of frames in
the log file or to -1 if the checkpoint could not run because
of an error or because the database is not in WAL mode. If pnCkpt is not
NULL,then *pnCkpt is set to the total number of checkpointed frames in the
log file (including any that were already checkpointed before the function
was called) or to -1 if the checkpoint could not run due to an error or
because the database is not in WAL mode. Note that upon successful
completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.

All calls obtain an exclusive "checkpoint" lock on the database file. If
any other process is running a checkpoint operation at the same time, the
lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
busy-handler configured, it will not be invoked in this case.

The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
exclusive "writer" lock on the database file. If the writer lock cannot be
obtained immediately, and a busy-handler is configured, it is invoked and
the writer lock retried until either the busy-handler returns 0 or the lock
is successfully obtained. The busy-handler is also invoked while waiting for
database readers as described above. If the busy-handler returns 0 before
the writer lock is obtained or while waiting for database readers, the
checkpoint operation proceeds from that point in the same way as
SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
without blocking any further. SQLITE_BUSY is returned in this case.

If parameter zDb is NULL or points to a zero length string, then the
specified operation is attempted on all WAL databases attached to
database connection db.  In this case the
values written to output parameters *pnLog and *pnCkpt are undefined. If
an SQLITE_BUSY error is encountered when processing one or more of the
attached WAL databases, the operation is still attempted on any remaining
attached databases and SQLITE_BUSY is returned at the end. If any other
error occurs while processing an attached database, processing is abandoned
and the error code is returned to the caller immediately. If no error
(SQLITE_BUSY or otherwise) is encountered while processing the attached
databases, SQLITE_OK is returned.

If database zDb is the name of an attached database that is not in WAL
mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
zDb is not NULL (or a zero length string) and is not the name of any
attached database, SQLITE_ERROR is returned to the caller.

Unless it returns SQLITE_MISUSE,
the sqlite3_wal_checkpoint_v2() interface
sets the error information that is queried by
sqlite3_errcode() and sqlite3_errmsg().

The PRAGMA wal_checkpoint command can be used to invoke this interface
from SQL.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_stmt_isexplain()
c2: C API: Query The EXPLAIN Setting For A Prepared Statement
c5: c3ref/stmt_isexplain.html
c4:
The sqlite3_stmt_isexplain(S) interface returns 1 if the
prepared statement S is an EXPLAIN statement, or 2 if the
statement S is an EXPLAIN QUERY PLAN.
The sqlite3_stmt_isexplain(S) interface returns 0 if S is
an ordinary statement or a NULL pointer.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Add Content To A Dynamic String
c5: c3ref/str_append.html
c0:
sqlite3_str_appendf(), sqlite3_str_vappendf(), sqlite3_str_append(), sqlite3_str_appendall(), sqlite3_str_appendchar(), sqlite3_str_reset()

c4:
These interfaces add content to an sqlite3_str object previously obtained
from sqlite3_str_new().

The sqlite3_str_appendf(X,F,...) and
sqlite3_str_vappendf(X,F,V) interfaces uses the built-in printf
functionality of SQLite to append formatted text onto the end of
sqlite3_str object X.

The sqlite3_str_append(X,S,N) method appends exactly N bytes from string S
onto the end of the sqlite3_str object X.  N must be non-negative.
S must contain at least N non-zero bytes of content.  To append a
zero-terminated string in its entirety, use the sqlite3_str_appendall()
method instead.

The sqlite3_str_appendall(X,S) method appends the complete content of
zero-terminated string S onto the end of sqlite3_str object X.

The sqlite3_str_appendchar(X,N,C) method appends N copies of the
single-byte character C onto the end of sqlite3_str object X.
This method can be used, for example, to add whitespace indentation.

The sqlite3_str_reset(X) method resets the string under construction
inside sqlite3_str object X back to zero bytes in length.

These methods do not return a result code.  If an error occurs, that fact
is recorded in the sqlite3_str object and can be recovered by a
subsequent call to sqlite3_str_errcode(X).
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Compiling An SQL Statement
c5: c3ref/prepare.html
c0:
sqlite3_prepare(), sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16(), sqlite3_prepare16_v2(), sqlite3_prepare16_v3()

c4:
To execute an SQL statement, it must first be compiled into a byte-code
program using one of these routines.  Or, in other words, these routines
are constructors for the prepared statement object.

The preferred routine to use is sqlite3_prepare_v2().  The
sqlite3_prepare() interface is legacy and should be avoided.
sqlite3_prepare_v3() has an extra "prepFlags" option that is used
for special purposes.

The use of the UTF-8 interfaces is preferred, as SQLite currently
does all parsing using UTF-8.  The UTF-16 interfaces are provided
as a convenience.  The UTF-16 interfaces work by converting the
input text into UTF-8, then invoking the corresponding UTF-8 interface.

The first argument, "db", is a database connection obtained from a
prior successful call to sqlite3_open(), sqlite3_open_v2() or
sqlite3_open16().  The database connection must not have been closed.

The second argument, "zSql", is the statement to be compiled, encoded
as either UTF-8 or UTF-16.  The sqlite3_prepare(), sqlite3_prepare_v2(),
and sqlite3_prepare_v3()
interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
and sqlite3_prepare16_v3() use UTF-16.

If the nByte argument is negative, then zSql is read up to the
first zero terminator. If nByte is positive, then it is the
number of bytes read from zSql.  If nByte is zero, then no prepared
statement is generated.
If the caller knows that the supplied string is nul-terminated, then
there is a small performance advantage to passing an nByte parameter that
is the number of bytes in the input string including
the nul-terminator.

If pzTail is not NULL then *pzTail is made to point to the first byte
past the end of the first SQL statement in zSql.  These routines only
compile the first statement in zSql, so *pzTail is left pointing to
what remains uncompiled.

*ppStmt is left pointing to a compiled prepared statement that can be
executed using sqlite3_step().  If there is an error, *ppStmt is set
to NULL.  If the input text contains no SQL (if the input is an empty
string or a comment) then *ppStmt is set to NULL.
The calling procedure is responsible for deleting the compiled
SQL statement using sqlite3_finalize() after it has finished with it.
ppStmt may not be NULL.

On success, the sqlite3_prepare() family of routines return SQLITE_OK;
otherwise an error code is returned.

The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
are retained for backwards compatibility, but their use is discouraged.
In the "vX" interfaces, the prepared statement
that is returned (the sqlite3_stmt object) contains a copy of the
original SQL text. This causes the sqlite3_step() interface to
behave differently in three ways:



If the database schema changes, instead of returning SQLITE_SCHEMA as it
always used to do, sqlite3_step() will automatically recompile the SQL
statement and try to run it again. As many as SQLITE_MAX_SCHEMA_RETRY
retries will occur before sqlite3_step() gives up and returns an error.



When an error occurs, sqlite3_step() will return one of the detailed
error codes or extended error codes.  The legacy behavior was that
sqlite3_step() would only return a generic SQLITE_ERROR result code
and the application would have to make a second call to sqlite3_reset()
in order to find the underlying cause of the problem. With the "v2" prepare
interfaces, the underlying reason for the error is returned immediately.



If the specific value bound to a host parameter in the
WHERE clause might influence the choice of query plan for a statement,
then the statement will be automatically recompiled, as if there had been
a schema change, on the first sqlite3_step() call following any change
to the bindings of that parameter.
The specific value of a WHERE-clause parameter might influence the
choice of query plan if the parameter is the left-hand side of a LIKE
or GLOB operator or if the parameter is compared to an indexed column
and the SQLITE_ENABLE_STAT4 compile-time option is enabled.



sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
the extra prepFlags parameter, which is a bit array consisting of zero or
more of the SQLITE_PREPARE_* flags.  The
sqlite3_prepare_v2() interface works exactly the same as
sqlite3_prepare_v3() with a zero prepFlags parameter.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Database Connection Configuration Options
c5: c3ref/c_dbconfig_defensive.html
c0:
SQLITE_DBCONFIG_MAINDBNAME, SQLITE_DBCONFIG_LOOKASIDE, SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_DBCONFIG_DEFENSIVE, SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_DBCONFIG_DQS_DML, SQLITE_DBCONFIG_DQS_DDL, SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_DBCONFIG_MAX

c4:
These constants are the available integer configuration options that
can be passed as the second argument to the sqlite3_db_config() interface.

New configuration options may be added in future releases of SQLite.
Existing configuration options might be discontinued.  Applications
should check the return code from sqlite3_db_config() to make sure that
the call worked.  The sqlite3_db_config() interface will return a
non-zero error code if a discontinued or unsupported configuration option
is invoked.




SQLITE_DBCONFIG_LOOKASIDE
 This option takes three additional arguments that determine the
lookaside memory allocator configuration for the database connection.
The first argument (the third parameter to sqlite3_db_config() is a
pointer to a memory buffer to use for lookaside memory.
The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
may be NULL in which case SQLite will allocate the
lookaside buffer itself using sqlite3_malloc(). The second argument is the
size of each lookaside buffer slot.  The third argument is the number of
slots.  The size of the buffer in the first argument must be greater than
or equal to the product of the second and third arguments.  The buffer
must be aligned to an 8-byte boundary.  If the second argument to
SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
rounded down to the next smaller multiple of 8.  The lookaside memory
configuration for a database connection can only be changed when that
connection is not currently using lookaside memory, or in other words
when the "current value" returned by
sqlite3_db_status(D,SQLITE_CONFIG_LOOKASIDE,...) is zero.
Any attempt to change the lookaside memory configuration when lookaside
memory is in use leaves the configuration unchanged and returns
SQLITE_BUSY.



SQLITE_DBCONFIG_ENABLE_FKEY
 This option is used to enable or disable the enforcement of
foreign key constraints.  There should be two additional arguments.
The first argument is an integer which is 0 to disable FK enforcement,
positive to enable FK enforcement or negative to leave FK enforcement
unchanged.  The second parameter is a pointer to an integer into which
is written 0 or 1 to indicate whether FK enforcement is off or on
following this call.  The second parameter may be a NULL pointer, in
which case the FK enforcement setting is not reported back. 



SQLITE_DBCONFIG_ENABLE_TRIGGER
 This option is used to enable or disable triggers.
There should be two additional arguments.
The first argument is an integer which is 0 to disable triggers,
positive to enable triggers or negative to leave the setting unchanged.
The second parameter is a pointer to an integer into which
is written 0 or 1 to indicate whether triggers are disabled or enabled
following this call.  The second parameter may be a NULL pointer, in
which case the trigger setting is not reported back. 



SQLITE_DBCONFIG_ENABLE_VIEW
 This option is used to enable or disable views.
There should be two additional arguments.
The first argument is an integer which is 0 to disable views,
positive to enable views or negative to leave the setting unchanged.
The second parameter is a pointer to an integer into which
is written 0 or 1 to indicate whether views are disabled or enabled
following this call.  The second parameter may be a NULL pointer, in
which case the view setting is not reported back. 



SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
 This option is used to enable or disable the
fts3_tokenizer() function which is part of the
FTS3 full-text search engine extension.
There should be two additional arguments.
The first argument is an integer which is 0 to disable fts3_tokenizer() or
positive to enable fts3_tokenizer() or negative to leave the setting
unchanged.
The second parameter is a pointer to an integer into which
is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
following this call.  The second parameter may be a NULL pointer, in
which case the new setting is not reported back. 



SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
 This option is used to enable or disable the sqlite3_load_extension()
interface independently of the load_extension() SQL function.
The sqlite3_enable_load_extension() API enables or disables both the
C-API sqlite3_load_extension() and the SQL function load_extension().
There should be two additional arguments.
When the first argument to this interface is 1, then only the C-API is
enabled and the SQL function remains disabled.  If the first argument to
this interface is 0, then both the C-API and the SQL function are disabled.
If the first argument is -1, then no changes are made to state of either the
C-API or the SQL function.
The second parameter is a pointer to an integer into which
is written 0 or 1 to indicate whether sqlite3_load_extension() interface
is disabled or enabled following this call.  The second parameter may
be a NULL pointer, in which case the new setting is not reported back.



 SQLITE_DBCONFIG_MAINDBNAME
 This option is used to change the name of the "main" database
schema.  The sole argument is a pointer to a constant UTF8 string
which will become the new schema name in place of "main".  SQLite
does not make a copy of the new main schema name string, so the application
must ensure that the argument passed into this DBCONFIG option is unchanged
until after the database connection closes.




SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
 Usually, when a database in wal mode is closed or detached from a
database handle, SQLite checks if this will mean that there are now no
connections at all to the database. If so, it performs a checkpoint
operation before closing the connection. This option may be used to
override this behaviour. The first parameter passed to this operation
is an integer - positive to disable checkpoints-on-close, or zero (the
default) to enable them, and negative to leave the setting unchanged.
The second parameter is a pointer to an integer
into which is written 0 or 1 to indicate whether checkpoints-on-close
have been disabled - 0 if they are not disabled, 1 if they are.



 SQLITE_DBCONFIG_ENABLE_QPSG
The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
the query planner stability guarantee (QPSG).  When the QPSG is active,
a single SQL query statement will always use the same algorithm regardless
of values of bound parameters. The QPSG disables some query optimizations
that look at the values of bound parameters, which can make some queries
slower.  But the QPSG has the advantage of more predictable behavior.  With
the QPSG active, SQLite will always use the same query plan in the field as
was used during testing in the lab.
The first argument to this setting is an integer which is 0 to disable
the QPSG, positive to enable QPSG, or negative to leave the setting
unchanged. The second parameter is a pointer to an integer into which
is written 0 or 1 to indicate whether the QPSG is disabled or enabled
following this call.



 SQLITE_DBCONFIG_TRIGGER_EQP
 By default, the output of EXPLAIN QUERY PLAN commands does not
include output for any operations performed by trigger programs. This
option is used to set or clear (the default) a flag that governs this
behavior. The first parameter passed to this operation is an integer -
positive to enable output for trigger programs, or zero to disable it,
or negative to leave the setting unchanged.
The second parameter is a pointer to an integer into which is written
0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
it is not disabled, 1 if it is.



 SQLITE_DBCONFIG_RESET_DATABASE
 Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
VACUUM in order to reset a database back to an empty database
with no schema and no content. The following process works even for
a badly corrupted database file:

 If the database connection is newly opened, make sure it has read the
database schema by preparing then discarding some query against the
database, or calling sqlite3_table_column_metadata(), ignoring any
errors.  This step is only necessary if the application desires to keep
the database in WAL mode after the reset if it was in WAL mode before
the reset.
 sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
 sqlite3_exec(db, "VACUUM", 0, 0, 0);
 sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);

Because resetting a database is destructive and irreversible, the
process requires the use of this obscure API and multiple steps to help
ensure that it does not happen by accident.


 SQLITE_DBCONFIG_DEFENSIVE
The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
"defensive" flag for a database connection.  When the defensive
flag is enabled, language features that allow ordinary SQL to
deliberately corrupt the database file are disabled.  The disabled
features include but are not limited to the following:

 The PRAGMA writable_schema=ON statement.
 The PRAGMA journal_mode=OFF statement.
 Writes to the sqlite_dbpage virtual table.
 Direct writes to shadow tables.




 SQLITE_DBCONFIG_WRITABLE_SCHEMA
The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
"writable_schema" flag. This has the same effect and is logically equivalent
to setting PRAGMA writable_schema=ON or PRAGMA writable_schema=OFF.
The first argument to this setting is an integer which is 0 to disable
the writable_schema, positive to enable writable_schema, or negative to
leave the setting unchanged. The second parameter is a pointer to an
integer into which is written 0 or 1 to indicate whether the writable_schema
is enabled or disabled following this call.




SQLITE_DBCONFIG_LEGACY_ALTER_TABLE
The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
the legacy behavior of the ALTER TABLE RENAME command such it
behaves as it did prior to version 3.24.0 (2018-06-04).  See the
"Compatibility Notice" on the ALTER TABLE RENAME documentation for
additional information. This feature can also be turned on and off
using the PRAGMA legacy_alter_table statement.




SQLITE_DBCONFIG_DQS_DML
The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
the legacy double-quoted string literal misfeature for DML statements
only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
default value of this setting is determined by the -DSQLITE_DQS
compile-time option.




SQLITE_DBCONFIG_DQS_DDL
The SQLITE_DBCONFIG_DQS option activates or deactivates
the legacy double-quoted string literal misfeature for DDL statements,
such as CREATE TABLE and CREATE INDEX. The
default value of this setting is determined by the -DSQLITE_DQS
compile-time option.




SQLITE_DBCONFIG_TRUSTED_SCHEMA
The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
assume that database schemas are untainted by malicious content.
When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
takes additional defensive steps to protect the application from harm
including:

 Prohibit the use of SQL functions inside triggers, views,
CHECK constraints, DEFAULT clauses, expression indexes,
partial indexes, or generated columns
unless those functions are tagged with SQLITE_INNOCUOUS.
 Prohibit the use of virtual tables inside of triggers or views
unless those virtual tables are tagged with SQLITE_VTAB_INNOCUOUS.

This setting defaults to "on" for legacy compatibility, however
all applications are advised to turn it off if possible. This setting
can also be controlled using the PRAGMA trusted_schema statement.




SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
the legacy file format flag.  When activated, this flag causes all newly
created database file to have a schema format version number (the 4-byte
integer found at offset 44 into the database header) of 1.  This in turn
means that the resulting database file will be readable and writable by
any SQLite version back to 3.0.0 (2004-06-18).  Without this setting,
newly created databases are generally not understandable by SQLite versions
prior to 3.3.0 (2006-01-11).  As these words are written, there
is now scarcely any need to generated database files that are compatible
all the way back to version 3.0.0, and so this setting is of little
practical use, but is provided so that SQLite can continue to claim the
ability to generate new database files that are compatible with  version
3.0.0.
Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
the VACUUM command will fail with an obscure error when attempting to
process a table with generated columns and a descending index.  This is
not considered a bug since SQLite versions 3.3.0 and earlier do not support
either generated columns or decending indexes.


See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_open(), sqlite3_open16(), sqlite3_open_v2()
c2: C API: Opening A New Database Connection
c5: c3ref/open.html
c4:
These routines open an SQLite database file as specified by the
filename argument. The filename argument is interpreted as UTF-8 for
sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
order for sqlite3_open16(). A database connection handle is usually
returned in *ppDb, even if an error occurs.  The only exception is that
if SQLite is unable to allocate memory to hold the sqlite3 object,
a NULL will be written into *ppDb instead of a pointer to the sqlite3
object. If the database is opened (and/or created) successfully, then
SQLITE_OK is returned.  Otherwise an error code is returned. The
sqlite3_errmsg() or sqlite3_errmsg16() routines can be used to obtain
an English language description of the error following a failure of any
of the sqlite3_open() routines.

The default encoding will be UTF-8 for databases created using
sqlite3_open() or sqlite3_open_v2().  The default encoding for databases
created using sqlite3_open16() will be UTF-16 in the native byte order.

Whether or not an error occurs when it is opened, resources
associated with the database connection handle should be released by
passing it to sqlite3_close() when it is no longer required.

The sqlite3_open_v2() interface works like sqlite3_open()
except that it accepts two additional parameters for additional control
over the new database connection.  The flags parameter to
sqlite3_open_v2() must include, at a minimum, one of the following
three flag combinations:


SQLITE_OPEN_READONLY
The database is opened in read-only mode.  If the database does not
already exist, an error is returned.

SQLITE_OPEN_READWRITE
The database is opened for reading and writing if possible, or reading
only if the file is write protected by the operating system.  In either
case the database must already exist, otherwise an error is returned.

SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
The database is opened for reading and writing, and is created if
it does not already exist. This is the behavior that is always used for
sqlite3_open() and sqlite3_open16().


In addition to the required flags, the following optional flags are
also supported:


SQLITE_OPEN_URI
The filename can be interpreted as a URI if this flag is set.

SQLITE_OPEN_MEMORY
The database will be opened as an in-memory database.  The database
is named by the "filename" argument for the purposes of cache-sharing,
if shared cache mode is enabled, but the "filename" is otherwise ignored.


SQLITE_OPEN_NOMUTEX
The new database connection will use the "multi-thread"
threading mode.  This means that separate threads are allowed
to use SQLite at the same time, as long as each thread is using
a different database connection.

SQLITE_OPEN_FULLMUTEX
The new database connection will use the "serialized"
threading mode.  This means the multiple threads can safely
attempt to use the same database connection at the same time.
(Mutexes will block any actual concurrency, but in this mode
there is no harm in trying.)

SQLITE_OPEN_SHAREDCACHE
The database is opened shared cache enabled, overriding
the default shared cache setting provided by
sqlite3_enable_shared_cache().

SQLITE_OPEN_PRIVATECACHE
The database is opened shared cache disabled, overriding
the default shared cache setting provided by
sqlite3_enable_shared_cache().


 SQLITE_OPEN_NOFOLLOW
The database filename is not allowed to be a symbolic link


If the 3rd parameter to sqlite3_open_v2() is not one of the
required combinations shown above optionally combined with other
SQLITE_OPEN_* bits
then the behavior is undefined.

The fourth parameter to sqlite3_open_v2() is the name of the
sqlite3_vfs object that defines the operating system interface that
the new database connection should use.  If the fourth parameter is
a NULL pointer then the default sqlite3_vfs object is used.

If the filename is ":memory:", then a private, temporary in-memory database
is created for the connection.  This in-memory database will vanish when
the database connection is closed.  Future versions of SQLite might
make use of additional special filenames that begin with the ":" character.
It is recommended that when a database filename actually does begin with
a ":" character you should prefix the filename with a pathname such as
"./" to avoid ambiguity.

If the filename is an empty string, then a private, temporary
on-disk database will be created.  This private database will be
automatically deleted as soon as the database connection is closed.


 URI Filenames

If URI filename interpretation is enabled, and the filename argument
begins with "file:", then the filename is interpreted as a URI. URI
filename interpretation is enabled if the SQLITE_OPEN_URI flag is
set in the third argument to sqlite3_open_v2(), or if it has
been enabled globally using the SQLITE_CONFIG_URI option with the
sqlite3_config() method or by the SQLITE_USE_URI compile-time option.
URI filename interpretation is turned off
by default, but future releases of SQLite might enable URI filename
interpretation by default.  See "URI filenames" for additional
information.

URI filenames are parsed according to RFC 3986. If the URI contains an
authority, then it must be either an empty string or the string
"localhost". If the authority is not an empty string or "localhost", an
error is returned to the caller. The fragment component of a URI, if
present, is ignored.

SQLite uses the path component of the URI as the name of the disk file
which contains the database. If the path begins with a '/' character,
then it is interpreted as an absolute path. If the path does not begin
with a '/' (meaning that the authority section is omitted from the URI)
then the path is interpreted as a relative path.
On windows, the first component of an absolute path
is a drive specification (e.g. "C:").



The query component of a URI may contain parameters that are interpreted
either by SQLite itself, or by a custom VFS implementation.
SQLite and its built-in VFSes interpret the
following query parameters:


 vfs: The "vfs" parameter may be used to specify the name of
a VFS object that provides the operating system interface that should
be used to access the database file on disk. If this option is set to
an empty string the default VFS object is used. Specifying an unknown
VFS is an error. If sqlite3_open_v2() is used and the vfs option is
present, then the VFS specified by the option takes precedence over
the value passed as the fourth parameter to sqlite3_open_v2().

 mode: The mode parameter may be set to either "ro", "rw",
"rwc", or "memory". Attempting to set it to any other value is
an error.
If "ro" is specified, then the database is opened for read-only
access, just as if the SQLITE_OPEN_READONLY flag had been set in the
third argument to sqlite3_open_v2(). If the mode option is set to
"rw", then the database is opened for read-write (but not create)
access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
been set. Value "rwc" is equivalent to setting both
SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  If the mode option is
set to "memory" then a pure in-memory database that never reads
or writes from disk is used. It is an error to specify a value for
the mode parameter that is less restrictive than that specified by
the flags passed in the third parameter to sqlite3_open_v2().

 cache: The cache parameter may be set to either "shared" or
"private". Setting it to "shared" is equivalent to setting the
SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
sqlite3_open_v2(). Setting the cache parameter to "private" is
equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
If sqlite3_open_v2() is used and the "cache" parameter is present in
a URI filename, its value overrides any behavior requested by setting
SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.

 psow: The psow parameter indicates whether or not the
powersafe overwrite property does or does not apply to the
storage media on which the database file resides.

 nolock: The nolock parameter is a boolean query parameter
which if set disables file locking in rollback journal modes.  This
is useful for accessing a database on a filesystem that does not
support locking.  Caution:  Database corruption might result if two
or more processes write to the same database and any one of those
processes uses nolock=1.

 immutable: The immutable parameter is a boolean query
parameter that indicates that the database file is stored on
read-only media.  When immutable is set, SQLite assumes that the
database file cannot be changed, even by a process with higher
privilege, and so the database is opened read-only and all locking
and change detection is disabled.  Caution: Setting the immutable
property on a database file that does in fact change can result
in incorrect query results and/or SQLITE_CORRUPT errors.
See also: SQLITE_IOCAP_IMMUTABLE.



Specifying an unknown parameter in the query component of a URI is not an
error.  Future versions of SQLite might understand additional query
parameters.  See "query parameters with special meaning to SQLite" for
additional information.


 URI filename examples


 URI filenames  Results
 file:data.db 
Open the file "data.db" in the current directory.
 file:/home/fred/data.db
file:///home/fred/data.db 
file://localhost/home/fred/data.db  
Open the database file "/home/fred/data.db".
 file://darkstar/home/fred/data.db 
An error. "darkstar" is not a recognized authority.

file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
 Windows only: Open the file "data.db" on fred's desktop on drive
C:. Note that the %20 escaping in this example is not strictly
necessary - space characters can be used literally
in URI filenames.
 file:data.db?mode=ro&cache=private 
Open file "data.db" in the current directory for read-only access.
Regardless of whether or not shared-cache mode is enabled by
default, use a private cache.
 file:/home/fred/data.db?vfs=unix-dotfile 
Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
that uses dot-files in place of posix advisory locking.
 file:data.db?mode=readonly 
An error. "readonly" is not a valid option for the "mode" parameter.


URI hexadecimal escape sequences (%HH) are supported within the path and
query components of a URI. A hexadecimal escape sequence consists of a
percent sign - "%" - followed by exactly two hexadecimal digits
specifying an octet value. Before the path or query components of a
URI filename are interpreted, they are encoded using UTF-8 and all
hexadecimal escape sequences replaced by a single byte containing the
corresponding octet. If this process generates an invalid UTF-8 encoding,
the results are undefined.

Note to Windows users:  The encoding used for the filename argument
of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
codepage is currently defined.  Filenames containing international
characters must be converted to UTF-8 prior to passing them into
sqlite3_open() or sqlite3_open_v2().

Note to Windows Runtime users:  The temporary directory must be set
prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
features that require the use of temporary files may fail.

See also: sqlite3_temp_directory
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_DENY
c2: C API: Authorizer Return Codes
c5: c3ref/c_deny.html
c4:
The authorizer callback function must
return either SQLITE_OK or one of these two constants in order
to signal SQLite whether or not the action is permitted.  See the
authorizer documentation for additional
information.

Note that SQLITE_IGNORE is also used as a conflict resolution mode
returned from the sqlite3_vtab_on_conflict() interface.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_libversion(), sqlite3_sourceid(), sqlite3_libversion_number()
c2: C API: Run-Time Library Version Numbers
c5: c3ref/libversion.html
c4:
These interfaces provide the same information as the SQLITE_VERSION,
SQLITE_VERSION_NUMBER, and SQLITE_SOURCE_ID C preprocessor macros
but are associated with the library instead of the header file.  Cautious
programmers might include assert() statements in their application to
verify that values returned by these interfaces match the macros in
the header, and thus ensure that the application is
compiled with matching library and header files.



The sqlite3_version[] string constant contains the text of SQLITE_VERSION
macro.  The sqlite3_libversion() function returns a pointer to the
to the sqlite3_version[] string constant.  The sqlite3_libversion()
function is provided for use in DLLs since DLL users usually do not have
direct access to string constants within the DLL.  The
sqlite3_libversion_number() function returns an integer equal to
SQLITE_VERSION_NUMBER.  The sqlite3_sourceid() function returns
a pointer to a string constant whose value is the same as the
SQLITE_SOURCE_ID C preprocessor macro.  Except if SQLite is built
using an edited copy of the amalgamation, then the last four characters
of the hash might be different from SQLITE_SOURCE_ID.

See also: sqlite_version() and sqlite_source_id().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_soft_heap_limit64(), sqlite3_hard_heap_limit64()
c2: C API: Impose A Limit On Heap Size
c5: c3ref/hard_heap_limit64.html
c4:
These interfaces impose limits on the amount of heap memory that will be
by all database connections within a single process.

The sqlite3_soft_heap_limit64() interface sets and/or queries the
soft limit on the amount of heap memory that may be allocated by SQLite.
SQLite strives to keep heap memory utilization below the soft heap
limit by reducing the number of pages held in the page cache
as heap memory usages approaches the limit.
The soft heap limit is "soft" because even though SQLite strives to stay
below the limit, it will exceed the limit rather than generate
an SQLITE_NOMEM error.  In other words, the soft heap limit
is advisory only.

The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
N bytes on the amount of memory that will be allocated.  The
sqlite3_hard_heap_limit64(N) interface is similar to
sqlite3_soft_heap_limit64(N) except that memory allocations will fail
when the hard heap limit is reached.

The return value from both sqlite3_soft_heap_limit64() and
sqlite3_hard_heap_limit64() is the size of
the heap limit prior to the call, or negative in the case of an
error.  If the argument N is negative
then no change is made to the heap limit.  Hence, the current
size of heap limits can be determined by invoking
sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).

Setting the heap limits to zero disables the heap limiter mechanism.

The soft heap limit may not be greater than the hard heap limit.
If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
is invoked with a value of N that is greater than the hard heap limit,
the the soft heap limit is set to the value of the hard heap limit.
The soft heap limit is automatically enabled whenever the hard heap
limit is enabled. When sqlite3_hard_heap_limit64(N) is invoked and
the soft heap limit is outside the range of 1..N, then the soft heap
limit is set to N.  Invoking sqlite3_soft_heap_limit64(0) when the
hard heap limit is enabled makes the soft heap limit equal to the
hard heap limit.

The memory allocation limits can also be adjusted using
PRAGMA soft_heap_limit and PRAGMA hard_heap_limit.

The heap limits are not enforced in the current implementation
if one or more of following conditions are true:


 The limit value is set to zero.
 Memory accounting is disabled using a combination of the
sqlite3_config(SQLITE_CONFIG_MEMSTATUS,...) start-time option and
the SQLITE_DEFAULT_MEMSTATUS compile-time option.
 An alternative page cache implementation is specified using
sqlite3_config(SQLITE_CONFIG_PCACHE2,...).
 The page cache allocates from its own memory pool supplied
by sqlite3_config(SQLITE_CONFIG_PAGECACHE,...) rather than
from the heap.


The circumstances under which SQLite will enforce the heap limits may
changes in future releases of SQLite.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_enable_shared_cache()
c2: C API: Enable Or Disable Shared Pager Cache
c5: c3ref/enable_shared_cache.html
c4:
This routine enables or disables the sharing of the database cache
and schema data structures between connections
to the same database. Sharing is enabled if the argument is true
and disabled if the argument is false.

Cache sharing is enabled and disabled for an entire process.
This is a change as of SQLite version 3.5.0 (2007-09-04).
In prior versions of SQLite,
sharing was enabled or disabled for each thread separately.

The cache sharing mode set by this interface effects all subsequent
calls to sqlite3_open(), sqlite3_open_v2(), and sqlite3_open16().
Existing database connections continue to use the sharing mode
that was in effect at the time they were opened.

This routine returns SQLITE_OK if shared cache was enabled or disabled
successfully.  An error code is returned otherwise.

Shared cache is disabled by default. It is recommended that it stay
that way.  In other words, do not use this routine.  This interface
continues to be provided for historical compatibility, but its use is
discouraged.  Any use of shared cache is discouraged.  If shared cache
must be used, it is recommended that shared cache only be enabled for
individual database connections using the sqlite3_open_v2() interface
with the SQLITE_OPEN_SHAREDCACHE flag.

Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
and will always return SQLITE_MISUSE. On those systems,
shared cache mode should be enabled per-database connection via
sqlite3_open_v2() with SQLITE_OPEN_SHAREDCACHE.

This interface is threadsafe on processors where writing a
32-bit integer is atomic.

See Also:  SQLite Shared-Cache Mode
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_enable_load_extension()
c2: C API: Enable Or Disable Extension Loading
c5: c3ref/enable_load_extension.html
c4:
So as not to open security holes in older applications that are
unprepared to deal with extension loading, and as a means of disabling
extension loading while evaluating user-entered SQL, the following API
is provided to turn the sqlite3_load_extension() mechanism on and off.

Extension loading is off by default.
Call the sqlite3_enable_load_extension() routine with onoff==1
to turn extension loading on and call it with onoff==0 to turn
it back off again.

This interface enables or disables both the C-API
sqlite3_load_extension() and the SQL function load_extension().
Use sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,..)
to enable or disable only the C-API.

Security warning: It is recommended that extension loading
be enabled using the SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION method
rather than this interface, so the load_extension() SQL function
remains disabled. This will prevent SQL injections from giving attackers
access to extension loading capabilities.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_initialize(), sqlite3_shutdown(), sqlite3_os_init(), sqlite3_os_end()
c2: C API: Initialize The SQLite Library
c5: c3ref/initialize.html
c4:
The sqlite3_initialize() routine initializes the
SQLite library.  The sqlite3_shutdown() routine
deallocates any resources that were allocated by sqlite3_initialize().
These routines are designed to aid in process initialization and
shutdown on embedded systems.  Workstation applications using
SQLite normally do not need to invoke either of these routines.

A call to sqlite3_initialize() is an "effective" call if it is
the first time sqlite3_initialize() is invoked during the lifetime of
the process, or if it is the first time sqlite3_initialize() is invoked
following a call to sqlite3_shutdown().  Only an effective call
of sqlite3_initialize() does any initialization.  All other calls
are harmless no-ops.

A call to sqlite3_shutdown() is an "effective" call if it is the first
call to sqlite3_shutdown() since the last sqlite3_initialize().  Only
an effective call to sqlite3_shutdown() does any deinitialization.
All other valid calls to sqlite3_shutdown() are harmless no-ops.

The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
is not.  The sqlite3_shutdown() interface must only be called from a
single thread.  All open database connections must be closed and all
other SQLite resources must be deallocated prior to invoking
sqlite3_shutdown().

Among other things, sqlite3_initialize() will invoke
sqlite3_os_init().  Similarly, sqlite3_shutdown()
will invoke sqlite3_os_end().

The sqlite3_initialize() routine returns SQLITE_OK on success.
If for some reason, sqlite3_initialize() is unable to initialize
the library (perhaps it is unable to allocate a needed resource such
as a mutex) it returns an error code other than SQLITE_OK.

The sqlite3_initialize() routine is called internally by many other
SQLite interfaces so that an application usually does not need to
invoke sqlite3_initialize() directly.  For example, sqlite3_open()
calls sqlite3_initialize() so the SQLite library will be automatically
initialized when sqlite3_open() is called if it has not be initialized
already.  However, if SQLite is compiled with the SQLITE_OMIT_AUTOINIT
compile-time option, then the automatic calls to sqlite3_initialize()
are omitted and the application must call sqlite3_initialize() directly
prior to using any other SQLite interface.  For maximum portability,
it is recommended that applications always invoke sqlite3_initialize()
directly prior to using any other SQLite interface.  Future releases
of SQLite may require this.  In other words, the behavior exhibited
when SQLite is compiled with SQLITE_OMIT_AUTOINIT might become the
default behavior in some future release of SQLite.

The sqlite3_os_init() routine does operating-system specific
initialization of the SQLite library.  The sqlite3_os_end()
routine undoes the effect of sqlite3_os_init().  Typical tasks
performed by these routines include allocation or deallocation
of static resources, initialization of global variables,
setting up a default sqlite3_vfs module, or setting up
a default configuration using sqlite3_config().

The application should never invoke either sqlite3_os_init()
or sqlite3_os_end() directly.  The application should only invoke
sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
interface is called automatically by sqlite3_initialize() and
sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
implementations for sqlite3_os_init() and sqlite3_os_end()
are built into SQLite when it is compiled for Unix, Windows, or OS/2.
When built for other platforms
(using the SQLITE_OS_OTHER=1 compile-time
option) the application must supply a suitable implementation for
sqlite3_os_init() and sqlite3_os_end().  An application-supplied
implementation of sqlite3_os_init() or sqlite3_os_end()
must return SQLITE_OK on success and some other error code upon
failure.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_wal_hook()
c2: C API: Write-Ahead Log Commit Hook
c5: c3ref/wal_hook.html
c4:
The sqlite3_wal_hook() function is used to register a callback that
is invoked each time data is committed to a database in wal mode.

The callback is invoked by SQLite after the commit has taken place and
the associated write-lock on the database released, so the implementation
may read, write or checkpoint the database as required.

The first parameter passed to the callback function when it is invoked
is a copy of the third parameter passed to sqlite3_wal_hook() when
registering the callback. The second is a copy of the database handle.
The third parameter is the name of the database that was written to -
either "main" or the name of an ATTACH-ed database. The fourth parameter
is the number of pages currently in the write-ahead log file,
including those that were just committed.

The callback function should normally return SQLITE_OK.  If an error
code is returned, that error will propagate back up through the
SQLite code base to cause the statement that provoked the callback
to report an error, though the commit will have still occurred. If the
callback returns SQLITE_ROW or SQLITE_DONE, or if it returns a value
that does not correspond to any valid SQLite error code, the results
are undefined.

A single database handle may have at most a single write-ahead log callback
registered at one time. Calling sqlite3_wal_hook() replaces any
previously registered write-ahead log callback. Note that the
sqlite3_wal_autocheckpoint() interface and the
wal_autocheckpoint pragma both invoke sqlite3_wal_hook() and will
overwrite any prior sqlite3_wal_hook() settings.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_collation_needed(), sqlite3_collation_needed16()
c2: C API: Collation Needed Callbacks
c5: c3ref/collation_needed.html
c4:
To avoid having to register all collation sequences before a database
can be used, a single callback function may be registered with the
database connection to be invoked whenever an undefined collation
sequence is required.

If the function is registered using the sqlite3_collation_needed() API,
then it is passed the names of undefined collation sequences as strings
encoded in UTF-8. If sqlite3_collation_needed16() is used,
the names are passed as UTF-16 in machine native byte order.
A call to either function replaces the existing collation-needed callback.

When the callback is invoked, the first argument passed is a copy
of the second argument to sqlite3_collation_needed() or
sqlite3_collation_needed16().  The second argument is the database
connection.  The third argument is one of SQLITE_UTF8, SQLITE_UTF16BE,
or SQLITE_UTF16LE, indicating the most desirable form of the collation
sequence function required.  The fourth parameter is the name of the
required collation sequence.

The callback function should register the desired collation using
sqlite3_create_collation(), sqlite3_create_collation16(), or
sqlite3_create_collation_v2().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_VTAB_CONSTRAINT_SUPPORT, SQLITE_VTAB_INNOCUOUS, SQLITE_VTAB_DIRECTONLY
c2: C API: Virtual Table Configuration Options
c5: c3ref/c_vtab_constraint_support.html
c4:
These macros define the various options to the
sqlite3_vtab_config() interface that virtual table implementations
can use to customize and optimize their behavior.




SQLITE_VTAB_CONSTRAINT_SUPPORT
Calls of the form
sqlite3_vtab_config(db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
where X is an integer.  If X is zero, then the virtual table whose
xCreate or xConnect method invoked sqlite3_vtab_config() does not
support constraints.  In this configuration (which is the default) if
a call to the xUpdate method returns SQLITE_CONSTRAINT, then the entire
statement is rolled back as if OR ABORT had been
specified as part of the users SQL statement, regardless of the actual
ON CONFLICT mode specified.

If X is non-zero, then the virtual table implementation guarantees
that if xUpdate returns SQLITE_CONSTRAINT, it will do so before
any modifications to internal or persistent data structures have been made.
If the ON CONFLICT mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
is able to roll back a statement or database transaction, and abandon
or continue processing the current SQL statement as appropriate.
If the ON CONFLICT mode is REPLACE and the xUpdate method returns
SQLITE_CONSTRAINT, SQLite handles this as if the ON CONFLICT mode
had been ABORT.

Virtual table implementations that are required to handle OR REPLACE
must do so within the xUpdate method. If a call to the
sqlite3_vtab_on_conflict() function indicates that the current ON
CONFLICT policy is REPLACE, the virtual table implementation should
silently replace the appropriate rows within the xUpdate callback and
return SQLITE_OK. Or, if this is not possible, it may return
SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
constraint handling.



SQLITE_VTAB_DIRECTONLY
Calls of the form
sqlite3_vtab_config(db,SQLITE_VTAB_DIRECTONLY) from within the
the xConnect or xCreate methods of a virtual table implmentation
prohibits that virtual table from being used from within triggers and
views.



SQLITE_VTAB_INNOCUOUS
Calls of the form
sqlite3_vtab_config(db,SQLITE_VTAB_INNOCUOUS) from within the
the xConnect or xCreate methods of a virtual table implmentation
identify that virtual table as being safe to use from within triggers
and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
virtual table can do no serious harm even if it is controlled by a
malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
flag unless absolutely necessary.


See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_INDEX_SCAN_UNIQUE
c2: C API: Virtual Table Scan Flags
c5: c3ref/c_index_scan_unique.html
c4:
Virtual table implementations are allowed to set the
sqlite3_index_info.idxFlags field to some combination of
these bits.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_filename_database(), sqlite3_filename_journal(), sqlite3_filename_wal()
c2: C API: Translate filenames
c5: c3ref/filename_database.html
c4:
These routines are available to custom VFS implementations for
translating filenames between the main database file, the journal file,
and the WAL file.

If F is the name of an sqlite database file, journal file, or WAL file
passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
returns the name of the corresponding database file.

If F is the name of an sqlite database file, journal file, or WAL file
passed by the SQLite core into the VFS, or if F is a database filename
obtained from sqlite3_db_filename(), then sqlite3_filename_journal(F)
returns the name of the corresponding rollback journal file.

If F is the name of an sqlite database file, journal file, or WAL file
that was passed by the SQLite core into the VFS, or if F is a database
filename obtained from sqlite3_db_filename(), then
sqlite3_filename_wal(F) returns the name of the corresponding
WAL file.

In all of the above, if F is not the name of a database, journal or WAL
filename passed into the VFS from the SQLite core and F is not the
return value from sqlite3_db_filename(), then the result is
undefined and is likely a memory access violation.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_stmt_busy()
c2: C API: Determine If A Prepared Statement Has Been Reset
c5: c3ref/stmt_busy.html
c4:
The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
prepared statement S has been stepped at least once using
sqlite3_step(S) but has neither run to completion (returned
SQLITE_DONE from sqlite3_step(S)) nor
been reset using sqlite3_reset(S).  The sqlite3_stmt_busy(S)
interface returns false if S is a NULL pointer.  If S is not a
NULL pointer and is not a pointer to a valid prepared statement
object, then the behavior is undefined and probably undesirable.

This interface can be used in combination sqlite3_next_stmt()
to locate all prepared statements associated with a database
connection that are in need of being reset.  This can be used,
for example, in diagnostic routines to search for prepared
statements that are holding a transaction open.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_trace(), sqlite3_profile()
c2: C API: Tracing And Profiling Functions
c5: c3ref/profile.html
c4:
These routines are deprecated. Use the sqlite3_trace_v2() interface
instead of the routines described here.

These routines register callback functions that can be used for
tracing and profiling the execution of SQL statements.

The callback function registered by sqlite3_trace() is invoked at
various times when an SQL statement is being run by sqlite3_step().
The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
SQL statement text as the statement first begins executing.
Additional sqlite3_trace() callbacks might occur
as each triggered subprogram is entered.  The callbacks for triggers
contain a UTF-8 SQL comment that identifies the trigger.

The SQLITE_TRACE_SIZE_LIMIT compile-time option can be used to limit
the length of bound parameter expansion in the output of sqlite3_trace().

The callback function registered by sqlite3_profile() is invoked
as each SQL statement finishes.  The profile callback contains
the original statement text and an estimate of wall-clock time
of how long that statement took to run.  The profile callback
time is in units of nanoseconds, however the current implementation
is only capable of millisecond resolution so the six least significant
digits in the time are meaningless.  Future versions of SQLite
might provide greater resolution on the profiler callback.  Invoking
either sqlite3_trace() or sqlite3_trace_v2() will cancel the
profile callback.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Status Parameters for database connections
c5: c3ref/c_dbstatus_options.html
c0:
SQLITE_DBSTATUS_LOOKASIDE_USED, SQLITE_DBSTATUS_CACHE_USED, SQLITE_DBSTATUS_SCHEMA_USED, SQLITE_DBSTATUS_STMT_USED, SQLITE_DBSTATUS_LOOKASIDE_HIT, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, SQLITE_DBSTATUS_CACHE_HIT, SQLITE_DBSTATUS_CACHE_MISS, SQLITE_DBSTATUS_CACHE_WRITE, SQLITE_DBSTATUS_DEFERRED_FKS, SQLITE_DBSTATUS_CACHE_USED_SHARED, SQLITE_DBSTATUS_CACHE_SPILL, SQLITE_DBSTATUS_MAX

c4:
These constants are the available integer "verbs" that can be passed as
the second argument to the sqlite3_db_status() interface.

New verbs may be added in future releases of SQLite. Existing verbs
might be discontinued. Applications should check the return code from
sqlite3_db_status() to make sure that the call worked.
The sqlite3_db_status() interface will return a non-zero error code
if a discontinued or unsupported verb is invoked.



 SQLITE_DBSTATUS_LOOKASIDE_USED
This parameter returns the number of lookaside memory slots currently
checked out.


 SQLITE_DBSTATUS_LOOKASIDE_HIT
This parameter returns the number of malloc attempts that were
satisfied using lookaside memory. Only the high-water value is meaningful;
the current value is always zero.



SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
This parameter returns the number malloc attempts that might have
been satisfied using lookaside memory but failed due to the amount of
memory requested being larger than the lookaside slot size.
Only the high-water value is meaningful;
the current value is always zero.



SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
This parameter returns the number malloc attempts that might have
been satisfied using lookaside memory but failed due to all lookaside
memory already being in use.
Only the high-water value is meaningful;
the current value is always zero.


 SQLITE_DBSTATUS_CACHE_USED
This parameter returns the approximate number of bytes of heap
memory used by all pager caches associated with the database connection.
The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.



SQLITE_DBSTATUS_CACHE_USED_SHARED
This parameter is similar to DBSTATUS_CACHE_USED, except that if a
pager cache is shared between two or more connections the bytes of heap
memory used by that pager cache is divided evenly between the attached
connections.  In other words, if none of the pager caches associated
with the database connection are shared, this request returns the same
value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
shared, the value returned by this call will be smaller than that returned
by DBSTATUS_CACHE_USED. The highwater mark associated with
SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.


 SQLITE_DBSTATUS_SCHEMA_USED
This parameter returns the approximate number of bytes of heap
memory used to store the schema for all databases associated
with the connection - main, temp, and any ATTACH-ed databases.
The full amount of memory used by the schemas is reported, even if the
schema memory is shared with other database connections due to
shared cache mode being enabled.
The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.


 SQLITE_DBSTATUS_STMT_USED
This parameter returns the approximate number of bytes of heap
and lookaside memory used by all prepared statements associated with
the database connection.
The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.



 SQLITE_DBSTATUS_CACHE_HIT
This parameter returns the number of pager cache hits that have
occurred. The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
is always 0.



 SQLITE_DBSTATUS_CACHE_MISS
This parameter returns the number of pager cache misses that have
occurred. The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
is always 0.



 SQLITE_DBSTATUS_CACHE_WRITE
This parameter returns the number of dirty cache entries that have
been written to disk. Specifically, the number of pages written to the
wal file in wal mode databases, or the number of pages written to the
database file in rollback mode databases. Any pages written as part of
transaction rollback or database recovery operations are not included.
If an IO or other error occurs while writing a page to disk, the effect
on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined. The
highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.



 SQLITE_DBSTATUS_CACHE_SPILL
This parameter returns the number of dirty cache entries that have
been written to disk in the middle of a transaction due to the page
cache overflowing. Transactions are more efficient if they are written
to disk all at once. When pages spill mid-transaction, that introduces
additional overhead. This parameter can be used help identify
inefficiencies that can be resolved by increasing the cache size.



 SQLITE_DBSTATUS_DEFERRED_FKS
This parameter returns zero for the current value if and only if
all foreign key constraints (deferred or immediate) have been
resolved.  The highwater mark is always 0.


See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_context_db_handle()
c2: C API: Database Connection For Functions
c5: c3ref/context_db_handle.html
c4:
The sqlite3_context_db_handle() interface returns a copy of
the pointer to the database connection (the 1st parameter)
of the sqlite3_create_function()
and sqlite3_create_function16() routines that originally
registered the application defined function.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_api_routines
c2: C API: Loadable Extension Thunk
c5: c3ref/api_routines.html
c4:
A pointer to the opaque sqlite3_api_routines structure is passed as
the third parameter to entry points of loadable extensions.  This
structure must be typedefed in order to work around compiler warnings
on some platforms.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Create Or Redefine SQL Functions
c5: c3ref/create_function.html
c0:
sqlite3_create_function(), sqlite3_create_function16(), sqlite3_create_function_v2(), sqlite3_create_window_function()

c4:
These functions (collectively known as "function creation routines")
are used to add SQL functions or aggregates or to redefine the behavior
of existing SQL functions or aggregates. The only differences between
the three "sqlite3_create_function*" routines are the text encoding
expected for the second parameter (the name of the function being
created) and the presence or absence of a destructor callback for
the application data pointer. Function sqlite3_create_window_function()
is similar, but allows the user to supply the extra callback functions
needed by aggregate window functions.

The first parameter is the database connection to which the SQL
function is to be added.  If an application uses more than one database
connection then application-defined SQL functions must be added
to each database connection separately.

The second parameter is the name of the SQL function to be created or
redefined.  The length of the name is limited to 255 bytes in a UTF-8
representation, exclusive of the zero-terminator.  Note that the name
length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
Any attempt to create a function with a longer name
will result in SQLITE_MISUSE being returned.

The third parameter (nArg)
is the number of arguments that the SQL function or
aggregate takes. If this parameter is -1, then the SQL function or
aggregate may take any number of arguments between 0 and the limit
set by sqlite3_limit(SQLITE_LIMIT_FUNCTION_ARG).  If the third
parameter is less than -1 or greater than 127 then the behavior is
undefined.

The fourth parameter, eTextRep, specifies what
text encoding this SQL function prefers for
its parameters.  The application should set this parameter to
SQLITE_UTF16LE if the function implementation invokes
sqlite3_value_text16le() on an input, or SQLITE_UTF16BE if the
implementation invokes sqlite3_value_text16be() on an input, or
SQLITE_UTF16 if sqlite3_value_text16() is used, or SQLITE_UTF8
otherwise.  The same SQL function may be registered multiple times using
different preferred text encodings, with different implementations for
each encoding.
When multiple implementations of the same function are available, SQLite
will pick the one that involves the least amount of data conversion.

The fourth parameter may optionally be ORed with SQLITE_DETERMINISTIC
to signal that the function will always return the same result given
the same inputs within a single SQL statement.  Most SQL functions are
deterministic.  The built-in random() SQL function is an example of a
function that is not deterministic.  The SQLite query planner is able to
perform additional optimizations on deterministic functions, so use
of the SQLITE_DETERMINISTIC flag is recommended where possible.

The fourth parameter may also optionally include the SQLITE_DIRECTONLY
flag, which if present prevents the function from being invoked from
within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
index expressions, or the WHERE clause of partial indexes.


For best security, the SQLITE_DIRECTONLY flag is recommended for
all application-defined SQL functions that do not need to be
used inside of triggers, view, CHECK constraints, or other elements of
the database schema.  This flags is especially recommended for SQL
functions that have side effects or reveal internal application state.
Without this flag, an attacker might be able to modify the schema of
a database file to include invocations of the function with parameters
chosen by the attacker, which the application will then execute when
the database file is opened and read.


The fifth parameter is an arbitrary pointer.  The implementation of the
function can gain access to this pointer using sqlite3_user_data().

The sixth, seventh and eighth parameters passed to the three
"sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
pointers to C-language functions that implement the SQL function or
aggregate. A scalar SQL function requires an implementation of the xFunc
callback only; NULL pointers must be passed as the xStep and xFinal
parameters. An aggregate SQL function requires an implementation of xStep
and xFinal and NULL pointer must be passed for xFunc. To delete an existing
SQL function or aggregate, pass NULL pointers for all three function
callbacks.

The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
and xInverse) passed to sqlite3_create_window_function are pointers to
C-language callbacks that implement the new function. xStep and xFinal
must both be non-NULL. xValue and xInverse may either both be NULL, in
which case a regular aggregate function is created, or must both be
non-NULL, in which case the new function may be used as either an aggregate
or aggregate window function. More details regarding the implementation
of aggregate window functions are
available here.

If the final parameter to sqlite3_create_function_v2() or
sqlite3_create_window_function() is not NULL, then it is destructor for
the application data pointer. The destructor is invoked when the function
is deleted, either by being overloaded or when the database connection
closes. The destructor is also invoked if the call to
sqlite3_create_function_v2() fails.  When the destructor callback is
invoked, it is passed a single argument which is a copy of the application
data pointer which was the fifth parameter to sqlite3_create_function_v2().

It is permitted to register multiple implementations of the same
functions with the same name but with either differing numbers of
arguments or differing preferred text encodings.  SQLite will use
the implementation that most closely matches the way in which the
SQL function is used.  A function implementation with a non-negative
nArg parameter is a better match than a function implementation with
a negative nArg.  A function where the preferred text encoding
matches the database encoding is a better
match than a function where the encoding is different.
A function where the encoding difference is between UTF16le and UTF16be
is a closer match than a function where the encoding difference is
between UTF8 and UTF16.

Built-in functions may be overloaded by new application-defined functions.

An application-defined function is permitted to call other
SQLite interfaces.  However, such calls must not
close the database connection nor finalize or reset the prepared
statement in which the function is running.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_create_collation(), sqlite3_create_collation_v2(), sqlite3_create_collation16()
c2: C API: Define New Collating Sequences
c5: c3ref/create_collation.html
c4:
These functions add, remove, or modify a collation associated
with the database connection specified as the first argument.

The name of the collation is a UTF-8 string
for sqlite3_create_collation() and sqlite3_create_collation_v2()
and a UTF-16 string in native byte order for sqlite3_create_collation16().
Collation names that compare equal according to sqlite3_strnicmp() are
considered to be the same name.

The third argument (eTextRep) must be one of the constants:

 SQLITE_UTF8,
 SQLITE_UTF16LE,
 SQLITE_UTF16BE,
 SQLITE_UTF16, or
 SQLITE_UTF16_ALIGNED.

The eTextRep argument determines the encoding of strings passed
to the collating function callback, xCompare.
The SQLITE_UTF16 and SQLITE_UTF16_ALIGNED values for eTextRep
force strings to be UTF16 with native byte order.
The SQLITE_UTF16_ALIGNED value for eTextRep forces strings to begin
on an even byte address.

The fourth argument, pArg, is an application data pointer that is passed
through as the first argument to the collating function callback.

The fifth argument, xCompare, is a pointer to the collating function.
Multiple collating functions can be registered using the same name but
with different eTextRep parameters and SQLite will use whichever
function requires the least amount of data transformation.
If the xCompare argument is NULL then the collating function is
deleted.  When all collating functions having the same name are deleted,
that collation is no longer usable.

The collating function callback is invoked with a copy of the pArg
application data pointer and with two strings in the encoding specified
by the eTextRep argument.  The two integer parameters to the collating
function callback are the length of the two strings, in bytes. The collating
function must return an integer that is negative, zero, or positive
if the first string is less than, equal to, or greater than the second,
respectively.  A collating function must always return the same answer
given the same inputs.  If two or more collating functions are registered
to the same collation name (using different eTextRep values) then all
must give an equivalent answer when invoked with equivalent strings.
The collating function must obey the following properties for all
strings A, B, and C:


 If A==B then B==A.
 If A==B and B==C then A==C.
 If A&lt;B THEN B&gt;A.
 If A&lt;B and B&lt;C then A&lt;C.


If a collating function fails any of the above constraints and that
collating function is registered and used, then the behavior of SQLite
is undefined.

The sqlite3_create_collation_v2() works like sqlite3_create_collation()
with the addition that the xDestroy callback is invoked on pArg when
the collating function is deleted.
Collating functions are deleted when they are overridden by later
calls to the collation creation functions or when the
database connection is closed using sqlite3_close().

The xDestroy callback is not called if the
sqlite3_create_collation_v2() function fails.  Applications that invoke
sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
check the return code and dispose of the application data pointer
themselves rather than expecting SQLite to deal with it for them.
This is different from every other SQLite interface.  The inconsistency
is unfortunate but cannot be changed without breaking backwards
compatibility.

See also:  sqlite3_collation_needed() and sqlite3_collation_needed16().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_create_filename(), sqlite3_free_filename()
c2: C API: Create and Destroy VFS Filenames
c5: c3ref/create_filename.html
c4:
These interfces are provided for use by VFS shim implementations and
are not useful outside of that context.

The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
database filename D with corresponding journal file J and WAL file W and
with N URI parameters key/values pairs in the array P.  The result from
sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
is safe to pass to routines like:

 sqlite3_uri_parameter(),
 sqlite3_uri_boolean(),
 sqlite3_uri_int64(),
 sqlite3_uri_key(),
 sqlite3_filename_database(),
 sqlite3_filename_journal(), or
 sqlite3_filename_wal().

If a memory allocation error occurs, sqlite3_create_filename() might
return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)
must be released by a corresponding call to sqlite3_free_filename(Y).

The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
of 2*N pointers to strings.  Each pair of pointers in this array corresponds
to a key and value for a query parameter.  The P parameter may be a NULL
pointer if N is zero.  None of the 2*N pointers in the P array may be
NULL pointers and key pointers should not be empty strings.
None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
be NULL pointers, though they can be empty strings.

The sqlite3_free_filename(Y) routine releases a memory allocation
previously obtained from sqlite3_create_filename().  Invoking
sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.

If the Y parameter to sqlite3_free_filename(Y) is anything other
than a NULL pointer or a pointer previously acquired from
sqlite3_create_filename(), then bad things such as heap
corruption or segfaults may occur. The value Y should be
used again after sqlite3_free_filename(Y) has been called.  This means
that if the sqlite3_vfs.xOpen() method of a VFS has been called using Y,
then the corresponding [sqlite3_module.xClose() method should also be
invoked prior to calling sqlite3_free_filename(Y).
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_blob_read()
c2: C API: Read Data From A BLOB Incrementally
c5: c3ref/blob_read.html
c4:
This function is used to read data from an open BLOB handle into a
caller-supplied buffer. N bytes of data are copied into buffer Z
from the open BLOB, starting at offset iOffset.

If offset iOffset is less than N bytes from the end of the BLOB,
SQLITE_ERROR is returned and no data is read.  If N or iOffset is
less than zero, SQLITE_ERROR is returned and no data is read.
The size of the blob (and hence the maximum value of N+iOffset)
can be determined using the sqlite3_blob_bytes() interface.

An attempt to read from an expired BLOB handle fails with an
error code of SQLITE_ABORT.

On success, sqlite3_blob_read() returns SQLITE_OK.
Otherwise, an error code or an extended error code is returned.

This routine only works on a BLOB handle which has been created
by a prior successful call to sqlite3_blob_open() and which has not
been closed by sqlite3_blob_close().  Passing any other pointer in
to this routine results in undefined and probably undesirable behavior.

See also: sqlite3_blob_write().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_update_hook()
c2: C API: Data Change Notification Callbacks
c5: c3ref/update_hook.html
c4:
The sqlite3_update_hook() interface registers a callback function
with the database connection identified by the first argument
to be invoked whenever a row is updated, inserted or deleted in
a rowid table.
Any callback set by a previous call to this function
for the same database connection is overridden.

The second argument is a pointer to the function to invoke when a
row is updated, inserted or deleted in a rowid table.
The first argument to the callback is a copy of the third argument
to sqlite3_update_hook().
The second callback argument is one of SQLITE_INSERT, SQLITE_DELETE,
or SQLITE_UPDATE, depending on the operation that caused the callback
to be invoked.
The third and fourth arguments to the callback contain pointers to the
database and table name containing the affected row.
The final callback parameter is the rowid of the row.
In the case of an update, this is the rowid after the update takes place.

The update hook is not invoked when internal system tables are
modified (i.e. sqlite_sequence).
The update hook is not invoked when WITHOUT ROWID tables are modified.

In the current implementation, the update hook
is not invoked when conflicting rows are deleted because of an
ON CONFLICT REPLACE clause.  Nor is the update hook
invoked when rows are deleted using the truncate optimization.
The exceptions defined in this paragraph might change in a future
release of SQLite.

The update hook implementation must not do anything that will modify
the database connection that invoked the update hook.  Any actions
to modify the database connection must be deferred until after the
completion of the sqlite3_step() call that triggered the update hook.
Note that sqlite3_prepare_v2() and sqlite3_step() both modify their
database connections for the meaning of "modify" in this paragraph.

The sqlite3_update_hook(D,C,P) function
returns the P argument from the previous call
on the same database connection D, or NULL for
the first call on D.

See also the sqlite3_commit_hook(), sqlite3_rollback_hook(),
and sqlite3_preupdate_hook() interfaces.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_value_dup(), sqlite3_value_free()
c2: C API: Copy And Free SQL Values
c5: c3ref/value_dup.html
c4:
The sqlite3_value_dup(V) interface makes a copy of the sqlite3_value
object D and returns a pointer to that copy.  The sqlite3_value returned
is a protected sqlite3_value object even if the input is not.
The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
memory allocation fails.

The sqlite3_value_free(V) interface frees an sqlite3_value object
previously obtained from sqlite3_value_dup().  If V is a NULL pointer
then sqlite3_value_free(V) is a harmless no-op.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_aggregate_context()
c2: C API: Obtain Aggregate Function Context
c5: c3ref/aggregate_context.html
c4:
Implementations of aggregate SQL functions use this
routine to allocate memory for storing their state.

The first time the sqlite3_aggregate_context(C,N) routine is called
for a particular aggregate function, SQLite allocates
N bytes of memory, zeroes out that memory, and returns a pointer
to the new memory. On second and subsequent calls to
sqlite3_aggregate_context() for the same aggregate function instance,
the same buffer is returned.  Sqlite3_aggregate_context() is normally
called once for each invocation of the xStep callback and then one
last time when the xFinal callback is invoked.  When no rows match
an aggregate query, the xStep() callback of the aggregate function
implementation is never called and xFinal() is called exactly once.
In those cases, sqlite3_aggregate_context() might be called for the
first time from within xFinal().

The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
when first called if N is less than or equal to zero or if a memory
allocate error occurs.

The amount of space allocated by sqlite3_aggregate_context(C,N) is
determined by the N parameter on first successful call.  Changing the
value of N in any subsequent call to sqlite3_aggregate_context() within
the same aggregate function instance will not resize the memory
allocation.  Within the xFinal callback, it is customary to set
N=0 in calls to sqlite3_aggregate_context(C,N) so that no
pointless memory allocations occur.

SQLite automatically frees the memory allocated by
sqlite3_aggregate_context() when the aggregate query concludes.

The first parameter must be a copy of the
SQL function context that is the first parameter
to the xStep or xFinal callback routine that implements the aggregate
function.

This routine must be called from the same thread in which
the aggregate SQL function is running.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_bind_parameter_count()
c2: C API: Number Of SQL Parameters
c5: c3ref/bind_parameter_count.html
c4:
This routine can be used to find the number of SQL parameters
in a prepared statement.  SQL parameters are tokens of the
form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
placeholders for values that are bound
to the parameters at a later time.

This routine actually returns the index of the largest (rightmost)
parameter. For all forms except ?NNN, this will correspond to the
number of unique parameters.  If parameters of the ?NNN form are used,
there may be gaps in the list.

See also: sqlite3_bind(),
sqlite3_bind_parameter_name(), and
sqlite3_bind_parameter_index().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_blob_reopen()
c2: C API: Move a BLOB Handle to a New Row
c5: c3ref/blob_reopen.html
c4:
This function is used to move an existing BLOB handle so that it points
to a different row of the same database table. The new row is identified
by the rowid value passed as the second argument. Only the row can be
changed. The database, table and column on which the blob handle is open
remain the same. Moving an existing BLOB handle to a new row is
faster than closing the existing handle and opening a new one.

The new row must meet the same criteria as for sqlite3_blob_open() -
it must exist and there must be either a blob or text value stored in
the nominated column. If the new row is not present in the table, or if
it does not contain a blob or text value, or if another error occurs, an
SQLite error code is returned and the blob handle is considered aborted.
All subsequent calls to sqlite3_blob_read(), sqlite3_blob_write() or
sqlite3_blob_reopen() on an aborted blob handle immediately return
SQLITE_ABORT. Calling sqlite3_blob_bytes() on an aborted blob handle
always returns zero.

This function sets the database handle error code and message.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Name Of The Folder Holding Temporary Files
c5: c3ref/temp_directory.html
c4:
If this global variable is made to point to a string which is
the name of a folder (a.k.a. directory), then all temporary files
created by SQLite when using a built-in VFS
will be placed in that directory.  If this variable
is a NULL pointer, then SQLite performs a search for an appropriate
temporary file directory.

Applications are strongly discouraged from using this global variable.
It is required to set a temporary folder on Windows Runtime (WinRT).
But for all other platforms, it is highly recommended that applications
neither read nor write this variable.  This global variable is a relic
that exists for backwards compatibility of legacy applications and should
be avoided in new projects.

It is not safe to read or modify this variable in more than one
thread at a time.  It is not safe to read or modify this variable
if a database connection is being used at the same time in a separate
thread.
It is intended that this variable be set once
as part of process initialization and before any SQLite interface
routines have been called and that this variable remain unchanged
thereafter.

The temp_store_directory pragma may modify this variable and cause
it to point to memory obtained from sqlite3_malloc.  Furthermore,
the temp_store_directory pragma always assumes that any string
that this variable points to is held in memory obtained from
sqlite3_malloc and the pragma may attempt to free that memory
using sqlite3_free.
Hence, if this variable is modified directly, either it should be
made NULL or made to point to memory obtained from sqlite3_malloc
or else the use of the temp_store_directory pragma should be avoided.
Except when requested by the temp_store_directory pragma, SQLite
does not free the memory that sqlite3_temp_directory points to.  If
the application wants that memory to be freed, it must do
so itself, taking care to only do so after all database connection
objects have been destroyed.

Note to Windows Runtime users:  The temporary directory must be set
prior to calling sqlite3_open or sqlite3_open_v2.  Otherwise, various
features that require the use of temporary files may fail.  Here is an
example of how to do this using C++ with the Windows Runtime:


See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_BLOB, SQLITE_NULL
c2: C API: Fundamental Datatypes
c5: c3ref/c_blob.html
c4:
Every value in SQLite has one of five fundamental datatypes:


 64-bit signed integer
 64-bit IEEE floating point number
 string
 BLOB
 NULL


These constants are codes for each of those types.

Note that the SQLITE_TEXT constant was also used in SQLite version 2
for a completely different meaning.  Software that links against both
SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
SQLITE_TEXT.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_UTF8, SQLITE_UTF16LE, SQLITE_UTF16BE, SQLITE_UTF16, SQLITE_ANY, SQLITE_UTF16_ALIGNED
c2: C API: Text Encodings
c5: c3ref/c_any.html
c4:
These constant define integer codes that represent the various
text encodings supported by SQLite.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_pcache_methods2
c2: C API: Application Defined Page Cache.
c5: c3ref/pcache_methods2.html
c4:
The sqlite3_config(SQLITE_CONFIG_PCACHE2, ...) interface can
register an alternative page cache implementation by passing in an
instance of the sqlite3_pcache_methods2 structure.
In many applications, most of the heap memory allocated by
SQLite is used for the page cache.
By implementing a
custom page cache using this API, an application can better control
the amount of memory consumed by SQLite, the way in which
that memory is allocated and released, and the policies used to
determine exactly which parts of a database file are cached and for
how long.

The alternative page cache mechanism is an
extreme measure that is only needed by the most demanding applications.
The built-in page cache is recommended for most uses.

The contents of the sqlite3_pcache_methods2 structure are copied to an
internal buffer by SQLite within the call to sqlite3_config.  Hence
the application may discard the parameter after the call to
sqlite3_config() returns.



The xInit() method is called once for each effective
call to sqlite3_initialize()
(usually only once during the lifetime of the process). The xInit()
method is passed a copy of the sqlite3_pcache_methods2.pArg value.
The intent of the xInit() method is to set up global data structures
required by the custom page cache implementation.
If the xInit() method is NULL, then the
built-in default page cache is used instead of the application defined
page cache.



The xShutdown() method is called by sqlite3_shutdown().
It can be used to clean up
any outstanding resources before process shutdown, if required.
The xShutdown() method may be NULL.

SQLite automatically serializes calls to the xInit method,
so the xInit method need not be threadsafe.  The
xShutdown method is only called from sqlite3_shutdown() so it does
not need to be threadsafe either.  All other methods must be threadsafe
in multithreaded applications.

SQLite will never invoke xInit() more than once without an intervening
call to xShutdown().



SQLite invokes the xCreate() method to construct a new cache instance.
SQLite will typically create one cache instance for each open database file,
though this is not guaranteed. The
first parameter, szPage, is the size in bytes of the pages that must
be allocated by the cache.  szPage will always a power of two.  The
second parameter szExtra is a number of bytes of extra storage
associated with each page cache entry.  The szExtra parameter will
a number less than 250.  SQLite will use the
extra szExtra bytes on each page to store metadata about the underlying
database page on disk.  The value passed into szExtra depends
on the SQLite version, the target platform, and how SQLite was compiled.
The third argument to xCreate(), bPurgeable, is true if the cache being
created will be used to cache database pages of a file stored on disk, or
false if it is used for an in-memory database. The cache implementation
does not have to do anything special based with the value of bPurgeable;
it is purely advisory.  On a cache where bPurgeable is false, SQLite will
never invoke xUnpin() except to deliberately delete a page.
In other words, calls to xUnpin() on a cache with bPurgeable set to
false will always have the "discard" flag set to true.
Hence, a cache created with bPurgeable false will
never contain any unpinned pages.



The xCachesize() method may be called at any time by SQLite to set the
suggested maximum cache-size (number of pages stored by) the cache
instance passed as the first argument. This is the value configured using
the SQLite "PRAGMA cache_size" command.  As with the bPurgeable
parameter, the implementation is not required to do anything with this
value; it is advisory only.



The xPagecount() method must return the number of pages currently
stored in the cache, both pinned and unpinned.



The xFetch() method locates a page in the cache and returns a pointer to
an sqlite3_pcache_page object associated with that page, or a NULL pointer.
The pBuf element of the returned sqlite3_pcache_page object will be a
pointer to a buffer of szPage bytes used to store the content of a
single database page.  The pExtra element of sqlite3_pcache_page will be
a pointer to the szExtra bytes of extra storage that SQLite has requested
for each entry in the page cache.

The page to be fetched is determined by the key. The minimum key value
is 1.  After it has been retrieved using xFetch, the page is considered
to be "pinned".

If the requested page is already in the page cache, then the page cache
implementation must return a pointer to the page buffer with its content
intact.  If the requested page is not already in the cache, then the
cache implementation should use the value of the createFlag
parameter to help it determined what action to take:


 createFlag  Behavior when page is not already in cache
 0  Do not allocate a new page.  Return NULL.
 1  Allocate a new page if it easy and convenient to do so.
Otherwise return NULL.
 2  Make every effort to allocate a new page.  Only return
NULL if allocating a new page is effectively impossible.


SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
will only use a createFlag of 2 after a prior call with a createFlag of 1
failed.  In between the xFetch() calls, SQLite may
attempt to unpin one or more cache pages by spilling the content of
pinned pages to disk and synching the operating system disk cache.



xUnpin() is called by SQLite with a pointer to a currently pinned page
as its second argument.  If the third parameter, discard, is non-zero,
then the page must be evicted from the cache.
If the discard parameter is
zero, then the page may be discarded or retained at the discretion of
page cache implementation. The page cache implementation
may choose to evict unpinned pages at any time.

The cache must not perform any reference counting. A single
call to xUnpin() unpins the page regardless of the number of prior calls
to xFetch().



The xRekey() method is used to change the key value associated with the
page passed as the second argument. If the cache
previously contains an entry associated with newKey, it must be
discarded. Any prior cache entry associated with newKey is guaranteed not
to be pinned.

When SQLite calls the xTruncate() method, the cache must discard all
existing cache entries with page numbers (keys) greater than or equal
to the value of the iLimit parameter passed to xTruncate(). If any
of these pages are pinned, they are implicitly unpinned, meaning that
they can be safely discarded.



The xDestroy() method is used to delete a cache allocated by xCreate().
All resources associated with the specified cache should be freed. After
calling the xDestroy() method, SQLite considers the sqlite3_pcache*
handle invalid, and will not use it with any other sqlite3_pcache_methods2
functions.



SQLite invokes the xShrink() method when it wants the page cache to
free up as much of heap memory as possible.  The page cache implementation
is not obligated to free any memory, but well-behaved implementations should
do their best.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Result Values From A Query
c5: c3ref/column_blob.html
c0:
sqlite3_column_blob(), sqlite3_column_double(), sqlite3_column_int(), sqlite3_column_int64(), sqlite3_column_text(), sqlite3_column_text16(), sqlite3_column_value(), sqlite3_column_bytes(), sqlite3_column_bytes16(), sqlite3_column_type()

c4:
Summary:


Details:

These routines return information about a single column of the current
result row of a query.  In every case the first argument is a pointer
to the prepared statement that is being evaluated (the sqlite3_stmt*
that was returned from sqlite3_prepare_v2() or one of its variants)
and the second argument is the index of the column for which information
should be returned. The leftmost column of the result set has the index 0.
The number of columns in the result can be determined using
sqlite3_column_count().

If the SQL statement does not currently point to a valid row, or if the
column index is out of range, the result is undefined.
These routines may only be called when the most recent call to
sqlite3_step() has returned SQLITE_ROW and neither
sqlite3_reset() nor sqlite3_finalize() have been called subsequently.
If any of these routines are called after sqlite3_reset() or
sqlite3_finalize() or after sqlite3_step() has returned
something other than SQLITE_ROW, the results are undefined.
If sqlite3_step() or sqlite3_reset() or sqlite3_finalize()
are called from a different thread while any of these routines
are pending, then the results are undefined.

The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
each return the value of a result column in a specific data format.  If
the result column is not initially in the requested format (for example,
if the query returns an integer but the sqlite3_column_text() interface
is used to extract the value) then an automatic type conversion is performed.

The sqlite3_column_type() routine returns the
datatype code for the initial data type
of the result column.  The returned value is one of SQLITE_INTEGER,
SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL.
The return value of sqlite3_column_type() can be used to decide which
of the first six interface should be used to extract the column value.
The value returned by sqlite3_column_type() is only meaningful if no
automatic type conversions have occurred for the value in question.
After a type conversion, the result of calling sqlite3_column_type()
is undefined, though harmless.  Future
versions of SQLite may change the behavior of sqlite3_column_type()
following a type conversion.

If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
or sqlite3_column_bytes16() interfaces can be used to determine the size
of that BLOB or string.

If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
routine returns the number of bytes in that BLOB or string.
If the result is a UTF-16 string, then sqlite3_column_bytes() converts
the string to UTF-8 and then returns the number of bytes.
If the result is a numeric value then sqlite3_column_bytes() uses
sqlite3_snprintf() to convert that value to a UTF-8 string and returns
the number of bytes in that string.
If the result is NULL, then sqlite3_column_bytes() returns zero.

If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
routine returns the number of bytes in that BLOB or string.
If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
the string to UTF-16 and then returns the number of bytes.
If the result is a numeric value then sqlite3_column_bytes16() uses
sqlite3_snprintf() to convert that value to a UTF-16 string and returns
the number of bytes in that string.
If the result is NULL, then sqlite3_column_bytes16() returns zero.

The values returned by sqlite3_column_bytes() and
sqlite3_column_bytes16() do not include the zero terminators at the end
of the string.  For clarity: the values returned by
sqlite3_column_bytes() and sqlite3_column_bytes16() are the number of
bytes in the string, not the number of characters.

Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
even empty strings, are always zero-terminated.  The return
value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.

Warning: The object returned by sqlite3_column_value() is an
unprotected sqlite3_value object.  In a multithreaded environment,
an unprotected sqlite3_value object may only be used safely with
sqlite3_bind_value() and sqlite3_result_value().
If the unprotected sqlite3_value object returned by
sqlite3_column_value() is used in any other way, including calls
to routines like sqlite3_value_int(), sqlite3_value_text(),
or sqlite3_value_bytes(), the behavior is not threadsafe.
Hence, the sqlite3_column_value() interface
is normally only useful within the implementation of
application-defined SQL functions or virtual tables, not within
top-level application code.

The these routines may attempt to convert the datatype of the result.
For example, if the internal representation is FLOAT and a text result
is requested, sqlite3_snprintf() is used internally to perform the
conversion automatically.  The following table details the conversions
that are applied:



Note that when type conversions occur, pointers returned by prior
calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
sqlite3_column_text16() may be invalidated.
Type conversions and pointer invalidations might occur
in the following cases:


 The initial content is a BLOB and sqlite3_column_text() or
sqlite3_column_text16() is called.  A zero-terminator might
need to be added to the string.
 The initial content is UTF-8 text and sqlite3_column_bytes16() or
sqlite3_column_text16() is called.  The content must be converted
to UTF-16.
 The initial content is UTF-16 text and sqlite3_column_bytes() or
sqlite3_column_text() is called.  The content must be converted
to UTF-8.


Conversions between UTF-16be and UTF-16le are always done in place and do
not invalidate a prior pointer, though of course the content of the buffer
that the prior pointer references will have been modified.  Other kinds
of conversion are done in place when it is possible, but sometimes they
are not possible and in those cases prior pointers are invalidated.

The safest policy is to invoke these routines
in one of the following ways:


sqlite3_column_text() followed by sqlite3_column_bytes()
sqlite3_column_blob() followed by sqlite3_column_bytes()
sqlite3_column_text16() followed by sqlite3_column_bytes16()


In other words, you should call sqlite3_column_text(),
sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
into the desired format, then invoke sqlite3_column_bytes() or
sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
to sqlite3_column_text() or sqlite3_column_blob() with calls to
sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
with calls to sqlite3_column_bytes().

The pointers returned are valid until a type conversion occurs as
described above, or until sqlite3_step() or sqlite3_reset() or
sqlite3_finalize() is called.  The memory space used to hold strings
and BLOBs is freed automatically.  Do not pass the pointers returned
from sqlite3_column_blob(), sqlite3_column_text(), etc. into
sqlite3_free().

As long as the input parameters are correct, these routines will only
fail if an out-of-memory error occurs during a format conversion.
Only the following subset of interfaces are subject to out-of-memory
errors:


 sqlite3_column_blob()
 sqlite3_column_text()
 sqlite3_column_text16()
 sqlite3_column_bytes()
 sqlite3_column_bytes16()


If an out-of-memory error occurs, then the return value from these
routines is the same as if the column had contained an SQL NULL value.
Valid SQL NULL returns can be distinguished from out-of-memory errors
by invoking the sqlite3_errcode() immediately after the suspect
return value is obtained and before any
other SQLite interface is called on the same database connection.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_pcache
c2: C API: Custom Page Cache Object
c5: c3ref/pcache.html
c4:
The sqlite3_pcache type is opaque.  It is implemented by
the pluggable module.  The SQLite core has no knowledge of
its size or internal structure and never deals with the
sqlite3_pcache object except by holding and passing pointers
to the object.

See sqlite3_pcache_methods2 for additional information.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_backup
c2: C API: Online Backup Object
c5: c3ref/backup.html
c4:
The sqlite3_backup object records state information about an ongoing
online backup operation.  The sqlite3_backup object is created by
a call to sqlite3_backup_init() and is destroyed by a call to
sqlite3_backup_finish().

See Also: Using the SQLite Online Backup API
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_deserialize()
c2: C API: Deserialize a database
c5: c3ref/deserialize.html
c4:
The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
database connection D to disconnect from database S and then
reopen S as an in-memory database based on the serialization contained
in P.  The serialized database P is N bytes in size.  M is the size of
the buffer P, which might be larger than N.  If M is larger than N, and
the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
permitted to add content to the in-memory database as long as the total
size does not exceed M bytes.

If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
invoke sqlite3_free() on the serialization buffer when the database
connection closes.  If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
SQLite will try to increase the buffer size using sqlite3_realloc64()
if writes on the database cause it to grow larger than M bytes.

The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
database is currently in a read transaction or is involved in a backup
operation.

If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
sqlite3_free() is invoked on argument P prior to returning.

This interface is only available if SQLite is compiled with the
SQLITE_ENABLE_DESERIALIZE option.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_db_handle()
c2: C API: Find The Database Handle Of A Prepared Statement
c5: c3ref/db_handle.html
c4:
The sqlite3_db_handle interface returns the database connection handle
to which a prepared statement belongs.  The database connection
returned by sqlite3_db_handle is the same database connection
that was the first argument
to the sqlite3_prepare_v2() call (or its variants) that was used to
create the statement in the first place.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_busy_handler()
c2: C API: Register A Callback To Handle SQLITE_BUSY Errors
c5: c3ref/busy_handler.html
c4:
The sqlite3_busy_handler(D,X,P) routine sets a callback function X
that might be invoked with argument P whenever
an attempt is made to access a database table associated with
database connection D when another thread
or process has the table locked.
The sqlite3_busy_handler() interface is used to implement
sqlite3_busy_timeout() and PRAGMA busy_timeout.

If the busy callback is NULL, then SQLITE_BUSY
is returned immediately upon encountering the lock.  If the busy callback
is not NULL, then the callback might be invoked with two arguments.

The first argument to the busy handler is a copy of the void* pointer which
is the third argument to sqlite3_busy_handler().  The second argument to
the busy handler callback is the number of times that the busy handler has
been invoked previously for the same locking event.  If the
busy callback returns 0, then no additional attempts are made to
access the database and SQLITE_BUSY is returned
to the application.
If the callback returns non-zero, then another attempt
is made to access the database and the cycle repeats.

The presence of a busy handler does not guarantee that it will be invoked
when there is lock contention. If SQLite determines that invoking the busy
handler could result in a deadlock, it will go ahead and return SQLITE_BUSY
to the application instead of invoking the
busy handler.
Consider a scenario where one process is holding a read lock that
it is trying to promote to a reserved lock and
a second process is holding a reserved lock that it is trying
to promote to an exclusive lock.  The first process cannot proceed
because it is blocked by the second and the second process cannot
proceed because it is blocked by the first.  If both processes
invoke the busy handlers, neither will make any progress.  Therefore,
SQLite returns SQLITE_BUSY for the first process, hoping that this
will induce the first process to release its read lock and allow
the second process to proceed.

The default busy callback is NULL.

There can only be a single busy handler defined for each
database connection.  Setting a new busy handler clears any
previously set handler.  Note that calling sqlite3_busy_timeout()
or evaluating PRAGMA busy_timeout=N will change the
busy handler and thus clear any previously set busy handler.

The busy callback should not take any actions which modify the
database connection that invoked the busy handler.  In other words,
the busy handler is not reentrant.  Any such actions
result in undefined behavior.

A busy handler must not close the database connection
or prepared statement that invoked the busy handler.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: struct sqlite3_vtab_cursor
c2: C API: Virtual Table Cursor Object
c5: c3ref/vtab_cursor.html
c4:
Every virtual table module implementation uses a subclass of the
following structure to describe cursors that point into the
virtual table and are used
to loop through the virtual table.  Cursors are created using the
xOpen method of the module and are destroyed
by the xClose method.  Cursors are used
by the xFilter, xNext, xEof, xColumn, and xRowid methods
of the module.  Each module implementation will define
the content of a cursor structure to suit its own needs.

This superclass exists in order to define fields of the cursor that
are common to all implementations.
See also lists of
  Objects,
  Constants, and
  Functions.


