# page_content

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.
This page last modified on  2022-04-18 02:55:50 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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 are 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.
This page last modified on  2024-02-21 13:43:47 UTC


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 INDEXED 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
INDEXED 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.

This page last modified on  2022-01-08 05:02:57 UTC


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.

This page last modified on  2022-01-08 05:02:57 UTC


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 147-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
MATERIALIZED
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
RETURNING
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


This page last modified on  2022-11-26 14:56:19 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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).

This page last modified on  2022-01-08 05:02:57 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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

BEFORE and AFTER triggers work only on ordinary tables.
INSTEAD OF triggers work only on views.

If an INSTEAD OF INSERT trigger exists on a view, then it is
possible to execute an INSERT statement against that view.  No actual
insert occurs.  Instead, the statements contained within the trigger
are run.  INSTEAD OF DELETE and
INSTEAD OF UPDATE triggers work the same way for DELETE and UPDATE statements
against views.

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: RETURNING
c5: lang_returning.html
c4:
1. Overview



 
 


 
 


 
 



 
 


 
 




 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 







The RETURNING clause is not a statement itself, but a clause that can
optionally appear near the end of top-level
DELETE, INSERT, and UPDATE statements.
The effect of the RETURNING clause is to cause the statement to return
one result row for each database row that is deleted, inserted, or updated.
 RETURNING is not standard SQL.  It is an extension.
SQLite's syntax for RETURNING is modelled after 
PostgreSQL.
  

The RETURNING syntax has been supported by SQLite since version 3.35.0
(2021-03-12).

1.1. Typical Use


The RETURNING clause is designed to provide the application with the
values of columns that are filled in automatically by SQLite.  For
example:

CREATE TABLE t0(
  a INTEGER PRIMARY KEY,
  b DATE DEFAULT CURRENT_TIMESTAMP,
  c INTEGER
);
INSERT INTO t0(c) VALUES(random()) RETURNING *;



In the INSERT statement above, SQLite computes the values for all
three columns.  The RETURNING clause causes SQLite to report the chosen
values back to the application.  This saves the application from having
to issue a separate query to figure out exactly what values were inserted.

2. Details


The RETURNING clause is followed by a comma-separated list of
expressions.  These expressions are similar to the expressions following
the SELECT keyword in a SELECT statement in that they
define the values of the columns in the result set.  Each expression
defines the value for a single column.  Each expression may be
optionally followed by an AS clause that determines the name of
the result column.  The special "*" expression expands into a list
of all non-hidden columns of the table being deleted,
inserted, or updated.


For INSERT and UPDATE statements, references to columns in the table
being modified refer to the value of that column after the change
has been applied.  For DELETE statements, references to columns mean
the value before the delete occurs.


The RETURNING clause only returns rows that are directly modified
by the DELETE, INSERT, or UPDATE statement.  The RETURNING clause
does not report any additional database changes
caused by foreign key constraints or triggers.


A RETURNING clause for an UPSERT reports both inserted and
updated rows.

2.1. Processing Order


When a DELETE, INSERT, or UPDATE statement with a RETURNING clause
is run, all of the database changes occur during the first invocation
of sqlite3_step().  The RETURNING clause output is accumulated in
memory.  The first sqlite3_step() call returns one row of RETURNING
output and subsequent rows of RETURNING output are returned by subsequent
calls to sqlite3_step().
To put this another way, all RETURNING clause output is embargoed
until after all database modification actions are completed.


This means that if a statement has a RETURNING clause that generates
a large amount of output, either many rows or large
string or BLOB values, then the statement might use a lot of 
temporary memory to hold those values while it is running.


The first prototype of the RETURNING clause returned
values as they were generated.  That approach used less memory, but
it had other problems:



If the calls sqlite3_step() for two or more DML statements
where interleaved and if one of the
statements hit a constraint failure and aborted, reverting its
changes, then that could disrupt the operation of the other
DML statement.  This could not corrupt the database file, but
it could yield surprising and difficult-to-explain results in
the database.


If an application failed to call sqlite3_step() repeatedly until
it received SQLITE_DONE, then some of the database changes might
never occur.


The order of operations was different from client/server database
engines like PostgreSQL, which might cause portability issues
for some applications.



For these reasons, the current implementation was modified so that
all database changes happen before any RETURNING output is emitted.


While SQLite does guarantee that all database changes will occur
before any RETURNING output is emitted, it does not guarantee
that the order of individual RETURNING rows will match the order in
which those rows were changed in the database.  The output order
for the RETURNING rows is arbitrary and is not necessarily related
to the order in which the rows were processed internally.

2.2. ACID Changes


When the previous "Processing Order" section says that
"database changes occur during the first invocation of sqlite3_step()",
that means that the changes are stored in the private page cache of
the database connection that is running the statement.  It does
not mean that the changes are actually committed.  The commit
does not occur until the statement finishes, and maybe not even then
if the statement is part of a larger transaction.  Changes to the
database are still atomic, consistent, isolated, and durable (ACID).
When the previous section says "changes occur",
this means that internal data structure are adjusted pending a transaction
commit.  Some of those changes may or may not spill into the
write-ahead log, depending on how much pressure there is on the
page cache.  If the page cache is not under memory pressure, then
probably nothing will be written to disk until after the transaction
completes, which is after sqlite3_step() returns SQLITE_DONE.


In other words, when the previous section says "database changes
occur", that means that the changes occur in the memory of the
specific database connection that is running the statement, not that
the changes are written to disk.

3. Limitations And Caveats



The RETURNING clause is not available on DELETE and UPDATE statements
against virtual tables.
This limitation might be removed in future versions of SQLite.


The RETURNING clause is only available in top-level DELETE, INSERT,
and UPDATE statements.  The RETURNING clause cannot be used by
statements within triggers.


Even though a DML statement with a RETURNING clause returns table content,
it cannot be used as a subquery.  The RETURNING clause can only return
data to the application.  It is not currently possible to divert the
RETURNING output into another table or query.  PostgreSQL has the ability
to use a DML statement with a RETURNING clause like a view in a 
common table expressions. SQLite does not currently have that
ability, though that is something that might be added in a future release.


The rows emitted by the RETURNING clause appear in an arbitrary order.
That order might change depending on the database schema, upon the specific
release of SQLite used, or even from one execution of the same statement
to the next.
There is no way to cause the output rows to appear in a particular order.
Even if SQLite is compiled with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT
option such that ORDER BY clauses are allowed on DELETE and UPDATE
statements, those ORDER BY clauses do not constrain the output order
of RETURNING.


The values emitted by the RETURNING clause are the values as seen
by the top-level DELETE, INSERT, or UPDATE statement
and do not reflect any subsequent value changes made by triggers.
Thus, if the database includes AFTER triggers that modifies some
of the values of each row inserted or updated, the RETURNING clause
emits the original values that are computed before those triggers run.


The RETURNING clause may not contain top-level aggregate functions or
window functions.  If there are subqueries in the RETURNING clause,
those subqueries may contain aggregates and window functions, but
aggregates cannot occur at the top level.


The RETURNING clause may only reference the table being modified.
In an UPDATE FROM statement, the auxiliary tables named in the FROM
clause may not participate in the RETURNING clause.


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.
This page last modified on  2022-01-08 05:02:57 UTC


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,
math 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.


 
 



See the functions within expressions documentation for
more information about how SQL function invocations fit into the context
of an SQL expression.

2. List Of Core Functions




abs(X)
changes()
char(X1,X2,...,XN)
coalesce(X,Y,...)
concat(X,...)
concat_ws(SEP,X,...)
format(FORMAT,...)
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)
octet_length(X)
printf(FORMAT,...)
quote(X)
random()
randomblob(N)
replace(X,Y,Z)
round(X)
round(X,Y)
rtrim(X)
rtrim(X,Y)
sign(X)
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)
substring(X,Y)
substring(X,Y,Z)
total_changes()
trim(X)
trim(X,Y)
typeof(X)
unhex(X)
unhex(X,Y)
unicode(X)
unlikely(X)
upper(X)
zeroblob(N)




3. 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_changes64()
  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.


concat(X,...)
  The concat(...) function returns a string which is the concatenation of the
  string representation of all of its non-NULL arguments.  If all arguments are
  NULL, then concat() returns an empty string.


concat_ws(SEP,X,...)
  The concat_ws(SEP,...) function returns a string that is the concatenation of
  all non-null arguments beyond the first argument, using the text value of the
  first argument as a separator.  If the first argument is NULL, then concat_ws()
  returns NULL.  If all arguments other than the first are NULL, then concat_ws()
  returns an empty string.


format(FORMAT,...)
  The format(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.


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.
  
  If the argument X in "hex(X)" is an
  integer or floating point number, then "interprets its argument as a BLOB" means
  that the binary number is first converted into a UTF8 text representation, then
  that text is interpreted as a BLOB.  Hence, "hex(12345678)" renders
  as "3132333435363738" not the binary representation of the integer value
  "0000000000BC614E".
  
  See also:  unhex()


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.
  
  Note that for strings, the length(X) function returns the character
  length of the string, not the byte length.  The character length is the number
  of characters in the string.  The character length is always different from
  the byte length for UTF-16 strings, and can be different from the byte length
  for UTF-8 strings if the string contains multi-byte characters.  Use the
  octet_length() function to find the byte length of a string.
  
  For BLOB values, length(X) always returns the byte-length of the BLOB.
  
  For string values, length(X) must read the entire string into memory in order
  to compute the character length.  But for BLOB values, that is not necessary as
  SQLite knows how many bytes are in the BLOB.  Hence, for multi-megabyte values,
  the length(X) function is usually much faster for BLOBs than for strings, since
  it does not need to load the value into memory.


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 loading is disabled 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 collating function is used.


octet_length(X)
  The octet_length(X) function returns the number of bytes in the encoding
  of text string X.  If X is NULL then octet_length(X) returns NULL.  If X is
  a BLOB value, then octet_length(X) is the same as length(X).  If X is a
  numeric value, then octet_length(X) returns the number of bytes in a text
  rendering of that number.
  
  Because octet_length(X) returns the number of bytes in X, not the number
  of characters, the value returned depends on the database encoding.  The
  octet_length() function can return different answers for the same input string
  if the database encoding is UTF16 instead of UTF8.
  
  If argument X is a table column and the value is of type text or blob,
  then octet_length(X) avoids reading the content of X from disk, as the byte
  length can be computed from metadata.  Thus, octet_length(X) is efficient
  even if X is a column containing a multi-megabyte text or blob value.


printf(FORMAT,...)
  The printf() SQL function is an alias for the format() SQL function.
  The format() SQL function was originally named printf(). But the name was
  later changed to format() for compatibility with other database engines.
  The printf() name is retained as an alias so as not to break legacy code.


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 or negative, it is taken 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.


sign(X)
  The sign(X) function returns -1, 0, or +1 if the argument X is a numeric
  value that is negative, zero, or positive, respectively.  If the argument
  to sign(X) is NULL or is a string or blob that cannot be losslessly converted
  into a number, then sign(X) returns NULL.


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 SHA3-256 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)substring(X,Y,Z)substring(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.
  
  "substring()" is an alias for "substr()" beginning with SQLite version 3.34.


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_changes64()
  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".


unhex(X)unhex(X,Y)
  The unhex(X,Y) function returns a BLOB value which is the decoding of the
  hexadecimal string X.  If X contains any
  characters that are not hexadecimal digits and which are not in Y, 
  then unhex(X,Y) returns NULL. If Y is omitted, it is
  understood to be an empty string and hence X must be a pure hexadecimal string.
  All hexadecimal digits in X must occur in pairs, with both digits of each
  pair beginning immediately adjacent to one another, or else unhex(X,Y)
  returns NULL.
  If either parameter X or Y is NULL, then unhex(X,Y) returns NULL.
  The X input may contain an arbitrary mix of upper and lower case hexadecimal
  digits.
  Hexadecimal digits in Y have no affect on the translation of X.  Only
  characters in Y that are not hexadecimal digits are ignored in X.
  
  See also:  hex()


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.



This page last modified on  2023-12-05 14:43:20 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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.


This page last modified on  2022-01-08 05:02:57 UTC


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.

   Whether the table is subject to strict type checking.


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 SELECT statement returns. 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 ALWAYS AS clause is a generated column.
Generated columns are supported beginning with SQLite version 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 a STRICT 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
  allows 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.

CHECK constraints are only verified when the table is written, not when
   it is read.  Furthermore, verification of CHECK constraints can be
   temporarily disabled using the "PRAGMA ignore_check_constraints=ON;"
   statement.  Hence, it is possible that a query might produce results that
   violate the CHECK constraints.



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.  NOT NULL
  constraints are not verified during queries, so a query of a column might
  produce a NULL value even though the column is marked as NOT NULL, if the
  database file is corrupt.


4. Constraint enforcement

Constraints are checked during INSERT and UPDATE and by
PRAGMA integrity_check and PRAGMA quick_check and sometimes
by ALTER TABLE.  Queries and DELETE
statements do not normally verify constraints.
Hence, if a database file has been corrupted (perhaps by an external
program making direct changes to the database file without going through 
the SQLite library) a query might return data that violates a constraint.
For example:

CREATE TABLE t1(x INT CHECK( x>3 ));
/* Insert a row with X less than 3 by directly writing into the
** database file using an external program */
PRAGMA integrity_check;  -- Reports row with x less than 3 as corrupt
INSERT INTO t1(x) VALUES(2);  -- Fails with SQLITE_CORRUPT
SELECT x FROM t1;  -- Returns an integer less than 3 in spite of the CHECK constraint


Enforcement of CHECK constraints can be temporarily disabled using
the PRAGMA ignore_check_constraints=ON; statement.

4.1. Response to constraint violations

The response to a constraint violation 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 another default conflict resolution algorithm by
  including a  in their definitions.
  Or, if a constraint definition does not include a ,
  the default conflict resolution algorithm is ABORT.
  The conflict resolution algorithm for CHECK constraints is always ABORT.
  (For historical compatibility only, table CHECK constraints are allowed
  to have a conflict resolution clause, but that has no effect.)
  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: 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.




2.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 does not match any row in the right-hand dataset.
       The added rows contain NULL values in the columns
       that would normally contain values copied from the right-hand input
       dataset.  

   
       

       If the join-operator is a "RIGHT JOIN" or "RIGHT 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 right-hand input 
       dataset that does not match any row in the left-hand dataset.
       The added rows contain NULL values in the columns
       that would normally contain values copied from the left-hand input
       dataset.  

   
       

       A "FULL JOIN" or "FULL OUTER JOIN" is a combination of a
       "LEFT JOIN" and a "RIGHT JOIN".  Extra rows of output are
       added for each row in left dataset that matches no rows in the right,
       and for each row in the right dataset that matches no rows in the
       left.  Unmatched columns are filled in with NULL.


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).



2.2. 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.3. 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.




2.4. 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 according to
    the processing rules stated below for ORDER BY expressions. 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.




2.5. Bare columns in an aggregate query

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;


If there is exactly one min() or max() aggregate
in the query, then all bare columns in the result set take values from an
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 are limitations on this special behavior of
min() and max():



If the same minimum or maximum value occurs on two or more rows,
then bare values might be selected from any of those rows.  The choice
is arbitrary.  There is no way to predict from which row the bare values
will be choosen.  The choice might be different for different bare columns
within the same query.


If there are two or more min() or max() aggregates
in the query, then bare column values will be taken from one of the rows
on which one of the aggregates has their minimum or maximum value.  The choice
of which min() or max() aggregate determines the 
selection of bare column values is arbitrary.  The choice might be different
for different bare columns within the same query.


This special processing for min() or max() aggregates
only works for the built-in implementation of those aggregates.  If an
application overrides the built-in min() or max() aggregates
with application-defined alternatives, then the values selected for bare
columns will be taken from an arbitrary row.


Most other SQL database engines disallow bare columns.  If you include
a bare column in a query, other database engines will usually raise an error.
The ability to include bare columns in a query is an SQLite-specific extension.
This is considered a feature, not a bug.  See the discussion on 
SQLite Forum thread 7481d2a6df8980ff
for additional information.




2.6. 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.




9. Deviations From Standard SQL

The SELECT syntax of SQLite differs slightly from standard SQL.
These differences are due to several reasons:


 In the mid-2000s, there was a lot of emphasis on keeping the library
        footprint as small as possible, so as not to use too much space
        on memory-limited flip-phones and similar.

 During the early years of SQLite, the lead developer sought to follow
        Postel's Law and to
        be forgiving and flexible in what input was accepted.

 There were bugs in early SQLite parsers that accepts some strange inputs.

 The lead developer's knowledge of SQL was imperfect.


Whatever the origin of the input quirks, we generally avoid trying to "fix" them,
as any new restrictions on the input syntax would likely cause at least some of
the millions of applications that use SQLite to break.  We do not want that.
The goal of the SQLite development team is to preserve backwards compability to
the fullest extent possible.  Hence, if a syntax quirk is harmless,
we leave it alone and document it here, rather than try to fix it.

9.1. Strange JOIN names

SQLite accepts all of the usual syntax for JOIN operators:



 
 



But it does not stop there.  SQLite is actually very flexible in how you
specify a join operator.  The general syntax is:


blah blah blah JOIN


Where there are between 1 and 3 instances of "blah", each of which can be
any of "CROSS", "FULL", "INNER", "LEFT", "NATURAL", "OUTER", or "RIGHT".  The SQLite
parser treats each of these keywords as an attribute of the join, which can be combined
in any order.  This creates the possibility of many new and creative join types beyond
what is specified by the syntax diagram.  Some of these non-standard join types are
specifically disallowed.  For example, you cannot say "INNER OUTER JOIN", because
that would be contradictory.  But you can say things like "OUTER LEFT NATURAL JOIN"
which means the same as "NATURAL LEFT OUTER JOIN".  Or you can say "LEFT RIGHT JOIN"
which is the same as "FULL JOIN".

Remember:  you can use these non-standard join types but you ought not.
Stick to using standard JOIN syntax for portability with other SQL database engines.

9.2. Precedence of comma-joins and CROSS JOIN

In standard SQL, joins that use the JOIN keyword take higher precedence
than comma-joins.  That is to say, JOIN operators happen before comma operators.
This is not the case in SQLite, where all joins have the same precedence.

Consider this example:


... FROM t1, t2 NATURAL FULL JOIN t3 ...


In standard SQL, the FULL JOIN between t2 and t3 would occur first, and
then the result of the left join would be cross-joined against t1.  But SQLite
always handles all joins from left to right.  Thus, SQLite will do a cross
join on t1 and t2 first, then the result of that cross join will feed into the FULL JOIN
with t3.  Inner joins are inherently associative, so the difference is only
evident if your FROM clause contains one or more outer joins.

You can work around this, and make your SQL statements portable across all
systems, by observing the following stylistic rules:


 Do not mix comma-joins with the JOIN keyword.  It is fine to use comma-joins,
but if you do, the you should use only comma-joins for the entire FROM clause.

 Prefer LEFT JOIN over other outer join operators.

 When in doubt, use parentheses to specify the exact join order that you intend.


Any one of these suggestions is sufficient to avoid problems, and most
programmers instinctively follow all of these suggestions without having to
be told, and so the lack of precedence difference between comma-joins and
the JOIN keyword in SQLite rarely comes up in practice.  But you should be aware
of the problem, in case it ever does appear.
This page last modified on  2023-06-13 13:23:44 UTC


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.
This page last modified on  2022-04-18 02:55:50 UTC


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 operates 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 a file named by the
argument to the INTO clause.
The argument is a scalar expression, such as a text literal.
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 loss, 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.


This page last modified on  2023-12-05 14:43:20 UTC


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


 
 


 
 


 
 



 
 



 
 


 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 


 
 





 
 


 
 





 
 



 
 





The aggregate functions shown below are available by default. 
There are two more aggregates grouped with the JSON SQL functions.
Applications can define custom aggregate functions using the
sqlite3_create_function() interface.
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.





If an ORDER BY clause is provided, that clause determines the order in which
the inputs to the aggregate are processed.  For aggregate functions like max()
and count(), the input order does not matter.  But for things like
string_agg() and json_group_object(), the ORDER BY clause will make a
difference in the result.  If no ORDER BY clause is specified, the inputs to the
aggregate occur in an arbitrary order that might change from one invocation
to the next.



See also: scalar functions and window functions.



2. List of built-in aggregate functions



avg(X)
count(*)
count(X)
group_concat(X)
group_concat(X,Y)
max(X)
min(X)
string_agg(X,Y)
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 whenever
  there is at least one non-NULL input even if all
  inputs are integers.  The result of avg() is NULL if
  there are no non-NULL inputs.  The result of avg() is computed
  as total()/count() so all of the constraints that apply to
  total() also apply to avg().


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)string_agg(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 string_agg(X,Y) function is an alias
  for group_concat(X,Y).  String_agg() is compatible with PostgreSQL
  and SQL-Server and group_concat() is compatible with MySQL.
  
  The order of the concatenated elements is arbitrary unless an
  ORDER BY argument is included immediately after the last parameter.


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 the 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 nor a NULL,
  then sum() returns a floating point value
  which is an approximation of the mathematical 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.
  No overflow error is ever raised if any prior input was a floating point
  value.
  Total() never throws an integer overflow.

  When summing floating-point values, if the magnitudes of the values
  differ wildly then the resulting sum might be imprecise due to the fact that
  IEEE 754 floating point values are approximations.
  Use the decimal_sum(X) aggregate in the decimal extension to obtain
  an exact summation of floating point numbers.  Consider this test case:


CREATE TABLE t1(x REAL);
INSERT INTO t1 VALUES(1.55e+308),(1.23),(3.2e-16),(-1.23),(-1.55e308);
SELECT sum(x), decimal_sum(x) FROM t1;


  The large values &plusmn;1.55e+308 cancel each other out, but the
  cancellation does not occur until the end of the sum and in the meantime
  the large +1.55e+308 swamps the tiny 3.2e-16 value.  The end result is
  an imprecise result for the sum().  The decimal_sum() aggregate
  generates an exact answer, at the cost of additional CPU and memory usage.
  Note also that decimal_sum() is not built into the SQLite core; it is a
  loadable extension.

  If sum of inputs is too large to represent as a IEEE 754 floating
  point value, then a +Infinity or -Infinity result may be returned.
  If very large values with differing signs are used
  such that the SUM() or TOTAL() function is
  unable to determine if the correct result is +Infinity or -Infinity
  or some other value in between, then the result is NULL.  Hence, for
  example, the following query returns NULL:


WITH t1(x) AS (VALUES(1.0),(-9e+999),(2.0),(+9e+999),(3.0))
 SELECT sum(x) FROM t1;




This page last modified on  2023-12-05 14:43:20 UTC


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


 
 


 
 



 
 


 
 



 
 


 
 




 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 





 
 




2. Description

UPSERT is a clause added 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, with generalizations.

An UPSERT is an ordinary INSERT statement that is followed by
one or more ON CONFLICT clauses, as shown in the syntax diagram above.

The syntax in between the "ON CONFLICT" and "DO" keywords
is called the "conflict target".  The conflict target specifies a
uniqueness constraint that will trigger the upsert.  The conflict target
may be omitted on the last ON CONFLICT clause in the INSERT statement, but
is required for all other ON CONFLICT clauses.

If the insert operation would cause the conflict target uniqueness
constraint to fail, then the insert is omitted and
the corresponding DO NOTHING or DO UPDATE operation is performed instead.
The ON CONFLICT clauses are checked in the order specified.  If the last
ON CONFLICT clause omits the conflict target, then it will fire if any
uniqueness constraint fails which is not captured by prior ON CONFLICT clauses.

Only a single ON CONFLICT clause, specifically the first ON CONFLICT
clause with a matching conflict target, may run for each row of the INSERT.
When an ON CONFLICT clause fires, all subsequent ON CONFLICT clauses are
bypassed for that one row.


In the case of a multi-row insert, the upsert decision is made separately
for each row of the insert.

The UPSERT processing happens only for uniqueness constraints.
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, CHECK,
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.

2.1. Examples

Some examples will help illustrate how UPSERT works:


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 restricts 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.2. 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.

The conflict resolution algorithm for the update operation
of the DO UPDATE clause is always ABORT.  In other words, the behavior
is as if the DO UPDATE clause were actually written as
"DO UPDATE OR ABORT".  If the DO UPDATE clause encounters any
constraint violation, the entire INSERT statement rolls back and
halts.  This is true even if the DO UPDATE clause is
contained within an INSERT statement or a trigger that specifies some
other conflict resolution algorithm.

4. History

UPSERT syntax was added to SQLite with version 3.24.0 (2018-06-04).
The original implementation closely followed the PostgreSQL syntax in that
it only permitted a single ON CONFLICT clause and it required a
conflict target for on DO UPDATE.
The syntax was generalized to permit multiple ON CONFLICT clauses and
to allow DO UPDATE resolution without a conflict target in
SQLite version 3.35.0 (2021-03-12).
This page last modified on  2024-04-11 23:26:09 UTC


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.

This page last modified on  2022-01-08 05:02:57 UTC


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.

This page last modified on  2022-01-08 05:02:57 UTC


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


SQLite supports seven scalar date and time functions as follows:




 date(time-value, modifier, modifier, ...) 
 time(time-value, modifier, modifier, ...) 
 datetime(time-value, modifier, modifier, ...) 
 julianday(time-value, modifier, modifier, ...) 
 unixepoch(time-value, modifier, modifier, ...) 
 strftime(format, time-value, modifier, modifier, ...) 
 timediff(time-value, time-value) 



The first six date and time functions take an optional time value as an argument, followed
by zero or more modifiers.
The strftime() function also takes a format string as its first argument.
The timediff() function takes exactly two arguments which are both time values.



Date and time values can be stored as

 text in a subset of the ISO-8601 format,
 numbers representing the Julian day, or
 numbers representing the number of seconds since (or before) 1970-01-01 00:00:00 UTC
     (the unix timestamp).



All of the date time functions access time-values as either ISO-8601 strings or
Julian day numbers.  They also access unix timestamps with optional arguments
(the 'auto' and 'unixepoch' modifiers described below).  Since the timediff()
function does not accept any optional argument, it can only use ISO-8601 and
Julian day number time values.




The date() function returns the date as text in this format: YYYY-MM-DD.




The time() function returns the time as text in this format: HH:MM:SS.




The datetime() function returns the date and time as text in this formats: YYYY-MM-DD HH:MM:SS.




The julianday() function returns the 
Julian day - the
fractional number of days since noon in Greenwich on November 24, 4714 B.C. 
(Proleptic Gregorian calendar).




The unixepoch() function returns a unix timestamp - the number of seconds
since 1970-01-01 00:00:00 UTC.  The unixepoch() function normally returns
an integer number of seconds, but with the optional subsec modifier it
will return a floating point number which is the fractional number of seconds.




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-31
 %e  day of month without leading zero: 0-31
 %f  fractional seconds: SS.SSS
 %F  ISO 8601 date: YYYY-MM-DD
 %H  hour: 00-24
 %I  hour for 12-hour clock: 01-12
 %j  day of year: 001-366
 %J  Julian day number (fractional)
 %k  hour without leading zero: 0-24
 %l  %I without leading zero: 1-12
 %m  month: 01-12
 %M  minute: 00-59
 %p  "AM" or "PM" depending on the hour
 %P  "am" or "pm" depending on the hour
 %R  ISO 8601 time: HH:MM
 %s  seconds since 1970-01-01
 %S  seconds: 00-59
 %T  ISO 8601 time: HH:MM:SS
 %u  day of week 1-7 with Monday==1
 %w  day of week 0-6 with Sunday==0
 %W  week of year: 00-53
 %Y  year: 0000-9999
 %%  %




Other date and time functions can be expressed
in terms of strftime():




FunctionEquivalent (or nearly) strftime()
   date(...)        strftime('%F', ...)
   time(...)        strftime('%T', ...)
   datetime(...)    strftime('%F %T', ...)
   julianday(...)   strftime('%J', ...) -- (numeric return)
   unixepoch(...)   strftime('%s', ...) -- (numeric return)




The date(), time(), and datetime() functions all return text, and so their
strftime() equivalents are exact.  However, the julianday()
and unixepoch() functions return numeric values.  Their strftime() equivalents
return a string that is the text representation of the corresponding number.



The main reasons for providing functions other than strftime() are
for convenience and for efficiency. The julianday() and unixepoch()
functions return real and integer values respectively, and do not
incur the format conversion costs or inexactitude resulting from use
of the '%J' or '%s' format specifiers with the strftime() function.




1.1. Timediff()


The timediff(A,B) routine returns a string that describes the amount
of time that must be added to B in order to reach time A.  The format of
the timediff() result is designed to be human-readable.  The format is:

(+|-)YYYY-MM-DD HH:MM:SS.SSS


This time difference string is also an allowed modifier for the other
date/time functions.  The following invariant holds for time values A
and B:

datetime(A) = datetime(B, timediff(A,B))



The length of months and years vary.  February is shorter than March.
Leap years are longer than non-leap years.  The output from timediff()
takes this all into account.  The timediff() function is intended to provide
a human-friendly description of the time span.  If you want to know the
number of days or seconds between two dates, A and B, then you can always do
one of these:

SELECT julianday(B) - julianday(A);
SELECT unixepoch(B) - unixepoch(A);



The timediff(A,B) might return the same result even for values A and B
that span a different number of days - depending on the starting date.
For example, both of the following two timediff() calls return the
same result ("-0000-01-00 00:00:00.000") even though the first timespan
is 28 days and the seconds is 31 days:

SELECT timediff('2023-02-15','2023-03-15');
SELECT timediff('2023-03-15','2023-04-15');


Summary:  If you want a human-friendly time span, use timediff().  If you
what a precise time difference (in days or seconds) use the difference
between two julianday() or unixepoch() calls.



2. Time Values

A time value can be in any of the following formats shown below.
The value is usually a string, though it can be an integer or floating
point number in the case of format 12.


 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 an integer or floating point value.
Format 12 might also be interpreted as a unix timestamp if it is immediately followed
either the 'auto' or 'unixepoch' modifier.



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 values 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.



In all functions other than timediff(),
the time-value (and all modifiers) may be omitted, in which case a time
value of 'now' is assumed.



3. Modifiers

For all date/time functions other than timediff(),
the time value argument 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 seconds
 NNN months
 NNN years
 &plusmn;HH:MM
 &plusmn;HH:MM:SS
 &plusmn;HH:MM:SS.SSS
 &plusmn;YYYY-MM-DD
 &plusmn;YYYY-MM-DD HH:MM
 &plusmn;YYYY-MM-DD HH:MM:SS
 &plusmn;YYYY-MM-DD HH:MM:SS.SSS
 start of month
 start of year
 start of day
 weekday N
 unixepoch
 julianday
 auto
 localtime
 utc
 subsec
 subsecond


The first thirteen modifiers (1 through 13) 
add the specified amount of time to the date and time 
specified by the arguments to its left.
The 's' character at the end of the modifier names in 1 through 6 is optional.
The NNN value can be any floating point number, with an optional '+' or '-' prefix.
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 date 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 time shift modifiers (7 through 13) move the time value by the
number of years, months, days, hours, minutes, and/or seconds specified.
An initial "+" or "-" is required for formats 10 through 13 but is optional
for formats 7, 8, and 9.  The changes are applies from left to right.
First the year is shifted by YYYY, then the month by MM, and then day
by DD, and so forth.  The normalization and rounding due to differing month
lengths and leap years is applied after each step.  The
timediff(A,B) function returns a time shift in format 13 that shifts
the time value B into A.

The "start of" modifiers (14 through 16) shift the date backwards 
to the beginning of the subject 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 (18) only works if it immediately follows 
a time value 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 time value 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 "julianday" modifier must immediately follow the initial
time-value which must be of the form DDDDDDDDD.  Any other use of
the 'julianday' modifier is an error and causes the function to return NULL.
The 'julianday' modifier forces the time-value number to be interpreted
as a julian-day number.  As this is the default behavior, the 'julianday'
modifier is scarcely more than a no-op.  The only difference is that
adding 'julianday' forces the DDDDDDDDD time-value format, and causes
a NULL to be returned if any other time-value format is used.



The "auto" modifier must immediately follow the initial time-value.
If the time-value is numeric (the DDDDDDDDDD format) then the 'auto'
modifier causes the time-value to interpreted as either a julian day
number or a unix timestamp, depending on its magnitude.  If the value
is between 0.0 and 5373484.499999, then it is interpreted as a julian
day number (corresponding to dates between
-4713-11-24 12:00:00 and 9999-12-31 23:59:59, inclusive).  For numeric
values outside of the range of valid julian day numbers, but within 
the range of -210866760000 to 253402300799, the 'auto' modifier causes
the value to be interpreted as a unix timestamp.  Other numeric values
are out of range and cause a NULL return.  The 'auto' modifier is a no-op 
for text time-values.

The 'auto' modifier can be used to work with date/time values even in
cases where it is not known if the julian day number or unix timestamp
formats are in use.  The 'auto' modifier will automatically select the
appropriate format.  However, there is a region of ambiguity.  Unix
timestamps for the first 63 days of 1970 will be interpreted as julian
day numbers.  The 'auto' modifier is very useful when the dataset is
guaranteed to not contain any dates within that region, but should be
avoided for applications that might make use of dates in the opening
months of 1970.



The "localtime" modifier (21) assumes the time value to its left is in
Universal Coordinated Time (UTC) and adjusts that time
value so that it is in 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 time value
to its left is in the local timezone and adjusts that time value to be in UTC.
If the time to the left is not in localtime, then the result of "utc" is
undefined.




The "subsecond" modifier (which may be abbreviated as just
"subsec") increases the resolution of the output for
datetime(), time(), and unixepoch(), and for the "%s"
format string in strftime().  The "subsecond"
modifier has no effect on other date/time functions.
The current implemention increases the resolution from seconds
to milliseconds, but this might increase to a higher resolution
in future releases of SQLite.  When "subsec" is used with
datetime() or time(), the seconds field at the end is
followed by a decimal point and one or more digits to show
fractional seconds.  When "subsec" is used with unixepoch(),
the result is a floating point value which is the number of
seconds and fractional seconds since 1970-01-01.


The "subsecond" and "subsec" modifiers have the special property
that they can occur as the first argument to date/time functions
(or as the first argument after the format string for strftime()).
When this happens, the time value that is normally in the first
argument is understood to be "now".  For example, a short cut to
get the current time in seconds since 1970 with millisecond
precision is to say:


  SELECT unixepoch('subsec');


4. Examples

Compute the current date.

SELECT date();

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');
    SELECT datetime(1092941466, 'auto'); -- Does not work for early 1970!


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 unixepoch();
  SELECT strftime('%s');


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 unixepoch() - unixepoch('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 with
millisecond precision:


  SELECT (julianday('now') - 2440587.5)*86400.0;
  SELECT unixepoch('now','subsec');


Compute how old Abraham Lincoln would be if he were still alive today:


  SELECT timediff('now','1809-02-12');


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.  They also assume that every
day is exactly 86400 seconds in duration; no leap seconds are incorporated.


c2: INSERT
c5: lang_insert.html
c4:
1. Overview



 
 


 
 



 
 


 
 



 
 


 
 




 
 



 
 


 
 



 
 




 
 



 
 


 
 





 
 



 
 


 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 



 
 





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".
This page last modified on  2022-01-08 05:02:57 UTC


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.
This page last modified on  2022-01-08 05:02:57 UTC


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 attributes:


 The "" must be a compound select.  That is to say,
     the CTE body must be two or more individual SELECT statements
     separated by compound operators like UNION, UNION ALL, INTERSECT,
     or EXCEPT.
 One or more of the individual SELECT statements that make up
     the compound must be
     "recursive".  A SELECT statement is recursive if
     its FROM clause contains exactly one reference to
     the CTE table (the table named on the left-hand side of the
     AS clause).
 One or more of the SELECT statements in the compound must be
     non-recursive.
 All non-recursive SELECT statements must occur before any
     recursive SELECT statements.
 The recursive SELECT statements must be separated from the
     non-recursive SELECT statements
     and from each other by the UNION or UNION ALL operators.
     If there are two or more recursive SELECT statements, they all must
     be separated from each other using the same operator that separates
     the first recursive SELECT from the last non-recursive SELECT statement.
 Recursive SELECT statements may not use
     aggregate functions or window functions.     


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



 
 


 
 




In the diagram above, initial-select means one or more
non-recursive SELECT statements and recursive-select means
one or more recursive SELECT statements.  The most common case is for there
to be exactly one initial-select and exactly one
recursive-select but more than one of each is allowed.

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 each
top-level SELECT statement in 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 may also be a compound select with
the restriction that all elements of that compound must be separated by
the same UNION or UNION ALL operator that separates
initial-select from recursive-select.
The recursive-select is allowed to include an
ORDER BY, LIMIT, and/or OFFSET but may not use
aggregate functions or window functions.

The ability for the recursive-select to be a compound
was added in version 3.34.0 (2020-12-01).  In earlier versions of
SQLite, the recursive-select could only be a single
simple SELECT statement.

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

Suppose you have an undirected graph where each node is
identified by an integer and edges are defined by a table like
this:


CREATE TABLE edge(aa INT, bb INT);
CREATE INDEX edge_aa ON edge(aa);
CREATE INDEX edge_bb ON edge(bb);


The indexes are not required, but they do help performance
for large graphs.
To find all nodes of the graph that are connected to
node 59, use a query similar to the following:


WITH RECURSIVE nodes(x) AS (
   SELECT 59
   UNION
   SELECT aa FROM edge JOIN nodes ON bb=x
   UNION
   SELECT bb FROM edge JOIN nodes ON aa=x
)
SELECT x FROM nodes;



The initial-select in this case is the simple query
"SELECT 59".  This establishes the base case.  The
recursive-select consists of the other two
SELECT statements.  The first recursive SELECT follows edges
in the bb-to-aa direction and the second recursive SELECT follows
edges in the aa-to-bb direction.  UNION is used instead of
UNION ALL to prevent the recursion from entering an infinite
loop if the graph contains cycles.


Here is a real-world example of using a graph query against a
directed 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 checkin.  For example:
https://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. Materialization Hints


The "AS MATERIALIZED" and "AS NOT MATERIALIZED" forms of a common table expression
are non-standard SQL syntax copied from PostgreSQL.  Using MATERIALIZED or
NOT MATERIALIZED after the AS keyword provides non-binding hints to the query
planner about how the CTE should be implemented.


If the MATERIALIZED phrase is used, then select-stmt will
be materialized into an ephemeral table that is held in memory or in a
temporary disk file.  That ephemeral table will then be used in place of the
CTE table name whenever the CTE table name appears in the subsequent SQL.
Because the select-stmt is evaluated immediately,
the opportunity to apply optimizations such as
query flattening or the push-down optimization, is lost.
This loss of optimization is a feature, not a bug.  Developers are able
to use the MATERIALIZED keyword as an "optimization fence" to more tightly
control the behavior of the SQLite query planner.  SQLite copied the idea of
using MATERIALIZED as an optimization fence from PostgreSQL.


If the NOT MATERIALIZED phrase is used, then select-stmt
is substituted as a subquery in place of every occurrence of the CTE
table name.  Optimizations such as flattening and
push-down are then applied to the subquery as if
the subquery had by used in directly.  In spite of its name, the NOT MATERIALIZED
phrase does not prohibit the use of materialization.  The query planner
is still free to implement the subquery using materialization if
it feels that is the best solution.  The true meaning of NOT MATERIALIZED
is closer to "TREAT LIKE ANY ORDINARY VIEW OR SUBQUERY".  


If neither hint is present, then SQLite is free to choose whatever
implementation strategy it thinks will work best.  This is the recommended
approach.  Do not use the MATERIALIZED or NOT MATERIALIZED keywords on
a common table expression unless you have a compelling reason to do so.


The MATERIALIZED and NOT MATERIALIZED hints are only available in
SQLite version 3.35.0 (2021-03-12) and later.

5. 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.

This page last modified on  2024-01-29 11:00:27 UTC


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.

  The RETURNING clause is not supported for 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.
This means that if there is a RETURNING clause, the rows returned by
the statement probably will not be in the order specified by the
ORDER BY clause.



4. The Truncate Optimization

When the WHERE clause and RETURNING clause are both  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.
This page last modified on  2022-01-08 05:02:57 UTC


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 enabled 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.
This page last modified on  2023-12-05 14:43:20 UTC


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 causes 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.
This page last modified on  2023-03-14 14:31:07 UTC


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
these alterations of an existing table:
it can be renamed;
a column can be renamed;
a column can be added to it;
or
a column can be dropped from it.



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 being 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 summarizes 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.


When adding a column with a CHECK constraint, or a NOT NULL constraint
on a generated column, the added constraints are tested against all 
preexisting rows in the table and the ADD COLUMN fails
if any constraint fails.  The testing of added constraints
against preexisting rows is a new enhancement as of SQLite version
3.37.0 (2021-11-27).

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 for renames or column addition without
constraints.
Because of this,
the execution time of such ALTER TABLE commands is independent of
the amount of data in the table and such commands will 
run as quickly on a table with 10 million rows as on a table with 1 row.
When adding new columns that have CHECK constraints, or adding generated
columns with NOT NULL constraints, or when deleting columns, then all
existing data in the table must be either read (to test new constraints
against existing rows) or written (to remove deleted columns).  In those
cases, the ALTER TABLE command takes time that is proportional to the
amount of content in the table being altered.


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. ALTER TABLE DROP COLUMN

 The DROP COLUMN syntax
is used to remove an existing column from a table.
The DROP COLUMN command removes the named column from the table,
and rewrites its content to purge the data associated
with that column.
The DROP COLUMN command only works if the column is not referenced
by any other parts of the schema and is not a PRIMARY KEY and
does not have a UNIQUE constraint.
Possible reasons why the DROP COLUMN command can fail include:

The column is a PRIMARY KEY or part of one.
The column has a UNIQUE constraint.
The column is indexed.
The column is named in the WHERE clause of a partial index.
The column is named in a table or column CHECK constraint
not associated with the column being dropped.
The column is used in a foreign key constraint.
The column is used in the expression of a generated column.
The column appears in a trigger or view.


5.1. How It Works

SQLite stores the schema as plain text in the sqlite_schema table.
The DROP COLUMN command (and all of the other variations of ALTER TABLE
as well) modify that text and then attempt to reparse the entire schema.
The command is only successful if the schema is still valid after the
text has been modified.  In the case of the DROP COLUMN command, the
only text modified is that the column definition is removed from the
CREATE TABLE statement.  The DROP COLUMN command will fail if there
are any traces of the column in other parts of the schema that will
prevent the schema from parsing after the CREATE TABLE statement has
been modified.

6. Disable Error Checking Using PRAGMA writable_schema=ON

ALTER TABLE will normally fail and make no changes if it encounters
any entries in the sqlite_schema table that do not parse.  For
example, if there is a malformed VIEW or TRIGGER associated with
table named "tbl1", then an attempt to rename "tbl1" to "tbl1neo" will
fail because the associated views and triggers could not be parsed.

Beginning with SQLite 3.38.0 (2022-02-22), this error checking
can be disabled by setting "PRAGMA writable_schema=ON;".  When
the schema is writable, ALTER TABLE silently ignores any rows of the
sqlite_schema table that do not parse.



7. Making Other Kinds Of Table Schema Changes

 The only schema altering commands directly supported by SQLite are the
"rename table", "rename column", "add column", "drop 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.



8. 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.




This page last modified on  2022-08-10 18:45:48 UTC


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



 
 


 
 



 
 


 
 




 
 



 
 


 
 



 
 




 
 



 
 


 
 



 
 



 
 


 
 



 
 




 
 



 
 



 
 



 
 


 
 





 
 


 
 







2. Operators, and Parse-Affecting Attributes
SQLite understands these operators, listed in precedence1 order
(top to bottom / highest to lowest):


  



  
    Operators&nbsp;2
  
  
    ~&nbsp;&lsqb;expr&rsqb;&nbsp;&nbsp;&nbsp;&nbsp;+&nbsp;&lsqb;expr&rsqb;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&lsqb;expr&rsqb;
  
  
    &lsqb;expr&rsqb;&nbsp;COLLATE&nbsp;&lpar;collation-name&rpar;&nbsp;3
  
  
    ||&nbsp;&nbsp;&nbsp;-&gt;&nbsp;&nbsp;&nbsp;-&gt;&gt;
  
  
    *&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;%
  
  
    +&nbsp;&nbsp;&nbsp;-
  
  
    &amp;&ensp;&nbsp;|&nbsp;&nbsp;&nbsp;&lt;&lt;&ensp;&nbsp;&gt;&gt;
  
  
    &lsqb;expr&rsqb;&nbsp;ESCAPE&nbsp;&lsqb;escape-character-expr&rsqb;&nbsp;4
  
  
    &lt;&nbsp;&nbsp;&gt;&nbsp;&nbsp;&lt;=&nbsp;&nbsp;&gt;=
  
  
    =&nbsp;&nbsp;==&nbsp;&nbsp;&lt;&gt;&nbsp;&nbsp;!=&nbsp;&nbsp;IS&nbsp;&nbsp;&nbsp;IS&nbsp;NOT
      IS&nbsp;DISTINCT&nbsp;FROM&nbsp;&nbsp;&nbsp;IS&nbsp;NOT&nbsp;DISTINCT&nbsp;FROM
      &lsqb;expr&rsqb;&nbsp;BETWEEN5&nbsp;&lsqb;expr&rsqb;&nbsp;AND&nbsp;&lsqb;expr&rsqb;&ensp;
      IN5&nbsp;&nbsp;MATCH5&nbsp;&nbsp;LIKE5&nbsp;&nbsp;REGEXP5&nbsp;&nbsp;GLOB5
      &lsqb;expr&rsqb;&nbsp;ISNULL&nbsp;&nbsp;&lsqb;expr&rsqb;&nbsp;NOTNULL&nbsp;&nbsp;&nbsp;&lsqb;expr&rsqb;&nbsp;NOT&nbsp;NULL
    
  
  
    NOT&nbsp;&lsqb;expr&rsqb;
  
  
    AND
  
  
    OR
  



 Operators shown within the same table cell share precedence.
 "&lsqb;expr&rsqb;" denotes operand locations for non-binary operators.
 &nbsp;&nbsp;Operators with no "&lsqb;expr&rsqb;" adjunct are binary and left-associative. 
 The COLLATE clause (with its collation-name) acts as a single postfix operator.
 The ESCAPE clause (with its escape character) acts as a single postfix operator.
 &nbsp;&nbsp;It can only bind to a preceding &lsqb;expr&rsqb; LIKE &lsqb;expr&rsqb; expression.
 Each keyword in (BETWEEN IN GLOB LIKE MATCH REGEXP) may be prefixed
 &nbsp;&nbsp;by NOT, retaining the bare operator's precedence and associativity.





The COLLATE operator is a unary postfix
operator that assigns a collating sequence to an expression.
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 not-equal operator can be either
!= or &lt;&gt;.
The || operator is "concatenate" - it joins together
the two strings of its operands.
The -&gt; and -&gt;&gt; operators are "extract";
they extract the RHS component from the LHS.
For an example, see
JSON subcomponent extraction.



The % operator casts both of its operands to type
INTEGER and then computes the remainder after dividing the left integer
by the right integer. The other arithmetic operators perform integer
arithmetic if both operands are integers and no overflow would result,
or floating point arithmetic, per IEEE Standard 754, if either operand
is a real value or integer arithmetic would produce an overflow.
Integer divide yields an integer result, truncated toward zero.


The result of any binary operator is either a numeric value or
NULL, except for the || concatenation operator,
and the -&gt; and -&gt;&gt; extract operators
which evaluate to either NULL or a text value.

All operators generally evaluate to NULL when any operand is NULL,
with specific exceptions as stated below. This is in accordance with
the SQL92 standard.

 When paired with NULL:
&nbsp;&nbsp;AND evaluates to 0 (false) when
the other operand is false; and
&nbsp;&nbsp;OR evaluates to 1 (true)
when the other operand is true.






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.





The IS NOT DISTINCT FROM operator is an alternative spelling
for the IS operator.
Likewise, the IS DISTINCT FROM operator means the same thing
as IS NOT.  Standard SQL does not support the compact IS and IS NOT
notation.  Those compact forms are an SQLite extension.  You have to use
the prolix and much less readable IS NOT DISTINCT FROM and
IS DISTINCT FROM operators on other SQL database engines.



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 it 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, MATCH, and extract 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.



The extract operators act as a special syntax for functions
"-&gt;"() and "-&gt;&gt;"(). Default implementations for these functions
perform JSON subcomponent extraction,
but extensions can override them for other purposes.



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.



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 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 an operand of a comparison operator or as
the value in an UPDATE SET clause whose column name list has the same size.



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 the IS operator
evaluates the left-hand operand as a boolean value and returns an appropriate
answer.



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,
math 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 and the ORDER BY clause 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.
This page last modified on  2024-02-27 20:24:47 UTC


c2: Built-In Mathematical SQL Functions
c5: lang_mathfunc.html
c4:
1. Overview

The math functions shown below are a subgroup of
scalar functions that are built into the
SQLite amalgamation source file but are only active
if the amalgamation is compiled using the
-DSQLITE_ENABLE_MATH_FUNCTIONS compile-time option.

The arguments to math functions can be integers, floating-point numbers,
or strings or blobs that look like integers or real numbers.  If any argument
is NULL or is a string or blob that is not readily converted into a number,
then the function will return NULL.
These functions also return NULL for domain errors, such as trying to
take the square root of a negative number, or compute the arccosine of a
value greater than 1.0 or less than -1.0.

The values returned by these functions are often approximations.
For example, the pi() function returns 
3.141592653589793115997963468544185161590576171875 which 
is about 1.22465e-16 too small, but it is the closest approximation available
for IEEE754 doubles.




acos(X)
acosh(X)
asin(X)
asinh(X)
atan(X)
atan2(Y,X)
atanh(X)
ceil(X)
ceiling(X)
cos(X)
cosh(X)
degrees(X)
exp(X)
floor(X)
ln(X)
log(B,X)
log(X)
log10(X)
log2(X)
mod(X,Y)
pi()
pow(X,Y)
power(X,Y)
radians(X)
sin(X)
sinh(X)
sqrt(X)
tan(X)
tanh(X)
trunc(X)




2. Descriptions of built-in scalar SQL math functions



acos(X)
  Return the arccosine of X.  The result is in radians.


acosh(X)
  Return the hyperbolic arccosine of X.


asin(X)
  Return the arcsine of X.  The result is in radians.


asinh(X)
  Return the hyperbolic arcsine of X.


atan(X)
  Return the arctangent of X.  The result is in radians.


atan2(Y,X)
  Return the arctangent of Y/X.  The result is in radians.  The
  result is placed into correct quadrant depending on the signs
  of X and Y.


atanh(X)
  Return the hyperbolic arctangent of X.


ceil(X)ceiling(X)
  Return the first representable integer value greater than or equal to X.
  For positive values of X, this routine rounds away from zero.
  For negative values of X, this routine rounds toward zero.


cos(X)
  Return the cosine of X.  X is in radians.


cosh(X)
  Return the hyperbolic cosine of X.


degrees(X)
  Convert value X from radians into degrees.


exp(X)
  Compute e (Euler's number, approximately 2.71828182845905) raised
  to the power X.


floor(X)
  Return the first representable integer value less than or equal to X.
  For positive numbers, this function rounds toward zero.
  For negative numbers, this function rounds away from zero.


ln(X)
  Return the natural logarithm of X.


log(X)log10(X)log(B,X)
  Return the base-10 logarithm for X.  Or, for the two-argument version,
  return the base-B logarithm of X.
  
  Compatibility note:  SQLite works like PostgreSQL in that the log() function
  computes a base-10 logarithm.  Most other SQL database engines compute a
  natural logarithm for log().  In the two-argument version of log(B,X), the
  first argument is the base and the second argument is the operand.  This is
  the same as in PostgreSQL and MySQL, but is reversed from SQL Server which
  uses the second argument as the base and the first argument as the operand.


log2(X)
  Return the logarithm base-2 for the number X.


mod(X,Y)
  Return the remainder after dividing X by Y.  This is similar to the '%'
  operator, except that it works for non-integer arguments.


pi()
  Return an approximation for &pi;.


pow(X,Y)power(X,Y)
  Compute X raised to the power Y.


radians(X)
  Convert X from degrees into radians.


sin(X)
  Return the sine of X.  X is in radians.


sinh(X)
  Return the hyperbolic sine of X.


sqrt(X)
  Return the square root of X.  NULL is returned if X is negative.


tan(X)
  Return the tangent of X.  X is in radians.


tanh(X)
  Return the hyperbolic tangent of X.


trunc(X)
  Return the representable integer in between X and 0 (inclusive)
  that is furthest away from zero.  Or, in other words, return the
  integer part of X, rounding toward zero.
  The trunc() function is similar to ceiling(X) and floor(X) except
  that it always rounds toward zero whereas ceiling(X) and floor(X) round
  up and down, respectively.



This page last modified on  2023-12-05 14:43:20 UTC


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.
 The application must not dereference the arrays or string pointers
passed as the 3rd and 4th callback parameters after it returns.

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() upgrades the database file lock.  In other words, xLock() moves the
database file lock in the direction NONE toward EXCLUSIVE. The argument to
xLock() is always on of SHARED, RESERVED, PENDING, or EXCLUSIVE, never
SQLITE_LOCK_NONE.  If the database file lock is already at or above the
requested lock, then the call to xLock() is a no-op.
xUnlock() downgrades the database file lock to either SHARED or NONE.
to xUnlock() is a no-op.
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.


c2: C API: Mutexes
c5: c3ref/mutex_alloc.html
c0:
sqlite3_mutex_alloc(), sqlite3_mutex_free(), sqlite3_mutex_enter(), sqlite3_mutex_try(), sqlite3_mutex_leave()

c4:
The SQLite core uses these routines for thread
synchronization. Though they are intended for internal
use by SQLite, code that links against SQLite is
permitted to use any of these routines.

The SQLite source code contains multiple implementations
of these mutex routines.  An appropriate implementation
is selected automatically at compile-time.  The following
implementations are available in the SQLite core:


   SQLITE_MUTEX_PTHREADS
   SQLITE_MUTEX_W32
   SQLITE_MUTEX_NOOP


The SQLITE_MUTEX_NOOP implementation is a set of routines
that does no real locking and is appropriate for use in
a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
and Windows.

If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
implementation is included with the library. In this case the
application must supply a custom mutex implementation using the
SQLITE_CONFIG_MUTEX option of the sqlite3_config() function
before calling sqlite3_initialize() or any other public sqlite3_
function that calls sqlite3_initialize().

The sqlite3_mutex_alloc() routine allocates a new
mutex and returns a pointer to it. The sqlite3_mutex_alloc()
routine returns NULL if it is unable to allocate the requested
mutex.  The argument to sqlite3_mutex_alloc() must one of these
integer constants:


  SQLITE_MUTEX_FAST
  SQLITE_MUTEX_RECURSIVE
  SQLITE_MUTEX_STATIC_MAIN
  SQLITE_MUTEX_STATIC_MEM
  SQLITE_MUTEX_STATIC_OPEN
  SQLITE_MUTEX_STATIC_PRNG
  SQLITE_MUTEX_STATIC_LRU
  SQLITE_MUTEX_STATIC_PMEM
  SQLITE_MUTEX_STATIC_APP1
  SQLITE_MUTEX_STATIC_APP2
  SQLITE_MUTEX_STATIC_APP3
  SQLITE_MUTEX_STATIC_VFS1
  SQLITE_MUTEX_STATIC_VFS2
  SQLITE_MUTEX_STATIC_VFS3


The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
cause sqlite3_mutex_alloc() to create
a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
is used but not necessarily so when SQLITE_MUTEX_FAST is used.
The mutex implementation does not need to make a distinction
between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
not want to.  SQLite will only request a recursive mutex in
cases where it really needs one.  If a faster non-recursive mutex
implementation is available on the host platform, the mutex subsystem
might return such a mutex in response to SQLITE_MUTEX_FAST.

The other allowed parameters to sqlite3_mutex_alloc() (anything other
than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
a pointer to a static preexisting mutex.  Nine static mutexes are
used by the current version of SQLite.  Future versions of SQLite
may add additional static mutexes.  Static mutexes are for internal
use by SQLite only.  Applications that use SQLite mutexes should
use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
SQLITE_MUTEX_RECURSIVE.

Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
returns a different mutex on every call.  For the static
mutex types, the same mutex is returned on every call that has
the same type number.

The sqlite3_mutex_free() routine deallocates a previously
allocated dynamic mutex.  Attempting to deallocate a static
mutex results in undefined behavior.

The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
to enter a mutex.  If another thread is already within the mutex,
sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
upon successful entry.  Mutexes created using
SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
In such cases, the
mutex must be exited an equal number of times before another thread
can enter.  If the same thread tries to enter any mutex other
than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.

Some systems (for example, Windows 95) do not support the operation
implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
will always return SQLITE_BUSY. In most cases the SQLite core only uses
sqlite3_mutex_try() as an optimization, so this is acceptable
behavior. The exceptions are unix builds that set the
SQLITE_ENABLE_SETLK_TIMEOUT build option. In that case a working
sqlite3_mutex_try() is required.

The sqlite3_mutex_leave() routine exits a mutex that was
previously entered by the same thread.   The behavior
is undefined if the mutex is not currently entered by the
calling thread or is not currently allocated.

If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(),
sqlite3_mutex_leave(), or sqlite3_mutex_free() is a NULL pointer,
then any of the four routines behaves as a no-op.

See also: sqlite3_mutex_held() and sqlite3_mutex_notheld().
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
allocation 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_clear_bindings()
c2: C API: Reset All Bindings On A Prepared Statement
c5: c3ref/clear_bindings.html
c4:
Contrary to the intuition of many, sqlite3_reset() does not reset
the bindings on a prepared statement.
Use this routine to reset all host parameters to NULL.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_changes(), sqlite3_changes64()
c2: C API: Count The Number Of Rows Modified
c5: c3ref/changes.html
c4:
These functions return 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.
The two functions are identical except for the type of the return value
and that if the number of rows modified by the most recent INSERT, UPDATE
or DELETE is greater than the maximum value supported by type "int", then
the return value of sqlite3_changes() is undefined. Executing any other
type of SQL statement does not modify the value returned by these functions.

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_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_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_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_stmt_status()
c2: C API: Prepared Statement Status
c5: c3ref/stmt_status.html
c4:
Each prepared statement maintains various
SQLITE_STMTSTATUS counters that measure the number
of times it has performed specific operations.  These counters can
be used to monitor the performance characteristics of the prepared
statements.  For example, if the number of table steps greatly exceeds
the number of table searches or result rows, that would tend to indicate
that the prepared statement is using a full table scan rather than
an index.

This interface is used to retrieve and reset counter values from
a prepared statement.  The first argument is the prepared statement
object to be interrogated.  The second argument
is an integer code for a specific SQLITE_STMTSTATUS counter
to be interrogated.
The current value of the requested counter is returned.
If the resetFlg is true, then the counter is reset to zero after this
interface call returns.

See also: sqlite3_status() and sqlite3_db_status().
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.


c2: C API: Checkpoint Mode Values
c5: c3ref/c_checkpoint_full.html
c0:
SQLITE_CHECKPOINT_PASSIVE, SQLITE_CHECKPOINT_FULL, SQLITE_CHECKPOINT_RESTART, SQLITE_CHECKPOINT_TRUNCATE

c4:
These constants define all valid values for the "checkpoint mode" passed
as the third parameter to the sqlite3_wal_checkpoint_v2() interface.
See the sqlite3_wal_checkpoint_v2() documentation for details on the
meaning of each of these checkpoint modes.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_db_readonly()
c2: C API: Determine if a database is read-only
c5: c3ref/db_readonly.html
c4:
The sqlite3_db_readonly(D,N) interface returns 1 if the database N
of connection D is read-only, 0 if it is read/write, or -1 if N is not
the name of a database on connection D.
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.


c2: C API: Source Of Data In A Query Result
c5: c3ref/column_database_name.html
c0:
sqlite3_column_database_name(), sqlite3_column_database_name16(), sqlite3_column_table_name(), sqlite3_column_table_name16(), sqlite3_column_origin_name(), sqlite3_column_origin_name16()

c4:
These routines provide a means to determine the database, table, and
table column that is the origin of a particular result column in
SELECT statement.
The name of the database or table or column can be returned as
either a UTF-8 or UTF-16 string.  The _database_ routines return
the database name, the _table_ routines return the table name, and
the origin_ routines return the column name.
The returned string is valid until the prepared statement is destroyed
using sqlite3_finalize() or until the statement is automatically
reprepared by the first call to sqlite3_step() for a particular run
or until the same information is requested
again in a different encoding.

The names returned are the original un-aliased names of the
database, table, and column.

The first argument to these interfaces is a prepared statement.
These functions return information about the Nth result column returned by
the statement, where N is the second function argument.
The left-most column is column 0 for these routines.

If the Nth column returned by the statement is an expression or
subquery and is not a column value, then all of these functions return
NULL.  These routines might also return NULL if a memory allocation error
occurs.  Otherwise, they return the name of the attached database, table,
or column that query result column was extracted from.

As with all other SQLite APIs, those whose names end with "16" return
UTF-16 encoded strings and the other functions return UTF-8.

These APIs are only available if the library was compiled with the
SQLITE_ENABLE_COLUMN_METADATA C-preprocessor symbol.

If two or more threads call one or more
column metadata interfaces
for the same prepared statement and result column
at the same time then the results are undefined.
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. If V is a pointer value, then the result
of sqlite3_value_dup(V) is a NULL value.

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_snapshot_free()
c2: C API: Destroy a snapshot
c5: c3ref/snapshot_free.html
c4:
The sqlite3_snapshot_free(P) interface destroys sqlite3_snapshot P.
The application must eventually free every sqlite3_snapshot object
using this routine to avoid a memory leak.

The sqlite3_snapshot_free() interface is only available when the
SQLITE_ENABLE_SNAPSHOT compile-time option is used.
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_user_data()
c2: C API: User Data For Functions
c5: c3ref/user_data.html
c4:
The sqlite3_user_data() interface returns a copy of
the pointer that was the pUserData parameter (the 5th parameter)
of the sqlite3_create_function()
and sqlite3_create_function16() routines that originally
registered the application defined function.

This routine must be called from the same thread in which
the application-defined function is running.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Extended Result Codes
c5: c3ref/c_abort_rollback.html
c0:
SQLITE_ERROR_MISSING_COLLSEQ, SQLITE_ERROR_RETRY, SQLITE_ERROR_SNAPSHOT, SQLITE_IOERR_READ, SQLITE_IOERR_SHORT_READ, SQLITE_IOERR_WRITE, SQLITE_IOERR_FSYNC, SQLITE_IOERR_DIR_FSYNC, SQLITE_IOERR_TRUNCATE, SQLITE_IOERR_FSTAT, SQLITE_IOERR_UNLOCK, SQLITE_IOERR_RDLOCK, SQLITE_IOERR_DELETE, SQLITE_IOERR_BLOCKED, SQLITE_IOERR_NOMEM, SQLITE_IOERR_ACCESS, SQLITE_IOERR_CHECKRESERVEDLOCK, SQLITE_IOERR_LOCK, SQLITE_IOERR_CLOSE, SQLITE_IOERR_DIR_CLOSE, SQLITE_IOERR_SHMOPEN, SQLITE_IOERR_SHMSIZE, SQLITE_IOERR_SHMLOCK, SQLITE_IOERR_SHMMAP, SQLITE_IOERR_SEEK, SQLITE_IOERR_DELETE_NOENT, SQLITE_IOERR_MMAP, SQLITE_IOERR_GETTEMPPATH, SQLITE_IOERR_CONVPATH, SQLITE_IOERR_VNODE, SQLITE_IOERR_AUTH, SQLITE_IOERR_BEGIN_ATOMIC, SQLITE_IOERR_COMMIT_ATOMIC, SQLITE_IOERR_ROLLBACK_ATOMIC, SQLITE_IOERR_DATA, SQLITE_IOERR_CORRUPTFS, SQLITE_IOERR_IN_PAGE, SQLITE_LOCKED_SHAREDCACHE, SQLITE_LOCKED_VTAB, SQLITE_BUSY_RECOVERY, SQLITE_BUSY_SNAPSHOT, SQLITE_BUSY_TIMEOUT, SQLITE_CANTOPEN_NOTEMPDIR, SQLITE_CANTOPEN_ISDIR, SQLITE_CANTOPEN_FULLPATH, SQLITE_CANTOPEN_CONVPATH, SQLITE_CANTOPEN_DIRTYWAL, SQLITE_CANTOPEN_SYMLINK, SQLITE_CORRUPT_VTAB, SQLITE_CORRUPT_SEQUENCE, SQLITE_CORRUPT_INDEX, SQLITE_READONLY_RECOVERY, SQLITE_READONLY_CANTLOCK, SQLITE_READONLY_ROLLBACK, SQLITE_READONLY_DBMOVED, SQLITE_READONLY_CANTINIT, SQLITE_READONLY_DIRECTORY, SQLITE_ABORT_ROLLBACK, SQLITE_CONSTRAINT_CHECK, SQLITE_CONSTRAINT_COMMITHOOK, SQLITE_CONSTRAINT_FOREIGNKEY, SQLITE_CONSTRAINT_FUNCTION, SQLITE_CONSTRAINT_NOTNULL, SQLITE_CONSTRAINT_PRIMARYKEY, SQLITE_CONSTRAINT_TRIGGER, SQLITE_CONSTRAINT_UNIQUE, SQLITE_CONSTRAINT_VTAB, SQLITE_CONSTRAINT_ROWID, SQLITE_CONSTRAINT_PINNED, SQLITE_CONSTRAINT_DATATYPE, SQLITE_NOTICE_RECOVER_WAL, SQLITE_NOTICE_RECOVER_ROLLBACK, SQLITE_NOTICE_RBU, SQLITE_WARNING_AUTOINDEX, SQLITE_AUTH_USER, SQLITE_OK_LOAD_PERMANENTLY, SQLITE_OK_SYMLINK

c4:
In its default configuration, SQLite API routines return one of 30 integer
result codes.  However, experience has shown that many of
these result codes are too coarse-grained.  They do not provide as
much information about problems as programmers might like.  In an effort to
address this, newer versions of SQLite (version 3.3.8 2006-10-09
and later) include
support for additional result codes that provide more detailed information
about errors. These extended result codes are enabled or disabled
on a per database connection basis using the
sqlite3_extended_result_codes() API.  Or, the extended code for
the most recent error can be obtained using
sqlite3_extended_errcode().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_keyword_count(), sqlite3_keyword_name(), sqlite3_keyword_check()
c2: C API: SQL Keyword Checking
c5: c3ref/keyword_check.html
c4:
These routines provide access to the set of SQL language keywords
recognized by SQLite.  Applications can uses these routines to determine
whether or not a specific identifier needs to be escaped (for example,
by enclosing in double-quotes) so as not to confuse the parser.

The sqlite3_keyword_count() interface returns the number of distinct
keywords understood by SQLite.

The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
makes *Z point to that keyword expressed as UTF8 and writes the number
of bytes in the keyword into *L.  The string that *Z points to is not
zero-terminated.  The sqlite3_keyword_name(N,Z,L) routine returns
SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
or L are NULL or invalid pointers then calls to
sqlite3_keyword_name(N,Z,L) result in undefined behavior.

The sqlite3_keyword_check(Z,L) interface checks to see whether or not
the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
if it is and zero if not.

The parser used by SQLite is forgiving.  It is often possible to use
a keyword as an identifier as long as such use does not result in a
parsing ambiguity.  For example, the statement
"CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
creates a new table named "BEGIN" with three columns named
"REPLACE", "PRAGMA", and "END".  Nevertheless, best practice is to avoid
using keywords as identifiers.  Common techniques used to avoid keyword
name collisions include:

 Put all identifier names inside double-quotes.  This is the official
SQL way to escape identifier names.
 Put identifier names inside &#91;...&#93;.  This is not standard SQL,
but it is what SQL Server does and so lots of programmers use this
technique.
 Begin every identifier with the letter "Z" as no SQL keywords start
with "Z".
 Include a digit somewhere in every identifier name.


Note that the number of keywords understood by SQLite can depend on
compile-time options.  For example, "VACUUM" is not a keyword if
SQLite is compiled with the -DSQLITE_OMIT_VACUUM option.  Also,
new keywords may be added to future releases of SQLite.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Introduction
c5: c3ref/intro.html
c4:
C-language Interface Specification for SQLite


These pages are intended to be precise and detailed specification.
For a tutorial introduction, see instead:

SQLite In 5 Minutes Or Less and/or
the Introduction To The SQLite C/C++ Interface.

This same content is also available as a
single large HTML file.


The SQLite interface elements can be grouped into three categories:


List Of Objects.
    This is a list of all abstract objects and datatypes used by the
    SQLite library.  There are couple dozen objects in total, but
    the two most important objects are:
    A database connection object sqlite3, and the
    prepared statement object sqlite3_stmt.

List Of Constants.
    This is a list of numeric constants used by SQLite and represented by
    #defines in the sqlite3.h header file.  These constants
    are things such as numeric result codes from
    various interfaces (ex: SQLITE_OK) or flags passed
    into functions to control behavior
    (ex: SQLITE_OPEN_READONLY).

List Of Functions.
    This is a list of all functions and methods operating on the
    objects and using and/or
    returning constants.  There
    are many functions, but most applications only use a handful.


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: sqlite3_blob_open()
c2: C API: Open A BLOB For Incremental I/O
c5: c3ref/blob_open.html
c4:
This interfaces opens a handle to the BLOB located
in row iRow, column zColumn, table zTable in database zDb;
in other words, the same BLOB that would be selected by:


SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;


Parameter zDb is not the filename that contains the database, but
rather the symbolic name of the database. For attached databases, this is
the name that appears after the AS keyword in the ATTACH statement.
For the main database file, the database name is "main". For TEMP
tables, the database name is "temp".

If the flags parameter is non-zero, then the BLOB is opened for read
and write access. If the flags parameter is zero, the BLOB is opened for
read-only access.

On success, SQLITE_OK is returned and the new BLOB handle is stored
in *ppBlob. Otherwise an error code is returned and, unless the error
code is SQLITE_MISUSE, *ppBlob is set to NULL. This means that, provided
the API is not misused, it is always safe to call sqlite3_blob_close()
on *ppBlob after this function it returns.

This function fails with SQLITE_ERROR if any of the following are true:

 Database zDb does not exist,
 Table zTable does not exist within database zDb,
 Table zTable is a WITHOUT ROWID table,
 Column zColumn does not exist,
 Row iRow is not present in the table,
 The specified column of row iRow contains a value that is not
a TEXT or BLOB value,
 Column zColumn is part of an index, PRIMARY KEY or UNIQUE
constraint and the blob is being opened for read/write access,
 Foreign key constraints are enabled,
column zColumn is part of a child key definition and the blob is
being opened for read/write access.


Unless it returns SQLITE_MISUSE, this function sets the
database connection error code and message accessible via
sqlite3_errcode() and sqlite3_errmsg() and related functions.

A BLOB referenced by sqlite3_blob_open() may be read using the
sqlite3_blob_read() interface and modified by using
sqlite3_blob_write().  The BLOB handle can be moved to a
different row of the same table using the sqlite3_blob_reopen()
interface.  However, the column, table, or database of a BLOB handle
cannot be changed after the BLOB handle is opened.

If the row that a BLOB handle points to is modified by an
UPDATE, DELETE, or by ON CONFLICT side-effects
then the BLOB handle is marked as "expired".
This is true if any column of the row is changed, even a column
other than the one the BLOB handle is open on.
Calls to sqlite3_blob_read() and sqlite3_blob_write() for
an expired BLOB handle fail with a return code of SQLITE_ABORT.
Changes written into a BLOB prior to the BLOB expiring are not
rolled back by the expiration of the BLOB.  Such changes will eventually
commit if the transaction continues to completion.

Use the sqlite3_blob_bytes() interface to determine the size of
the opened blob.  The size of a blob may not be changed by this
interface.  Use the UPDATE SQL command to change the size of a
blob.

The sqlite3_bind_zeroblob() and sqlite3_result_zeroblob() interfaces
and the built-in zeroblob SQL function may be used to create a
zero-filled blob to read or write using the incremental-blob interface.

To avoid a resource leak, every open BLOB handle should eventually
be released by a call to sqlite3_blob_close().

See also: sqlite3_blob_close(),
sqlite3_blob_reopen(), sqlite3_blob_read(),
sqlite3_blob_bytes(), sqlite3_blob_write().
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_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.

This interface is omitted if SQLite is compiled with
-DSQLITE_OMIT_SHARED_CACHE.  The -DSQLITE_OMIT_SHARED_CACHE
compile-time option is recommended because the
use of shared cache mode is discouraged.

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_wal_autocheckpoint()
c2: C API: Configure an auto-checkpoint
c5: c3ref/wal_autocheckpoint.html
c4:
The sqlite3_wal_autocheckpoint(D,N) is a wrapper around
sqlite3_wal_hook() that causes any database on database connection D
to automatically checkpoint
after committing a transaction if there are N or
more frames in the write-ahead log file.  Passing zero or
a negative value as the nFrame parameter disables automatic
checkpoints entirely.

The callback registered by this function replaces any existing callback
registered using sqlite3_wal_hook().  Likewise, registering a callback
using sqlite3_wal_hook() disables the automatic checkpoint mechanism
configured by this function.

The wal_autocheckpoint pragma can be used to invoke this interface
from SQL.

Checkpoints initiated by this mechanism are
PASSIVE.

Every new database connection defaults to having the auto-checkpoint
enabled with a threshold of 1000 or SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
pages.  The use of this interface
is only necessary if the default setting is found to be suboptimal
for a particular application.
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: sqlite3_bind_parameter_name()
c2: C API: Name Of A Host Parameter
c5: c3ref/bind_parameter_name.html
c4:
The sqlite3_bind_parameter_name(P,N) interface returns
the name of the N-th SQL parameter in the prepared statement P.
SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
respectively.
In other words, the initial ":" or "$" or "@" or "?"
is included as part of the name.
Parameters of the form "?" without a following integer have no name
and are referred to as "nameless" or "anonymous parameters".

The first host parameter has an index of 1, not 0.

If the value N is out of range or if the N-th parameter is
nameless, then NULL is returned.  The returned string is
always in UTF-8 encoding even if the named parameter was
originally specified as UTF-16 in sqlite3_prepare16(),
sqlite3_prepare16_v2(), or sqlite3_prepare16_v3().

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


c0: sqlite3_interrupt(), sqlite3_is_interrupted()
c2: C API: Interrupt A Long-Running Query
c5: c3ref/interrupt.html
c4:
This function causes any pending database operation to abort and
return at its earliest opportunity. This routine is typically
called in response to a user action such as pressing "Cancel"
or Ctrl-C where the user wants a long query operation to halt
immediately.

It is safe to call this routine from a thread different from the
thread that is currently running the database operation.  But it
is not safe to call this routine with a database connection that
is closed or might close before sqlite3_interrupt() returns.

If an SQL operation is very nearly finished at the time when
sqlite3_interrupt() is called, then it might not have an opportunity
to be interrupted and might continue to completion.

An SQL operation that is interrupted will return SQLITE_INTERRUPT.
If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
that is inside an explicit transaction, then the entire transaction
will be rolled back automatically.

The sqlite3_interrupt(D) call is in effect until all currently running
SQL statements on database connection D complete.  Any new SQL statements
that are started after the sqlite3_interrupt() call and before the
running statement count reaches zero are interrupted as if they had been
running prior to the sqlite3_interrupt() call.  New SQL statements
that are started after the running statement count reaches zero are
not effected by the sqlite3_interrupt().
A call to sqlite3_interrupt(D) that occurs when there are no running
SQL statements is a no-op and has no effect on SQL statements
that are started after the sqlite3_interrupt() call returns.

The sqlite3_is_interrupted(D) interface can be used to determine whether
or not an interrupt is currently in effect for database connection D.
It returns 1 if an interrupt is currently in effect, or 0 otherwise.
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: sqlite3_vtab_nochange()
c2: C API: Determine If Virtual Table Column Access Is For UPDATE
c5: c3ref/vtab_nochange.html
c4:
If the sqlite3_vtab_nochange(X) routine is called within the xColumn
method of a virtual table, then it might return true if the
column is being fetched as part of an UPDATE operation during which the
column value will not change.  The virtual table implementation can use
this hint as permission to substitute a return value that is less
expensive to compute and that the corresponding
xUpdate method understands as a "no-change" value.

If the xColumn method calls sqlite3_vtab_nochange() and finds that
the column is not changed by the UPDATE statement, then the xColumn
method can optionally return without setting a result, without calling
any of the sqlite3_result_xxxxx() interfaces.
In that case, sqlite3_value_nochange(X) will return true for the
same column in the xUpdate method.

The sqlite3_vtab_nochange() routine is an optimization.  Virtual table
implementations should continue to give a correct answer even if the
sqlite3_vtab_nochange() interface were to always return false.  In the
current implementation, the sqlite3_vtab_nochange() interface does always
returns false for the enhanced UPDATE FROM statement.
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_column_name(), sqlite3_column_name16()
c2: C API: Column Names In A Result Set
c5: c3ref/column_name.html
c4:
These routines return the name assigned to a particular column
in the result set of a SELECT statement.  The sqlite3_column_name()
interface returns a pointer to a zero-terminated UTF-8 string
and sqlite3_column_name16() returns a pointer to a zero-terminated
UTF-16 string.  The first parameter is the prepared statement
that implements the SELECT statement. The second parameter is the
column number.  The leftmost column is number 0.

The returned string pointer is valid until either the prepared statement
is destroyed by sqlite3_finalize() or until the statement is automatically
reprepared by the first call to sqlite3_step() for a particular run
or until the next call to
sqlite3_column_name() or sqlite3_column_name16() on the same column.

If sqlite3_malloc() fails during the processing of either routine
(for example during a conversion from UTF-8 to UTF-16) then a
NULL pointer is returned.

The name of a result column is the value of the "AS" clause for
that column, if there is an AS clause.  If there is no AS clause
then the name of the column is unspecified and may change from
one release of SQLite to the next.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_vtab_on_conflict()
c2: C API: Determine The Virtual Table Conflict Policy
c5: c3ref/vtab_on_conflict.html
c4:
This function may only be called from within a call to the xUpdate method
of a virtual table implementation for an INSERT or UPDATE operation. The
value returned is one of SQLITE_ROLLBACK, SQLITE_IGNORE, SQLITE_FAIL,
SQLITE_ABORT, or SQLITE_REPLACE, according to the ON CONFLICT mode
of the SQL statement that triggered the call to the xUpdate method of the
virtual table.
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: 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_strglob()
c2: C API: String Globbing
c5: c3ref/strglob.html
c4:
The sqlite3_strglob(P,X) interface returns zero if and only if
string X matches the GLOB pattern P.
The definition of GLOB pattern matching used in
sqlite3_strglob(P,X) is the same as for the "X GLOB P" operator in the
SQL dialect understood by SQLite.  The sqlite3_strglob(P,X) function
is case sensitive.

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_strlike().
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: File Locking Levels
c5: c3ref/c_lock_exclusive.html
c0:
SQLITE_LOCK_NONE, SQLITE_LOCK_SHARED, SQLITE_LOCK_RESERVED, SQLITE_LOCK_PENDING, SQLITE_LOCK_EXCLUSIVE

c4:
SQLite uses one of these integer values as the second
argument to calls it makes to the xLock() and xUnlock() methods
of an sqlite3_io_methods object.  These values are ordered from
lest restrictive to most restrictive.

The argument to xLock() is always SHARED or higher.  The argument to
xUnlock is either SHARED or NONE.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_db_config()
c2: C API: Configure database connections
c5: c3ref/db_config.html
c4:
The sqlite3_db_config() interface is used to make configuration
changes to a database connection.  The interface is similar to
sqlite3_config() except that the changes apply to a single
database connection (specified in the first argument).

The second argument to sqlite3_db_config(D,V,...)  is the
configuration verb - an integer code
that indicates what aspect of the database connection is being configured.
Subsequent arguments vary depending on the configuration verb.

Calls to sqlite3_db_config() return SQLITE_OK if and only if
the call is considered successful.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_database_file_object()
c2: C API: Database File Corresponding To A Journal
c5: c3ref/database_file_object.html
c4:
If X is the name of a rollback or WAL-mode journal file that is
passed into the xOpen method of sqlite3_vfs, then
sqlite3_database_file_object(X) returns a pointer to the sqlite3_file
object that represents the main database file.

This routine is intended for use in custom VFS implementations
only.  It is not a general-purpose interface.
The argument sqlite3_file_object(X) must be a filename pointer that
has been passed into sqlite3_vfs.xOpen method where the
flags parameter to xOpen contains one of the bits
SQLITE_OPEN_MAIN_JOURNAL or SQLITE_OPEN_WAL.  Any other use
of this routine results in undefined and probably undesirable
behavior.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Flags For File Open Operations
c5: c3ref/c_open_autoproxy.html
c0:
sqlite3_open_v2(), SQLITE_OPEN_READONLY, SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_DELETEONCLOSE, SQLITE_OPEN_EXCLUSIVE, SQLITE_OPEN_AUTOPROXY, SQLITE_OPEN_URI, SQLITE_OPEN_MEMORY, SQLITE_OPEN_MAIN_DB, SQLITE_OPEN_TEMP_DB, SQLITE_OPEN_TRANSIENT_DB, SQLITE_OPEN_MAIN_JOURNAL, SQLITE_OPEN_TEMP_JOURNAL, SQLITE_OPEN_SUBJOURNAL, SQLITE_OPEN_SUPER_JOURNAL, SQLITE_OPEN_NOMUTEX, SQLITE_OPEN_FULLMUTEX, SQLITE_OPEN_SHAREDCACHE, SQLITE_OPEN_PRIVATECACHE, SQLITE_OPEN_WAL, SQLITE_OPEN_NOFOLLOW, SQLITE_OPEN_EXRESCODE

c4:
These bit values are intended for use in the
3rd parameter to the sqlite3_open_v2() interface and
in the 4th parameter to the sqlite3_vfs.xOpen method.

Only those flags marked as "Ok for sqlite3_open_v2()" may be
used as the third argument to the sqlite3_open_v2() interface.
The other flags have historically been ignored by sqlite3_open_v2(),
though future versions of SQLite might change so that an error is
raised if any of the disallowed bits are passed into sqlite3_open_v2().
Applications should not depend on the historical behavior.

Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into
sqlite3_open_v2() does *not* cause the underlying database file
to be opened using O_EXCL.  Passing SQLITE_OPEN_EXCLUSIVE into
sqlite3_open_v2() has historically be a no-op and might become an
error in future versions of SQLite.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_ACCESS_EXISTS, SQLITE_ACCESS_READWRITE, SQLITE_ACCESS_READ
c2: C API: Flags for the xAccess VFS method
c5: c3ref/c_access_exists.html
c4:
These integer constants can be used as the third parameter to
the xAccess method of an sqlite3_vfs object.  They determine
what kind of permissions the xAccess method is looking for.
With SQLITE_ACCESS_EXISTS, the xAccess method
simply checks whether the file exists.
With SQLITE_ACCESS_READWRITE, the xAccess method
checks whether the named directory is both readable and writable
(in other words, if files can be added, removed, and renamed within
the directory).
The SQLITE_ACCESS_READWRITE constant is currently used only by the
temp_store_directory pragma, though this could change in a future
release of SQLite.
With SQLITE_ACCESS_READ, the xAccess method
checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
currently unused, though it might be used in a future release of
SQLite.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_close(), sqlite3_close_v2()
c2: C API: Closing A Database Connection
c5: c3ref/close.html
c4:
The sqlite3_close() and sqlite3_close_v2() routines are destructors
for the sqlite3 object.
Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
the sqlite3 object is successfully destroyed and all associated
resources are deallocated.

Ideally, applications should finalize all
prepared statements, close all BLOB handles, and
finish all sqlite3_backup objects associated
with the sqlite3 object prior to attempting to close the object.
If the database connection is associated with unfinalized prepared
statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
sqlite3_close() will leave the database connection open and return
SQLITE_BUSY. If sqlite3_close_v2() is called with unfinalized prepared
statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
it returns SQLITE_OK regardless, but instead of deallocating the database
connection immediately, it marks the database connection as an unusable
"zombie" and makes arrangements to automatically deallocate the database
connection after all prepared statements are finalized, all BLOB handles
are closed, and all backups have finished. The sqlite3_close_v2() interface
is intended for use with host languages that are garbage collected, and
where the order in which destructors are called is arbitrary.

If an sqlite3 object is destroyed while a transaction is open,
the transaction is automatically rolled back.

The C parameter to sqlite3_close(C) and sqlite3_close_v2(C)
must be either a NULL
pointer or an sqlite3 object pointer obtained
from sqlite3_open(), sqlite3_open16(), or
sqlite3_open_v2(), and not previously closed.
Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
argument is a harmless no-op.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Device Characteristics
c5: c3ref/c_iocap_atomic.html
c0:
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

c4:
The xDeviceCharacteristics method of the sqlite3_io_methods
object returns an integer which is a vector of these
bit values expressing I/O characteristics of the mass storage
device that holds the file that the sqlite3_io_methods
refers to.

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().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
after reboot following a crash or power loss, the only bytes in a
file that were written at the application level might have changed
and that adjacent bytes, even bytes within the same sector are
guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
flag indicates that a file cannot be deleted when open.  The
SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
read-only media and cannot be changed even by processes with
elevated privileges.

The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
filesystem supports doing multiple write operations atomically when those
write operations are bracketed by SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and
SQLITE_FCNTL_COMMIT_ATOMIC_WRITE.
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_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: sqlite3_sleep()
c2: C API: Suspend Execution For A Short Time
c5: c3ref/sleep.html
c4:
The sqlite3_sleep() function causes the current thread to suspend execution
for at least a number of milliseconds specified in its parameter.

If the operating system does not support sleep requests with
millisecond time resolution, then the time will be rounded up to
the nearest second. The number of milliseconds of sleep actually
requested from the operating system is returned.

SQLite implements this interface by calling the xSleep()
method of the default sqlite3_vfs object.  If the xSleep() method
of the default VFS is not implemented correctly, or not implemented at
all, then the behavior of sqlite3_sleep() may deviate from the description
in the previous paragraphs.

If a negative argument is passed to sqlite3_sleep() the results vary by
VFS and operating system.  Some system treat a negative argument as an
instruction to sleep forever.  Others understand it to mean do not sleep
at all. In SQLite version 3.42.0 and later, a negative
argument passed into sqlite3_sleep() is changed to zero before it is relayed
down into the xSleep method of the VFS.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_db_filename()
c2: C API: Return The Filename For A Database Connection
c5: c3ref/db_filename.html
c4:
The sqlite3_db_filename(D,N) interface returns a pointer to the filename
associated with database N of connection D.
If there is no attached database N on the database
connection D, or if database N is a temporary or in-memory database, then
this function will return either a NULL pointer or an empty string.

The string value returned by this routine is owned and managed by
the database connection.  The value will be valid until the database N
is DETACH-ed or until the database connection closes.

The filename returned by this function is the output of the
xFullPathname method of the VFS.  In other words, the filename
will be an absolute pathname, even if the filename used
to open the database originally was a URI or relative pathname.

If the filename pointer returned by this routine is not NULL, then it
can be used as the filename input parameter to these routines:

 sqlite3_uri_parameter()
 sqlite3_uri_boolean()
 sqlite3_uri_int64()
 sqlite3_filename_database()
 sqlite3_filename_journal()
 sqlite3_filename_wal()

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 created 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_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: struct sqlite3_snapshot
c2: C API: Database Snapshot
c5: c3ref/snapshot.html
c4:
An instance of the snapshot object records the state of a WAL mode
database for some specific point in history.

In WAL mode, multiple database connections that are open on the
same database file can each be reading a different historical version
of the database file.  When a database connection begins a read
transaction, that connection sees an unchanging copy of the database
as it existed for the point in time when the transaction first started.
Subsequent changes to the database from other connections are not seen
by the reader until a new read transaction is started.

The sqlite3_snapshot object records state information about an historical
version of the database file so that it is possible to later open a new read
transaction that sees that historical version of the database rather than
the most recent version.
1 Constructor using this object: sqlite3_snapshot_get()
1 Destructor using this object: sqlite3_snapshot_free()
3 Methods using this object:
 sqlite3_snapshot_cmp(),
sqlite3_snapshot_open(),
sqlite3_snapshot_recover()
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_blob_bytes()
c2: C API: Return The Size Of An Open BLOB
c5: c3ref/blob_bytes.html
c4:
Returns the size in bytes of the BLOB accessible via the
successfully opened BLOB handle in its only argument.  The
incremental blob I/O routines can only read or overwriting existing
blob content; they cannot change the size of a blob.

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 lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_get_autocommit()
c2: C API: Test For Auto-Commit Mode
c5: c3ref/get_autocommit.html
c4:
The sqlite3_get_autocommit() interface returns non-zero or
zero if the given database connection is or is not in autocommit mode,
respectively.  Autocommit mode is on by default.
Autocommit mode is disabled by a BEGIN statement.
Autocommit mode is re-enabled by a COMMIT or ROLLBACK.

If certain kinds of errors occur on a statement within a multi-statement
transaction (errors including SQLITE_FULL, SQLITE_IOERR,
SQLITE_NOMEM, SQLITE_BUSY, and SQLITE_INTERRUPT) then the
transaction might be rolled back automatically.  The only way to
find out whether SQLite automatically rolled back the transaction after
an error is to use this function.

If another thread changes the autocommit status of the database
connection while this routine is running, then the return value
is undefined.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_result_subtype()
c2: C API: Setting The Subtype Of An SQL Function
c5: c3ref/result_subtype.html
c4:
The sqlite3_result_subtype(C,T) function causes the subtype of
the result from the application-defined SQL function with
sqlite3_context C to be the value T.  Only the lower 8 bits
of the subtype T are preserved in current versions of SQLite;
higher order bits are discarded.
The number of subtype bytes preserved by SQLite might increase
in future releases of SQLite.

Every application-defined SQL function that invokes this interface
should include the SQLITE_RESULT_SUBTYPE property in its
text encoding argument when the SQL function is
registered.  If the SQLITE_RESULT_SUBTYPE
property is omitted from the function that invokes sqlite3_result_subtype(),
then in some cases the sqlite3_result_subtype() might fail to set
the result subtype.

If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any
SQL function that invokes the sqlite3_result_subtype() interface
and that does not have the SQLITE_RESULT_SUBTYPE property will raise
an error.  Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1
by default.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_load_extension()
c2: C API: Load An Extension
c5: c3ref/load_extension.html
c4:
This interface loads an SQLite extension library from the named file.

The sqlite3_load_extension() interface attempts to load an
SQLite extension library contained in the file zFile.  If
the file cannot be loaded directly, attempts are made to load
with various operating-system specific extensions added.
So for example, if "samplelib" cannot be loaded, then names like
"samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
be tried also.

The entry point is zProc.
zProc may be 0, in which case SQLite will try to come up with an
entry point name on its own.  It first tries "sqlite3_extension_init".
If that does not work, it constructs a name "sqlite3_X_init" where the
X is consists of the lower-case equivalent of all ASCII alphabetic
characters in the filename from the last "/" to the first following
"." and omitting any initial "lib".
The sqlite3_load_extension() interface returns
SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
If an error occurs and pzErrMsg is not 0, then the
sqlite3_load_extension() interface shall attempt to
fill *pzErrMsg with error message text stored in memory
obtained from sqlite3_malloc(). The calling function
should free this memory by calling sqlite3_free().

Extension loading must be enabled using
sqlite3_enable_load_extension() or
sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,1,NULL)
prior to calling this API,
otherwise an error will be returned.

Security warning: It is recommended that the
SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION method be used to enable only this
interface.  The use of the sqlite3_enable_load_extension() interface
should be avoided.  This will keep the SQL function load_extension()
disabled and prevent SQL injections from giving attackers
access to extension loading capabilities.

See also the load_extension() SQL function.
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: SQLITE_DESERIALIZE_FREEONCLOSE, SQLITE_DESERIALIZE_RESIZEABLE, SQLITE_DESERIALIZE_READONLY
c2: C API: Flags for sqlite3_deserialize()
c5: c3ref/c_deserialize_freeonclose.html
c4:
The following are allowed values for 6th argument (the F argument) to
the sqlite3_deserialize(D,S,P,N,M,F) interface.

The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
in the P argument is held in memory obtained from sqlite3_malloc64()
and that SQLite should take ownership of this memory and automatically
free it when it has finished using it.  Without this flag, the caller
is responsible for freeing any dynamically allocated memory.

The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
grow the size of the database using calls to sqlite3_realloc64().  This
flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
Without this flag, the deserialized database cannot increase in size beyond
the number of bytes specified by the M parameter.

The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
should be treated as read-only.
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.


c0: sqlite3_autovacuum_pages()
c2: C API: Autovacuum Compaction Amount Callback
c5: c3ref/autovacuum_pages.html
c4:
The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback
function C that is invoked prior to each autovacuum of the database
file.  The callback is passed a copy of the generic data pointer (P),
the schema-name of the attached database that is being autovacuumed,
the size of the database file in pages, the number of free pages,
and the number of bytes per page, respectively.  The callback should
return the number of free pages that should be removed by the
autovacuum.  If the callback returns zero, then no autovacuum happens.
If the value returned is greater than or equal to the number of
free pages, then a complete autovacuum happens.

If there are multiple ATTACH-ed database files that are being
modified as part of a transaction commit, then the autovacuum pages
callback is invoked separately for each file.

The callback is not reentrant. The callback function should
not attempt to invoke any other SQLite interface.  If it does, bad
things may happen, including segmentation faults and corrupt database
files.  The callback function should be a simple function that
does some arithmetic on its input parameters and returns a result.

The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
destructor for the P parameter.  If X is not NULL, then X(P) is
invoked whenever the database connection closes or when the callback
is overwritten by another invocation of sqlite3_autovacuum_pages().

There is only one autovacuum pages callback per database connection.
Each call to the sqlite3_autovacuum_pages() interface overrides all
previous invocations for that database connection.  If the callback
argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer,
then the autovacuum steps callback is canceled.  The return value
from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might
be some other error code if something goes wrong.  The current
implementation will only return SQLITE_OK or SQLITE_MISUSE, but other
return codes might be added in future releases.

If no autovacuum pages callback is specified (the usual case) or
a NULL pointer is provided for the callback,
then the default behavior is to vacuum all free pages.  So, in other
words, the default behavior is the same as if the callback function
were something like this:


See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: File Name
c5: c3ref/filename.html
c4:
Type sqlite3_filename is used by SQLite to pass filenames to the
xOpen method of a VFS. It may be cast to (const char*) and treated
as a normal, nul-terminated, UTF-8 buffer containing the filename, but
may also be passed to special APIs such as:


  sqlite3_filename_database()
  sqlite3_filename_journal()
  sqlite3_filename_wal()
  sqlite3_uri_parameter()
  sqlite3_uri_boolean()
  sqlite3_uri_int64()
  sqlite3_uri_key()

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: 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.

Strings returned by sqlite3_column_text16() always have the endianness
which is native to the platform, regardless of the text encoding set
for the database.

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.

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: sqlite3_db_cacheflush()
c2: C API: Flush caches to disk mid-transaction
c5: c3ref/db_cacheflush.html
c4:
If a write-transaction is open on database connection D when the
sqlite3_db_cacheflush(D) interface invoked, any dirty
pages in the pager-cache that are not currently in use are written out
to disk. A dirty page may be in use if a database cursor created by an
active SQL statement is reading from it, or if it is page 1 of a database
file (page 1 is always "in use").  The sqlite3_db_cacheflush(D)
interface flushes caches for all schemas - "main", "temp", and
any attached databases.

If this function needs to obtain extra database locks before dirty pages
can be flushed to disk, it does so. If those locks cannot be obtained
immediately and there is a busy-handler callback configured, it is invoked
in the usual manner. If the required lock still cannot be obtained, then
the database is skipped and an attempt made to flush any dirty pages
belonging to the next (if any) database. If any databases are skipped
because locks cannot be obtained, but no other error occurs, this
function returns SQLITE_BUSY.

If any other error occurs while flushing dirty pages to disk (for
example an IO error or out-of-memory condition), then processing is
abandoned and an SQLite error code is returned to the caller immediately.

Otherwise, if no error occurs, sqlite3_db_cacheflush() returns SQLITE_OK.

This function does not set the database handle error code or message
returned by the sqlite3_errcode() and sqlite3_errmsg() functions.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_threadsafe()
c2: C API: Test To See If The Library Is Threadsafe
c5: c3ref/threadsafe.html
c4:
The sqlite3_threadsafe() function returns zero if and only if
SQLite was compiled with mutexing code omitted due to the
SQLITE_THREADSAFE compile-time option being set to 0.

SQLite can be compiled with or without mutexes.  When
the SQLITE_THREADSAFE C preprocessor macro is 1 or 2, mutexes
are enabled and SQLite is threadsafe.  When the
SQLITE_THREADSAFE macro is 0,
the mutexes are omitted.  Without the mutexes, it is not safe
to use SQLite concurrently from more than one thread.

Enabling mutexes incurs a measurable performance penalty.
So if speed is of utmost importance, it makes sense to disable
the mutexes.  But for maximum safety, mutexes should be enabled.
The default behavior is for mutexes to be enabled.

This interface can be used by an application to make sure that the
version of SQLite that it is linking against was compiled with
the desired setting of the SQLITE_THREADSAFE macro.

This interface only reports on the compile-time mutex setting
of the SQLITE_THREADSAFE flag.  If SQLite is compiled with
SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
can be fully or partially disabled using a call to sqlite3_config()
with the verbs SQLITE_CONFIG_SINGLETHREAD, SQLITE_CONFIG_MULTITHREAD,
or SQLITE_CONFIG_SERIALIZED.  The return value of the
sqlite3_threadsafe() function shows only the compile-time setting of
thread safety, not any run-time changes to that setting made by
sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
is unchanged by calls to sqlite3_config().

See the threading mode documentation for additional information.
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.


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_drop_modules()
c2: C API: Remove Unnecessary Virtual Table Implementations
c5: c3ref/drop_modules.html
c4:
The sqlite3_drop_modules(D,L) interface removes all virtual
table modules from database connection D except those named on list L.
The L parameter must be either NULL or a pointer to an array of pointers
to strings where the array is terminated by a single NULL pointer.
If the L parameter is NULL, then all virtual table modules are removed.

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


c0: sqlite3_db_status()
c2: C API: Database Connection Status
c5: c3ref/db_status.html
c4:
This interface is used to retrieve runtime status information
about a single database connection.  The first argument is the
database connection object to be interrogated.  The second argument
is an integer constant, taken from the set of
SQLITE_DBSTATUS options, that
determines the parameter to interrogate.  The set of
SQLITE_DBSTATUS options is likely
to grow in future releases of SQLite.

The current value of the requested parameter is written into *pCur
and the highest instantaneous value is written into *pHiwtr.  If
the resetFlg is true, then the highest instantaneous value is
reset back down to the current value.

The sqlite3_db_status() routine returns SQLITE_OK on success and a
non-zero error code on failure.

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


c0: SQLITE_SYNC_NORMAL, SQLITE_SYNC_FULL, SQLITE_SYNC_DATAONLY
c2: C API: Synchronization Type Flags
c5: c3ref/c_sync_dataonly.html
c4:
When SQLite invokes the xSync() method of an
sqlite3_io_methods object it uses a combination of
these integer values as the second argument.

When the SQLITE_SYNC_DATAONLY flag is used, it means that the
sync operation only needs to flush data to mass storage.  Inode
information need not be flushed. If the lower four bits of the flag
equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
If the lower four bits equal SQLITE_SYNC_FULL, that means
to use Mac OS X style fullsync instead of fsync().

Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
with the PRAGMA synchronous=NORMAL and PRAGMA synchronous=FULL
settings.  The synchronous pragma determines when calls to the
xSync VFS method occur and applies uniformly across all platforms.
The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
energetic or rigorous or forceful the sync operations are and
only make a difference on Mac OSX for the default SQLite code.
(Third-party VFS implementations might also make the distinction
between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
operating systems natively supported by SQLite, only Mac OSX
cares about the difference.)
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Result Codes
c5: c3ref/c_abort.html
c0:
sqlite3_file_control(), sqlite3_log(), sqlite3_step(), SQLITE_OK, SQLITE_ERROR, SQLITE_INTERNAL, SQLITE_PERM, SQLITE_BUSY, SQLITE_LOCKED, SQLITE_NOMEM, SQLITE_READONLY, SQLITE_INTERRUPT, SQLITE_IOERR, SQLITE_CORRUPT, SQLITE_NOTFOUND, SQLITE_FULL, SQLITE_CANTOPEN, SQLITE_PROTOCOL, SQLITE_EMPTY, SQLITE_SCHEMA, SQLITE_TOOBIG, SQLITE_CONSTRAINT, SQLITE_MISMATCH, SQLITE_MISUSE, SQLITE_NOLFS, SQLITE_AUTH, SQLITE_FORMAT, SQLITE_RANGE, SQLITE_NOTADB, SQLITE_NOTICE, SQLITE_WARNING, SQLITE_ROW, SQLITE_DONE

c4:
Many SQLite functions return an integer result code from the set shown
here in order to indicate success or failure.

New error codes may be added in future versions of SQLite.

See also: extended result code definitions
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_reset()
c2: C API: Reset A Prepared Statement Object
c5: c3ref/reset.html
c4:
The sqlite3_reset() function is called to reset a prepared statement
object back to its initial state, ready to be re-executed.
Any SQL statement variables that had values bound to them using
the sqlite3_bind_*() API retain their values.
Use sqlite3_clear_bindings() to reset the bindings.

The sqlite3_reset(S) interface resets the prepared statement S
back to the beginning of its program.

The return code from sqlite3_reset(S) indicates whether or not
the previous evaluation of prepared statement S completed successfully.
If sqlite3_step(S) has never before been called on S or if
sqlite3_step(S) has not been called since the previous call
to sqlite3_reset(S), then sqlite3_reset(S) will return
SQLITE_OK.

If the most recent call to sqlite3_step(S) for the
prepared statement S indicated an error, then
sqlite3_reset(S) returns an appropriate error code.
The sqlite3_reset(S) interface might also return an error code
if there were no prior errors but the process of resetting
the prepared statement caused a new error. For example, if an
INSERT statement with a RETURNING clause is only stepped one time,
that one call to sqlite3_step(S) might return SQLITE_ROW but
the overall statement might still fail and the sqlite3_reset(S) call
might return SQLITE_BUSY if locking constraints prevent the
database change from committing.  Therefore, it is important that
applications check the return code from sqlite3_reset(S) even if
no prior call to sqlite3_step(S) indicated a problem.

The sqlite3_reset(S) interface does not change the values
of any bindings on the prepared statement S.
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: sqlite3_declare_vtab()
c2: C API: Declare The Schema Of A Virtual Table
c5: c3ref/declare_vtab.html
c4:
The xCreate and xConnect methods of a
virtual table module call this interface
to declare the format (the names and datatypes of the columns) of
the virtual tables they implement.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_TXN_NONE, SQLITE_TXN_READ, SQLITE_TXN_WRITE
c2: C API: Allowed return values from sqlite3_txn_state()
c5: c3ref/c_txn_none.html
c4:
These constants define the current transaction state of a database file.
The sqlite3_txn_state(D,S) interface returns one of these
constants in order to describe the transaction state of schema S
in database connection D.



 SQLITE_TXN_NONE
The SQLITE_TXN_NONE state means that no transaction is currently
pending.


 SQLITE_TXN_READ
The SQLITE_TXN_READ state means that the database is currently
in a read transaction.  Content has been read from the database file
but nothing in the database file has changed.  The transaction state
will advanced to SQLITE_TXN_WRITE if any changes occur and there are
no other conflicting concurrent write transactions.  The transaction
state will revert to SQLITE_TXN_NONE following a ROLLBACK or
COMMIT.


 SQLITE_TXN_WRITE
The SQLITE_TXN_WRITE state means that the database is currently
in a write transaction.  Content has been written to the database file
but has not yet committed.  The transaction state will change to
to SQLITE_TXN_NONE at the next ROLLBACK or COMMIT.
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.


c0: sqlite3_blob_write()
c2: C API: Write Data Into A BLOB Incrementally
c5: c3ref/blob_write.html
c4:
This function is used to write data into an open BLOB handle from a
caller-supplied buffer. N bytes of data are copied from the buffer Z
into the open BLOB, starting at offset iOffset.

On success, sqlite3_blob_write() returns SQLITE_OK.
Otherwise, an  error code or an extended error code is returned.
Unless SQLITE_MISUSE is returned, this function sets the
database connection error code and message accessible via
sqlite3_errcode() and sqlite3_errmsg() and related functions.

If the BLOB handle passed as the first argument was not opened for
writing (the flags parameter to sqlite3_blob_open() was zero),
this function returns SQLITE_READONLY.

This function may only modify the contents of the BLOB; it is
not possible to increase the size of a BLOB using this API.
If offset iOffset is less than N bytes from the end of the BLOB,
SQLITE_ERROR is returned and no data is written. The size of the
BLOB (and hence the maximum value of N+iOffset) can be determined
using the sqlite3_blob_bytes() interface. If N or iOffset are less
than zero SQLITE_ERROR is returned and no data is written.

An attempt to write to an expired BLOB handle fails with an
error code of SQLITE_ABORT.  Writes to the BLOB that occurred
before the BLOB handle expired are not rolled back by the
expiration of the handle, though of course those changes might
have been overwritten by the statement that expired the BLOB handle
or by other independent statements.

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_read().
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Error Logging Interface
c5: c3ref/log.html
c4:
The sqlite3_log() interface writes a message into the error log
established by the SQLITE_CONFIG_LOG option to sqlite3_config().
If logging is enabled, the zFormat string and subsequent arguments are
used with sqlite3_snprintf() to generate the final output string.

The sqlite3_log() interface is intended for use by extensions such as
virtual tables, collating functions, and SQL functions.  While there is
nothing to prevent an application from calling sqlite3_log(), doing so
is considered bad form.

The zFormat string must not be NULL.

To avoid deadlocks and other threading problems, the sqlite3_log() routine
will not use dynamically allocated memory.  The log message is stored in
a fixed-length buffer on the stack.  If the log message is longer than
a few hundred characters, it will be truncated to the length of the
buffer.
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: sqlite3_next_stmt()
c2: C API: Find the next prepared statement
c5: c3ref/next_stmt.html
c4:
This interface returns a pointer to the next prepared statement after
pStmt associated with the database connection pDb.  If pStmt is NULL
then this interface returns a pointer to the first prepared statement
associated with the database connection pDb.  If no prepared statement
satisfies the conditions of this routine, it returns NULL.

The database connection pointer D in a call to
sqlite3_next_stmt(D,S) must refer to an open database
connection and in particular must not be a NULL pointer.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: SQLITE_SERIALIZE_NOCOPY
c2: C API: Flags for sqlite3_serialize
c5: c3ref/c_serialize_nocopy.html
c4:
Zero or more of the following constants can be OR-ed together for
the F argument to sqlite3_serialize(D,S,P,F).

SQLITE_SERIALIZE_NOCOPY means that sqlite3_serialize() will return
a pointer to contiguous in-memory database that it is currently using,
without making a copy of the database.  If SQLite is not currently using
a contiguous in-memory database, then this option causes
sqlite3_serialize() to return a NULL pointer.  SQLite will only be
using a contiguous in-memory database if it has been initialized by a
prior call to sqlite3_deserialize().
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_vtab_distinct()
c2: C API: Determine if a virtual table query is DISTINCT
c5: c3ref/vtab_distinct.html
c4:
This API may only be used from within an xBestIndex method
of a virtual table implementation. The result of calling this
interface from outside of xBestIndex() is undefined and probably harmful.

The sqlite3_vtab_distinct() interface returns an integer between 0 and
3.  The integer returned by sqlite3_vtab_distinct()
gives the virtual table additional information about how the query
planner wants the output to be ordered. As long as the virtual table
can meet the ordering requirements of the query planner, it may set
the "orderByConsumed" flag.


If the sqlite3_vtab_distinct() interface returns 0, that means
that the query planner needs the virtual table to return all rows in the
sort order defined by the "nOrderBy" and "aOrderBy" fields of the
sqlite3_index_info object.  This is the default expectation.  If the
virtual table outputs all rows in sorted order, then it is always safe for
the xBestIndex method to set the "orderByConsumed" flag, regardless of
the return value from sqlite3_vtab_distinct().

If the sqlite3_vtab_distinct() interface returns 1, that means
that the query planner does not need the rows to be returned in sorted order
as long as all rows with the same values in all columns identified by the
"aOrderBy" field are adjacent.  This mode is used when the query planner
is doing a GROUP BY.

If the sqlite3_vtab_distinct() interface returns 2, that means
that the query planner does not need the rows returned in any particular
order, as long as rows with the same values in all "aOrderBy" columns
are adjacent.  Furthermore, only a single row for each particular
combination of values in the columns identified by the "aOrderBy" field
needs to be returned.  It is always ok for two or more rows with the same
values in all "aOrderBy" columns to be returned, as long as all such rows
are adjacent.  The virtual table may, if it chooses, omit extra rows
that have the same value for all columns identified by "aOrderBy".
However omitting the extra rows is optional.
This mode is used for a DISTINCT query.

If the sqlite3_vtab_distinct() interface returns 3, that means
that the query planner needs only distinct rows but it does need the
rows to be sorted. The virtual table implementation is free to omit
rows that are identical in all aOrderBy columns, if it wants to, but
it is not required to omit any rows.  This mode is used for queries
that have both DISTINCT and ORDER BY clauses.


For the purposes of comparing virtual table output values to see if the
values are same value for sorting purposes, two NULL values are considered
to be the same.  In other words, the comparison operator is "IS"
(or "IS NOT DISTINCT FROM") and not "==".

If a virtual table implementation is unable to meet the requirements
specified above, then it must not set the "orderByConsumed" flag in the
sqlite3_index_info object or an incorrect answer may result.

A virtual table implementation is always free to return rows in any order
it wants, as long as the "orderByConsumed" flag is not set.  When the
the "orderByConsumed" flag is unset, the query planner will add extra
bytecode to ensure that the final results returned by the SQL query are
ordered correctly.  The use of the "orderByConsumed" flag and the
sqlite3_vtab_distinct() interface is merely an optimization.  Careful
use of the sqlite3_vtab_distinct() interface and the "orderByConsumed"
flag might help queries against a virtual table to run faster.  Being
overly aggressive and setting the "orderByConsumed" flag when it is not
valid to do so, on the other hand, might cause SQLite to return incorrect
results.
See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_complete(), sqlite3_complete16()
c2: C API: Determine If An SQL Statement Is Complete
c5: c3ref/complete.html
c4:
These routines are useful during command-line input to determine if the
currently entered text seems to form a complete SQL statement or
if additional input is needed before sending the text into
SQLite for parsing.  These routines return 1 if the input string
appears to be a complete SQL statement.  A statement is judged to be
complete if it ends with a semicolon token and is not a prefix of a
well-formed CREATE TRIGGER statement.  Semicolons that are embedded within
string literals or quoted identifier names or comments are not
independent tokens (they are part of the token in which they are
embedded) and thus do not count as a statement terminator.  Whitespace
and comments that follow the final semicolon are ignored.

These routines return 0 if the statement is incomplete.  If a
memory allocation fails, then SQLITE_NOMEM is returned.

These routines do not parse the SQL statements thus
will not detect syntactically incorrect SQL.

If SQLite has not been initialized using sqlite3_initialize() prior
to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
automatically by sqlite3_complete16().  If that initialization fails,
then the return value from sqlite3_complete16() will be non-zero
regardless of whether or not the input SQL is complete.

The input to sqlite3_complete() must be a zero-terminated
UTF-8 string.

The input to sqlite3_complete16() must be a zero-terminated
UTF-16 string in native byte order.
See also lists of
  Objects,
  Constants, and
  Functions.


c2: C API: Status Parameters for prepared statements
c5: c3ref/c_stmtstatus_counter.html
c0:
SQLITE_STMTSTATUS_FULLSCAN_STEP, SQLITE_STMTSTATUS_SORT, SQLITE_STMTSTATUS_AUTOINDEX, SQLITE_STMTSTATUS_VM_STEP, SQLITE_STMTSTATUS_REPREPARE, SQLITE_STMTSTATUS_RUN, SQLITE_STMTSTATUS_FILTER_MISS, SQLITE_STMTSTATUS_FILTER_HIT, SQLITE_STMTSTATUS_MEMUSED

c4:
These preprocessor macros define integer codes that name counter
values associated with the sqlite3_stmt_status() interface.
The meanings of the various counters are as follows:



 SQLITE_STMTSTATUS_FULLSCAN_STEP
This is the number of times that SQLite has stepped forward in
a table as part of a full table scan.  Large numbers for this counter
may indicate opportunities for performance improvement through
careful use of indices.


 SQLITE_STMTSTATUS_SORT
This is the number of sort operations that have occurred.
A non-zero value in this counter may indicate an opportunity to
improvement performance through careful use of indices.


 SQLITE_STMTSTATUS_AUTOINDEX
This is the number of rows inserted into transient indices that
were created automatically in order to help joins run faster.
A non-zero value in this counter may indicate an opportunity to
improvement performance by adding permanent indices that do not
need to be reinitialized each time the statement is run.


 SQLITE_STMTSTATUS_VM_STEP
This is the number of virtual machine operations executed
by the prepared statement if that number is less than or equal
to 2147483647.  The number of virtual machine operations can be
used as a proxy for the total work done by the prepared statement.
If the number of virtual machine operations exceeds 2147483647
then the value returned by this statement status code is undefined.


 SQLITE_STMTSTATUS_REPREPARE
This is the number of times that the prepare statement has been
automatically regenerated due to schema changes or changes to
bound parameters that might affect the query plan.


 SQLITE_STMTSTATUS_RUN
This is the number of times that the prepared statement has
been run.  A single "run" for the purposes of this counter is one
or more calls to sqlite3_step() followed by a call to sqlite3_reset().
The counter is incremented on the first sqlite3_step() call of each
cycle.





SQLITE_STMTSTATUS_FILTER_HIT
SQLITE_STMTSTATUS_FILTER_MISS
SQLITE_STMTSTATUS_FILTER_HIT is the number of times that a join
step was bypassed because a Bloom filter returned not-found.  The
corresponding SQLITE_STMTSTATUS_FILTER_MISS value is the number of
times that the Bloom filter returned a find, and thus the join step
had to be processed as normal.


 SQLITE_STMTSTATUS_MEMUSED
This is the approximate number of bytes of heap memory
used to store the prepared statement.  This value is not actually
a counter, and so the resetFlg parameter to sqlite3_stmt_status()
is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.


See also lists of
  Objects,
  Constants, and
  Functions.


c0: sqlite3_snapshot_cmp()
c2: C API: Compare the ages of two snapshot handles.
c5: c3ref/snapshot_cmp.html
c4:
The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
of two valid snapshot handles.

If the two snapshot handles are not associated with the same database
file, the result of the comparison is undefined.

Additionally, the result of the comparison is only valid if both of the
snapshot handles were obtained by calling sqlite3_snapshot_get() since the
last time the wal file was deleted. The wal file is deleted when the
database is changed back to rollback mode or when the number of database
clients drops to zero. If either snapshot handle was obtained before the
wal file was last deleted, the value returned by this function
is undefined.

Otherwise, this API returns a negative value if P1 refers to an older
snapshot than P2, zero if the two handles refer to the same database
snapshot, and a positive value if P1 is a newer snapshot than P2.

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_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 behavior. 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_limit()
c2: C API: Run-time Limits
c5: c3ref/limit.html
c4:
This interface allows the size of various constructs to be limited
on a connection by connection basis.  The first parameter is the
database connection whose limit is to be set or queried.  The
second parameter is one of the limit categories that define a
class of constructs to be size limited.  The third parameter is the
new limit for that construct.

If the new limit is a negative number, the limit is unchanged.
For each limit category SQLITE_LIMIT_NAME there is a
hard upper bound
set at compile-time by a C preprocessor macro called
SQLITE_MAX_NAME.
(The "_LIMIT_" in the name is changed to "_MAX_".)
Attempts to increase a limit above its hard upper bound are
silently truncated to the hard upper bound.

Regardless of whether or not the limit was changed, the
sqlite3_limit() interface returns the prior value of the limit.
Hence, to find the current value of a limit without changing it,
simply invoke this interface with the third parameter set to -1.

Run-time limits are intended for use in applications that manage
both their own internal database and also databases that are controlled
by untrusted external sources.  An example application might be a
web browser that has its own databases for storing history and
separate databases controlled by JavaScript applications downloaded
off the Internet.  The internal databases can be given the
large, default limits.  Databases managed by external sources can
be given much smaller limits designed to prevent a denial of service
attack.  Developers might also want to use the sqlite3_set_authorizer()
interface to further control untrusted SQL.  The size of the database
created by an untrusted script can be contained using the
max_page_count PRAGMA.

New run-time limit categories may be added in future releases.
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().

6 Constructors using this object:


sqlite3_prepare
sqlite3_prepare16
sqlite3_prepare16_v2
sqlite3_prepare16_v3
sqlite3_prepare_v2
sqlite3_prepare_v3



1 Destructor using this object: sqlite3_finalize()
53 Methods using this object:


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_explain
sqlite3_stmt_isexplain
sqlite3_stmt_readonly
sqlite3_stmt_scanstatus
sqlite3_stmt_scanstatus_reset
sqlite3_stmt_scanstatus_v2
sqlite3_stmt_status



See also lists of
  Objects,
  Constants, and
  Functions.


