ADDED Doc/Extra/Core/images/sqlite370_banner.gif Index: Doc/Extra/Core/images/sqlite370_banner.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/sqlite370_banner.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/a.gif Index: Doc/Extra/Core/images/syntax/a.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/a.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/alter-table-stmt.gif Index: Doc/Extra/Core/images/syntax/alter-table-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/alter-table-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/analyze-stmt.gif Index: Doc/Extra/Core/images/syntax/analyze-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/analyze-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/attach-stmt.gif Index: Doc/Extra/Core/images/syntax/attach-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/attach-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/begin-stmt.gif Index: Doc/Extra/Core/images/syntax/begin-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/begin-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/column-constraint.gif Index: Doc/Extra/Core/images/syntax/column-constraint.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/column-constraint.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/column-def.gif Index: Doc/Extra/Core/images/syntax/column-def.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/column-def.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/comment-syntax.gif Index: Doc/Extra/Core/images/syntax/comment-syntax.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/comment-syntax.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/commit-stmt.gif Index: Doc/Extra/Core/images/syntax/commit-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/commit-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/common-table-expression.gif Index: Doc/Extra/Core/images/syntax/common-table-expression.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/common-table-expression.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/compound-operator.gif Index: Doc/Extra/Core/images/syntax/compound-operator.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/compound-operator.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/compound-select-stmt.gif Index: Doc/Extra/Core/images/syntax/compound-select-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/compound-select-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/conflict-clause.gif Index: Doc/Extra/Core/images/syntax/conflict-clause.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/conflict-clause.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/create-index-stmt.gif Index: Doc/Extra/Core/images/syntax/create-index-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/create-index-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/create-table-stmt.gif Index: Doc/Extra/Core/images/syntax/create-table-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/create-table-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/create-trigger-stmt.gif Index: Doc/Extra/Core/images/syntax/create-trigger-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/create-trigger-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/create-view-stmt.gif Index: Doc/Extra/Core/images/syntax/create-view-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/create-view-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/create-virtual-table-stmt.gif Index: Doc/Extra/Core/images/syntax/create-virtual-table-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/create-virtual-table-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/cte-table-name.gif Index: Doc/Extra/Core/images/syntax/cte-table-name.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/cte-table-name.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/delete-stmt-limited.gif Index: Doc/Extra/Core/images/syntax/delete-stmt-limited.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/delete-stmt-limited.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/delete-stmt.gif Index: Doc/Extra/Core/images/syntax/delete-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/delete-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/detach-stmt.gif Index: Doc/Extra/Core/images/syntax/detach-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/detach-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/drop-index-stmt.gif Index: Doc/Extra/Core/images/syntax/drop-index-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/drop-index-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/drop-table-stmt.gif Index: Doc/Extra/Core/images/syntax/drop-table-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/drop-table-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/drop-trigger-stmt.gif Index: Doc/Extra/Core/images/syntax/drop-trigger-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/drop-trigger-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/drop-view-stmt.gif Index: Doc/Extra/Core/images/syntax/drop-view-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/drop-view-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/expr.gif Index: Doc/Extra/Core/images/syntax/expr.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/expr.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/factored-select-stmt.gif Index: Doc/Extra/Core/images/syntax/factored-select-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/factored-select-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/floating-point-literal.gif Index: Doc/Extra/Core/images/syntax/floating-point-literal.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/floating-point-literal.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/foreign-key-clause.gif Index: Doc/Extra/Core/images/syntax/foreign-key-clause.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/foreign-key-clause.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/foreign-key-clause2.gif Index: Doc/Extra/Core/images/syntax/foreign-key-clause2.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/foreign-key-clause2.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/indexed-column.gif Index: Doc/Extra/Core/images/syntax/indexed-column.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/indexed-column.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/insert-stmt.gif Index: Doc/Extra/Core/images/syntax/insert-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/insert-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/join-clause.gif Index: Doc/Extra/Core/images/syntax/join-clause.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/join-clause.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/join-constraint.gif Index: Doc/Extra/Core/images/syntax/join-constraint.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/join-constraint.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/join-op.gif Index: Doc/Extra/Core/images/syntax/join-op.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/join-op.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/join-operator.gif Index: Doc/Extra/Core/images/syntax/join-operator.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/join-operator.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/join-source.gif Index: Doc/Extra/Core/images/syntax/join-source.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/join-source.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/literal-value.gif Index: Doc/Extra/Core/images/syntax/literal-value.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/literal-value.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/numeric-literal.gif Index: Doc/Extra/Core/images/syntax/numeric-literal.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/numeric-literal.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/ordering-term.gif Index: Doc/Extra/Core/images/syntax/ordering-term.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/ordering-term.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/pragma-stmt.gif Index: Doc/Extra/Core/images/syntax/pragma-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/pragma-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/pragma-value.gif Index: Doc/Extra/Core/images/syntax/pragma-value.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/pragma-value.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/qualified-table-name.gif Index: Doc/Extra/Core/images/syntax/qualified-table-name.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/qualified-table-name.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/raise-function.gif Index: Doc/Extra/Core/images/syntax/raise-function.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/raise-function.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/recursive-cte.gif Index: Doc/Extra/Core/images/syntax/recursive-cte.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/recursive-cte.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/reindex-stmt.gif Index: Doc/Extra/Core/images/syntax/reindex-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/reindex-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/release-stmt.gif Index: Doc/Extra/Core/images/syntax/release-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/release-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/result-column.gif Index: Doc/Extra/Core/images/syntax/result-column.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/result-column.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/rollback-stmt.gif Index: Doc/Extra/Core/images/syntax/rollback-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/rollback-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/savepoint-stmt.gif Index: Doc/Extra/Core/images/syntax/savepoint-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/savepoint-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/select-core.gif Index: Doc/Extra/Core/images/syntax/select-core.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/select-core.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/select-stmt.gif Index: Doc/Extra/Core/images/syntax/select-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/select-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/signed-number.gif Index: Doc/Extra/Core/images/syntax/signed-number.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/signed-number.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/simple-select-stmt.gif Index: Doc/Extra/Core/images/syntax/simple-select-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/simple-select-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/single-source.gif Index: Doc/Extra/Core/images/syntax/single-source.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/single-source.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/sql-stmt-list.gif Index: Doc/Extra/Core/images/syntax/sql-stmt-list.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/sql-stmt-list.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/sql-stmt.gif Index: Doc/Extra/Core/images/syntax/sql-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/sql-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/table-constraint.gif Index: Doc/Extra/Core/images/syntax/table-constraint.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/table-constraint.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/table-or-subquery.gif Index: Doc/Extra/Core/images/syntax/table-or-subquery.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/table-or-subquery.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/type-name.gif Index: Doc/Extra/Core/images/syntax/type-name.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/type-name.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/update-stmt-limited.gif Index: Doc/Extra/Core/images/syntax/update-stmt-limited.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/update-stmt-limited.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/update-stmt.gif Index: Doc/Extra/Core/images/syntax/update-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/update-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/vacuum-stmt.gif Index: Doc/Extra/Core/images/syntax/vacuum-stmt.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/vacuum-stmt.gif cannot compute difference between binary files ADDED Doc/Extra/Core/images/syntax/with-clause.gif Index: Doc/Extra/Core/images/syntax/with-clause.gif ================================================================== --- /dev/null +++ Doc/Extra/Core/images/syntax/with-clause.gif cannot compute difference between binary files ADDED Doc/Extra/Core/lang.html Index: Doc/Extra/Core/lang.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang.html @@ -0,0 +1,171 @@ + + + +Query Language Understood by SQLite + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ + + +

SQL As Understood By SQLite

+ +

SQLite understands most of the standard SQL +language. But it does omit some features +while at the same time +adding a few features of its own. This document attempts to +describe precisely what parts of the SQL language SQLite does +and does not support. A list of SQL keywords is +also provided. The SQL language syntax is described by +syntax diagrams. + +

The following syntax documentation topics are available:

+ + +
+ +

The routines sqlite3_prepare_v2(), sqlite3_prepare(), +sqlite3_prepare16(), sqlite3_prepare16_v2(), +sqlite3_exec(), and sqlite3_get_table() accept +an SQL statement list (sql-stmt-list) which is a semicolon-separated +list of statements.

+ +

sql-stmt-list:

+ syntax diagram sql-stmt-list +
+ + +

Each SQL statement in the statement list is an instance of the +following:

+ +

sql-stmt:

+ syntax diagram sql-stmt +
+ + + ADDED Doc/Extra/Core/lang_aggfunc.html Index: Doc/Extra/Core/lang_aggfunc.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_aggfunc.html @@ -0,0 +1,215 @@ + + + +SQLite Query Language: Aggregate Functions + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

Aggregate Functions

+ +

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

+ +

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

+ + + +
+avg(X) + The avg() function + returns the average value of all non-NULL X within a + group. String and BLOB values that do not look like numbers are + interpreted as 0. + The result of avg() is always a floating point value as long as + at there is at least one non-NULL input even if all + inputs are integers. The result of avg() is NULL if and only if + there are no non-NULL inputs. +
+count(X)
count(*)
+ The count(X) function returns + a count of the number of times + that X is not NULL in a group. The count(*) function + (with no arguments) returns the total number of rows in the group. +
+group_concat(X)
group_concat(X,Y)
+ The group_concat() function returns + a string which is the concatenation of + all non-NULL values of X. If parameter Y is present then + it is used as the separator + between instances of X. A comma (",") is used as the separator + if Y is omitted. The order of the concatenated elements is + arbitrary. +
+max(X) + The max() aggregate function + returns the maximum value of all values in the group. + The maximum value is the value that would be returned last in an + ORDER BY on the same column. Aggregate max() returns NULL + if and only if there are no non-NULL values in the group. +
+min(X) + The min() aggregate function + returns the minimum non-NULL value of all values in the group. + The minimum value is the first non-NULL value that would appear + in an ORDER BY of the column. + Aggregate min() returns NULL if and only if there are no non-NULL + values in the group. +
+sum(X)
total(X)
+ The sum() and total() aggregate functions + return sum of all non-NULL values in the group. + If there are no non-NULL input rows then sum() returns + NULL but total() returns 0.0. + NULL is not normally a helpful result for the sum of no rows + but the SQL standard requires it and most other + SQL database engines implement sum() that way so SQLite does it in the + same way in order to be compatible. The non-standard total() function + is provided as a convenient way to work around this design problem + in the SQL language.

+ +

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

+ +

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

+ + Index: Doc/Extra/Core/lang_altertable.html ================================================================== --- Doc/Extra/Core/lang_altertable.html +++ Doc/Extra/Core/lang_altertable.html @@ -1,127 +1,290 @@ - - - - ALTER TABLE - - - - -
-
-

- SQL As Understood By SQLite

-

- ALTER TABLE

-

- - - - - - - - - - - - - -
- sql-statement ::= - ALTER TABLE [database-name .] table-name alteration
- alteration ::= - RENAME TO new-table-name
- alteration ::= - ADD [COLUMN] column-def
-

-

- SQLite's version of the ALTER TABLE command allows the user to rename or add a new - column to an existing table. It is not possible to remove a column from a table. -

-

- The RENAME TO syntax is used to rename the table identified by [database-name.]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. However, if there are any view definitions, - or statements executed by triggers that refer to the table being renamed, these - are not automatically modified to use the new table name. If this is required, the - triggers or view definitions must be dropped and recreated to use the new table - name by hand. -

-

- 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. Column-def - may take any of the forms permissable 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 or CURRENT_TIMESTAMP. -
  • -
  • If a NOT NULL constraint is specified, then the column must have a default value - other than NULL.
  • -
-

- The execution time of the ALTER TABLE command is independent of the amount of data - in the table. The ALTER TABLE command runs as quickly on a table with 10 million - rows as it does on a table with 1 row. -

-

- After ADD COLUMN has been run on a database, that database will not be readable - by SQLite version 3.1.3 and earlier until the database is - VACUUMed.

-

-  

-
- -
-
- - + + + +SQLite Query Language: ALTER TABLE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

ALTER TABLE

alter-table-stmt: +

+
+ syntax diagram alter-table-stmt +

column-def: +

+ +
+ + +

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

+ +

The RENAME TO syntax is used to rename the table identified by +[database-name.]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. However, if there are +any view definitions, or statements executed by triggers that refer to +the table being renamed, these are not automatically modified to use the new +table name. If this is required, the triggers or view definitions must be +dropped and recreated to use the new table name by hand. +

+ +

If foreign key constraints are +enabled when a table is renamed, then any +REFERENCES clauses in any table (either the +table being renamed or some other table) +that refer to the table being renamed are modified to refer +to the renamed table by its new name. + +

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 column-def 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 REFERENCES clause + is added, the column must have a default value of NULL. +
+ +

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

+ +

The execution time of the ALTER TABLE command is independent of +the amount of data in the table. The ALTER TABLE command runs as quickly +on a table with 10 million rows as it does on a table with 1 row. +

+ +

After ADD COLUMN has been run on a database, that database will not +be readable by SQLite version 3.1.3 and earlier.

+ + Index: Doc/Extra/Core/lang_analyze.html ================================================================== --- Doc/Extra/Core/lang_analyze.html +++ Doc/Extra/Core/lang_analyze.html @@ -1,102 +1,193 @@ - - - - ANALYZE - - - - -
-
-

- SQL As Understood By SQLite

-

- ANALYZE

-

- - - - - -
- sql-statement ::= - ANALYZE
- - - - - -
- sql-statement ::= - ANALYZE database-name
- - - - - -
- sql-statement ::= - ANALYZE [database-name .] table-name
-

-

- The ANALYZE command gathers statistics about indices and stores them in a special - tables in the database where the query optimizer can use them to help make better - index choices. If no arguments are given, all indices in all attached databases - are analyzed. If a database name is given as the argument, all indices in that one - database are analyzed. If the argument is a table name, then only indices associated - with that one table are analyzed.

-

- The initial implementation stores all statistics in a single table named sqlite_stat1. - Future enhancements may create additional tables with the same name pattern except - with the "1" changed to a different digit. The sqlite_stat1 table cannot be DROPped, but all the content can be - DELETEd which has the same effect.

-

-  

-
- -
-
- - + + + +SQLite Query Language: ANALYZE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

ANALYZE

analyze-stmt: +

+
+ syntax diagram analyze-stmt +
+ + +

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

+ +

The default implementation stores all statistics in a single +table named "sqlite_stat1". If SQLite is compiled with the +SQLITE_ENABLE_STAT3 option and without the SQLITE_ENABLE_STAT4 +option, then additional histogram data is +collected and stored in sqlite_stat3. + 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 +when compiled with SQLITE_ENABLE_STAT2 but all recent versions of +SQLite ignore the sqlite_stat2 table. +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. +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_master.

+ +

+ + Index: Doc/Extra/Core/lang_attach.html ================================================================== --- Doc/Extra/Core/lang_attach.html +++ Doc/Extra/Core/lang_attach.html @@ -1,107 +1,252 @@ - - - - ATTACH DATABASE - - - -

-
-
-

- SQL As Understood By SQLite

-

- ATTACH DATABASE

-

- - - - - -
- sql-statement ::= - ATTACH [DATABASE] database-filename AS database-name
-

-

- The ATTACH DATABASE statement adds another database file to the current database - connection. If the filename contains punctuation characters it must be quoted. The - names 'main' and 'temp' refer to the main database and the database used for temporary - tables. These cannot be detached. Attached databases are removed using the - DETACH DATABASE statement.

-

- You can read from and write to an attached database and you can modify the schema - of the attached database. This is a new feature of SQLite version 3.0. In SQLite - 2.8, schema changes to attached databases were not allowed.

-

- You cannot create a new table with the same name as a table in an attached database, - but you can attach a database which contains tables whose names are duplicates of - tables in the main database. It is also permissible to attach the same database - file multiple times.

-

- Tables in an attached database can be referred to using the syntax database-name.table-name. - If an attached table doesn't have a duplicate table name in the main database, it - doesn't require a database name prefix. When a database is attached, all of its - tables which don't have duplicate names become the default table of that name. Any - tables of that name attached afterwards require the table prefix. If the default - table of a given name is detached, then the last table of that name attached becomes - the new default.

-

- Transactions involving multiple attached databases are atomic, assuming that the - main database is not ":memory:". If the main database is ":memory:" 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. Atomic commit - of attached databases is a new feature of SQLite version 3.0. In SQLite version - 2.8, all commits to attached databases behaved as if the main database were ":memory:". -

-

- There is a compile-time limit of 10 attached database files.

-

-


-  

- -
-
- - + + + +SQLite Query Language: ATTACH DATABASE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

ATTACH DATABASE

attach-stmt: +

+
+ syntax diagram attach-stmt +

expr: +

+ +
+ + +

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

The name that occurs after the AS keyword is the name of the database +used internally by SQLite. +The database-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 +database-name.table-name. If the name of the table is unique +across all attached databases and the main and temp databases, then the +database-name prefix is not required. If two or more tables in +different databases have the same name and the +database-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.

+ + Index: Doc/Extra/Core/lang_comment.html ================================================================== --- Doc/Extra/Core/lang_comment.html +++ Doc/Extra/Core/lang_comment.html @@ -1,102 +1,160 @@ - - - - comment - - - - -
-
-

- SQL As Understood By SQLite

-

- comment

-

- - - - - - - - - - - - - -
- comment ::= - SQL-comment | C-comment
- SQL-comment ::= - -- single-line
- C-comment ::= - /* multiple-lines [*/]
-

-

- Comments aren't SQL commands, but can occur in SQL queries. They are treated as - whitespace by the parser. They can begin anywhere whitespace can be found, including - inside expressions that span multiple lines. -

-

- SQL comments only extend to the end of the current line.

-

- C comments can span any number of lines. If there is no terminating delimiter, they - extend to the end of the input. This is not treated as an error. A new SQL statement - can begin on a line after a multiline comment ends. C comments can be embedded anywhere - whitespace can occur, including inside expressions, and in the middle of - other SQL - statements. C comments do not nest. SQL comments inside a C comment will be ignored. -

-

-


-  

- -
-
- - + + + +SQLite Query Language: comment + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

comment

comment-syntax: +

+
+ syntax diagram comment-syntax +
+ + +

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

+ + + Index: Doc/Extra/Core/lang_conflict.html ================================================================== --- Doc/Extra/Core/lang_conflict.html +++ Doc/Extra/Core/lang_conflict.html @@ -1,149 +1,229 @@ - - - - ON CONFLICT - - - - -
-
-

- SQL As Understood By SQLite

-

- ON CONFLICT clause

-

- - - - - - - - - -
- conflict-clause ::= - ON CONFLICT conflict-algorithm
- conflict-algorithm ::= - ROLLBACK | - ABORT | FAIL | IGNORE | REPLACE
-

-

- The ON CONFLICT clause is not a separate SQL command. It is a non-standard clause - 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 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", - to make the syntax seem more natural. 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 specifies an algorithm used to resolve constraint conflicts. - There are five choices: ROLLBACK, ABORT, FAIL, IGNORE, and REPLACE. The default - algorithm is ABORT. This is what they mean:

-
-
ROLLBACK
-
-

- When a constraint violation occurs, an immediate ROLLBACK occurs, thus ending the - current transaction, and the command aborts with a return code of SQLITE_CONSTRAINT. - If no transaction is active (other than the implied transaction that is created - on every command) then this algorithm works the same as ABORT.

-
-
ABORT
-
-

- When a constraint violation occurs, the command backs out any prior changes it might - have made and aborts with a return code of SQLITE_CONSTRAINT. But no ROLLBACK is - executed so changes from prior commands within the same transaction are preserved. - This is the default behavior.

-
-
FAIL
-
-

- When a constraint violation occurs, the command aborts with a return code SQLITE_CONSTRAINT. - But any changes to the database that the command made prior to encountering the - constraint violation are preserved and are not backed out. 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.

-
-
IGNORE
-
-

- When a constraint violation occurs, the one row that contains the constraint violation - is not inserted or changed. But the command continues executing normally. Other - rows before and after the row that contained the constraint violation continue to - be inserted or updated normally. No error is returned.

-
-
REPLACE
-
-

- When a UNIQUE constraint violation occurs, the pre-existing rows that are causing - the constraint violation are removed prior to inserting or updating the current - row. Thus the insert or update always occurs. The command continues executing normally. - No error is returned. If a NOT NULL constraint violation occurs, the NULL value - is replaced by the default value for that column. If the column has no default value, - then the ABORT algorithm is used. If a CHECK constraint violation occurs then the - IGNORE algorithm is used.

-

- When this conflict resolution strategy deletes rows in order to satisfy a constraint, - it does not invoke delete triggers on those rows. This behavior might change in - a future release.

-
-
-

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

-

-


-  

- -
-
- - + + + +SQLite Query Language: ON CONFLICT clause + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

ON CONFLICT clause

conflict-clause: +

+
+ syntax diagram conflict-clause +
+ + +

The ON CONFLICT clause is not a separate SQL command. It is a +non-standard clause 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 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 and NOT NULL +constraints (and to PRIMARY KEY constraints which for the purposes +of this section are the same thing as UNIQUE 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.

+ +
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 when the IGNORE conflict resolution +algorithm is used.

+ +
REPLACE
+

When a UNIQUE 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 violation occurs, the REPLACE conflict resolution +algorithm always 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.

+ + ADDED Doc/Extra/Core/lang_corefunc.html Index: Doc/Extra/Core/lang_corefunc.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_corefunc.html @@ -0,0 +1,450 @@ + + + +SQLite Query Language: Core Functions + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

Core Functions

+ +

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

+ + + +
+abs(X) + The abs(X) function returns the absolute value of the numeric + argument X. Abs(X) returns NULL if X is NULL. + Abs(X) return 0.0 if X is a string or blob + that cannot be converted to a numeric value. If X is the + integer -9223372036854775808 then abs(X) throws an integer overflow + error since there is no equivalent positive 64-bit two complement value. +
+changes() + The changes() function returns the number of database rows that were changed + or inserted or deleted by the most recently completed INSERT, DELETE, + or UPDATE statement, exclusive of statements in lower-level triggers. + The changes() SQL function is a wrapper around the sqlite3_changes() + C/C++ function and hence follows the same rules for counting changes. +
+char(X1,X2,...,XN) + The char(X1,X2,...,XN) function returns a string composed of characters having the + unicode code point values of integers X1 through XN, respectively. +
+coalesce(X,Y,...) + The coalesce() function returns a copy of its first non-NULL argument, or + NULL if all arguments are NULL. Coalesce() must have at least + 2 arguments. +
+glob(X,Y) + The glob(X,Y) function is equivalent to the + expression "Y GLOB X". + Note that the X and Y arguments are reversed in the glob() function + relative to the infix GLOB operator. + 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. +
+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. +
+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. +
+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. +
+last_insert_rowid() + The last_insert_rowid() function returns the ROWID + of the last row insert from the database connection which invoked the + function. + The last_insert_rowid() SQL function is a wrapper around the + sqlite3_last_insert_rowid() C/C++ interface function. +
+length(X) + For a string value X, the length(X) function returns the number of + characters (not bytes) in X prior to the first NUL character. + Since SQLite strings do not normally contain NUL characters, the length(X) + function will usually return the total number of characters in the string X. + For a blob value X, length(X) returns the number of bytes in the blob. + If X is NULL then length(X) is NULL. + If X is numeric then length(X) returns the length of a string + representation of X. +
+like(X,Y)
like(X,Y,Z)
+ The like() function is used to implement the + "Y LIKE X [ESCAPE Z]" 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. + 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). +
+load_extension(X)
load_extension(X,Y)
+ The load_extension(X,Y) function loads SQLite extensions out of the shared + library file named X using the entry point Y. The result of load_extension() + is always a NULL. If Y is omitted then the default entry point name is used. + The load_extension() function raises an exception if the extension fails to + load or initialize correctly. + +

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

+ +

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

+
+lower(X) + The lower(X) function returns a copy of string X with all ASCII characters + converted to lower case. The default built-in lower() function works + for ASCII characters only. To do case conversions on non-ASCII + characters, load the ICU extension. +
+ltrim(X)
ltrim(X,Y)
+ The ltrim(X,Y) function returns a string formed by removing any and all + characters that appear in Y from the left side of X. + If the Y argument is omitted, ltrim(X) removes spaces from the left side + of X. +
+max(X,Y,...) + The multi-argument max() function returns the argument with the + maximum value, or return NULL if any argument is NULL. + The multi-argument max() function searches its arguments from left to right + for an argument that defines a collating function and uses that collating + function for all string comparisons. If none of the arguments to max() + define a collating function, then the BINARY collating function is used. + Note that max() is a simple function when + it has 2 or more arguments but operates as an + aggregate function if given only a single argument. +
+min(X,Y,...) + The multi-argument min() function returns the argument with the + minimum value. + The multi-argument min() function searches its arguments from left to right + for an argument that defines a collating function and uses that collating + function for all string comparisons. If none of the arguments to min() + define a collating function, then the BINARY collating function is used. + Note that min() is a simple function when + it has 2 or more arguments but operates as an + aggregate function if given + only a single argument. +
+nullif(X,Y) + The nullif(X,Y) function returns its first argument if the arguments are + different and NULL if the arguments are the same. The nullif(X,Y) function + searches its arguments from left to right for an argument that defines a + collating function and uses that collating function for all string + comparisons. If neither argument to nullif() defines a collating function + then the BINARY is used. +
+printf(FORMAT,...) + The printf(FORMAT,...) SQL function works like the sqlite3_mprintf() C-language + function and the printf() function from the standard C library. + The first argument is a format string that specifies how to construct the output + string using values taken from subsequent arguments. If the FORMAT argument is + missing or NULL then the result is NULL. The %n format is silently ignored and + does not consume an argument. The %p format is an alias for %X. The %z format + is interchangeable with %s. If there are too few arguments in the argument list, + missing arguments are assumed to have a NULL value, which is translated into + 0 or 0.0 for numeric formats or an empty string for %s. +
+quote(X) + The quote(X) function returns the text of an SQL literal which + is the value of its argument suitable for inclusion into an SQL statement. + Strings are surrounded by single-quotes with escapes on interior quotes + as needed. BLOBs are encoded as hexadecimal literals. + Strings with embedded NUL characters cannot be represented as string + literals in SQL and hence the returned string literal is truncated prior + to the first NUL. +
+random() + The random() function returns a pseudo-random integer + between -9223372036854775808 and +9223372036854775807. +
+randomblob(N) + The randomblob(N) function return an N-byte blob containing pseudo-random + bytes. If N is less than 1 then a 1-byte random blob is returned. + +

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

+ +
+ hex(randomblob(16))

+ lower(hex(randomblob(16))) +
+
+replace(X,Y,Z) + The replace(X,Y,Z) function returns a string formed by substituting + string Z for every occurrence of string Y in string X. The BINARY + collating sequence is used for comparisons. If Y is an empty + string then return X unchanged. If Z is not initially + a string, it is cast to a UTF-8 string prior to processing. +
+round(X)
round(X,Y)
+ The round(X,Y) function returns a floating-point + value X rounded to Y digits to the right of the decimal point. + If the Y argument is omitted, it is assumed to be 0. +
+rtrim(X)
rtrim(X,Y)
+ The rtrim(X,Y) function returns a string formed by removing any and all + characters that appear in Y from the right side of X. + If the Y argument is omitted, rtrim(X) removes spaces from the right + side of X. +
+soundex(X) + The soundex(X) function returns a string that is the soundex encoding + of the string X. + The string "?000" is returned if the argument is NULL or contains + no ASCII alphabetic characters. + This function is omitted from SQLite by default. + It is only available if the SQLITE_SOUNDEX compile-time option + is used when SQLite is built. +
+sqlite_compileoption_get(N) + The sqlite_compileoption_get() SQL function is a wrapper around the + sqlite3_compileoption_get() C/C++ function. + This routine returns the N-th compile-time option used to build SQLite + or NULL if N is out of range. See also the compile_options pragma. +
+sqlite_compileoption_used(X) + The sqlite_compileoption_used() SQL function is a wrapper around the + sqlite3_compileoption_used() C/C++ function. + When the argument X to sqlite_compileoption_used(X) is a string which + is the name of a compile-time option, this routine returns true (1) or + false (0) depending on whether or not that option was used during the + build. +
+sqlite_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() begins with + the date and time that the source code was checked in and is follows by + an SHA1 hash that uniquely identifies the source tree. This function is + an SQL wrapper around the sqlite3_sourceid() C interface. +
+sqlite_version() + The sqlite_version() function returns the version string for the SQLite + library that is running. This function is an SQL + wrapper around the sqlite3_libversion() C-interface. +
+substr(X,Y,Z)
substr(X,Y)
+ The substr(X,Y,Z) function returns a substring of input string X that begins + with the Y-th character and which is Z characters long. + If Z is omitted then substr(X,Y) returns all characters through the end + of the string X beginning with the Y-th. + The left-most character of X is number 1. If Y is negative + then the first character of the substring is found by counting from the + right rather than the left. If Z is negative then + the abs(Z) characters preceding the Y-th character are returned. + If X is a string then characters indices refer to actual UTF-8 + characters. If X is a BLOB then the indices refer to bytes. +
+total_changes() + The total_changes() function returns the number of row changes + caused by INSERT, UPDATE or DELETE + statements since the current database connection was opened. + This function is a wrapper around the sqlite3_total_changes() + C/C++ interface. +
+trim(X)
trim(X,Y)
+ The trim(X,Y) function returns a string formed by removing any and all + characters that appear in Y from both ends of X. + If the Y argument is omitted, trim(X) removes spaces from both ends of X. +
+typeof(X) + The typeof(X) function returns a string that indicates the datatype of + the expression X: "null", "integer", "real", "text", or "blob". +
+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). +
+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. +
+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. +
+ + Index: Doc/Extra/Core/lang_createindex.html ================================================================== --- Doc/Extra/Core/lang_createindex.html +++ Doc/Extra/Core/lang_createindex.html @@ -1,119 +1,263 @@ - - - - CREATE INDEX - - - - -
-
-

- SQL As Understood By SQLite

-

- CREATE INDEX

-

- - - - - - - - - -
- sql-statement ::= - CREATE [UNIQUE] INDEX [IF NOT EXISTS] [database-name .] - index-name -
- ON
table-name - ( column-name - [, - column-name]* )
- column-name ::= - name [ COLLATE collation-name] [ ASC | DESC ]
-

-

- 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 names of columns in the table - that are used for the index key. Each column name can be followed by one of the - "ASC" or "DESC" keywords to indicate sort order, but the sort order is ignored in - the current implementation. Sorting is always done in ascending order.

-

- The COLLATE clause following each column name defines a collating sequence used - for text entires 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.

-

- There are no arbitrary limits on the number of indices that can be attached to a - single table, nor on the number of columns in an index.

-

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

-

- The exact text of each CREATE INDEX statement is stored in the sqlite_master - or sqlite_temp_master table, depending on whether the table being indexed - is temporary. Every time the database is opened, all CREATE INDEX statements are - read from the sqlite_master table and used to regenerate - SQLite's internal - representation of the index layout.

-

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

-

- Indexes are removed with the DROP INDEX command.

-

-


-  

- -
-
- - + + + +SQLite Query Language: CREATE INDEX + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

CREATE INDEX

create-index-stmt: +

+
+ syntax diagram create-index-stmt +

expr: +

+ +

indexed-column: +

+ +
+ + +

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 names of +columns in the table that are used for the index key. +If the optional WHERE clause is included, then the index is a "partial index". +

+ + + +

Each column name 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 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 and later. +The legacy_file_format pragma can be used to change set the specific +behavior for any version of SQLite.

+ +

The COLLATE clause optionally following each column name 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.

+ +

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

+ + + +

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 to 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) and is the interpretation +followed by PostgreSQL, MySQL, Firebird, and Oracle. Informix and +Microsoft SQL Server follow the other interpretation of the standard.

+ +

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.

+ +

Indexes are removed with the DROP INDEX command.

+ + + Index: Doc/Extra/Core/lang_createtable.html ================================================================== --- Doc/Extra/Core/lang_createtable.html +++ Doc/Extra/Core/lang_createtable.html @@ -1,250 +1,621 @@ - - - - CREATE TABLE - - - - -
-
-

- SQL As Understood By SQLite

-

- CREATE TABLE

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- sql-command ::= - CREATE [TEMP - | TEMPORARY] - TABLE [IF NOT EXISTS] - [database-name .] - table-name (
-    
column-def - [, - column-def]*
-    
[, - constraint]*
- )
- sql-command ::= - CREATE [TEMP - | TEMPORARY] - TABLE [database-name.] - table-name AS - select-statement
- column-def ::= - name [type] [[CONSTRAINT name] - column-constraint]*
- type ::= - typename |
-
typename - ( number - ) |
-
typename - ( number - , number - )
- column-constraint ::= - NOT NULL [ - conflict-clause - ] |
- PRIMARY KEY
[sort-order] [ - conflict-clause - ] [AUTOINCREMENT] |
- UNIQUE
[ conflict-clause ] |
- CHECK (
expr - ) |
- DEFAULT
value - |
- COLLATE
collation-name
- constraint ::= - PRIMARY KEY ( - column-list ) [ conflict-clause ] |
- UNIQUE (
column-list ) [ - conflict-clause - ] |
- CHECK (
expr - )
- conflict-clause ::= - ON CONFLICT conflict-algorithm
-

-

- A CREATE TABLE statement is basically the keywords "CREATE TABLE" followed by the - name of a new table and a parenthesized list of column definitions and constraints. - The table name can be either an identifier or a string. Tables names that begin - with "sqlite_" are reserved for use by the engine.

-

- Each column definition is the name of the column followed by the datatype for that - column, then one or more optional column constraints. The datatype for the column - does not restrict what data may be put in that column. See - Datatypes In SQLite Version 3 for additional information. The UNIQUE constraint - causes an index to be created on the specified columns. This index must contain - unique keys. The COLLATE clause specifies what text - collating function to use when comparing text entries for the column. The - built-in BINARY collating function is used by default. -

-

- The DEFAULT constraint specifies a default value to use when doing an INSERT. The - value may be NULL, a string constant or a number. Starting with version 3.1.0, the - default value may also be one of the special case-independant keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. If the value is NULL, a string constant or number, - it is literally inserted into the column whenever an INSERT statement that does - not specify a value for the column is executed. If the value is CURRENT_TIME, CURRENT_DATE - or CURRENT_TIMESTAMP, then the current UTC date and/or time is inserted into the - columns. For CURRENT_TIME, the format is HH:MM:SS. For CURRENT_DATE, YYYY-MM-DD. - The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS". -

-

- Specifying a PRIMARY KEY normally just creates a UNIQUE index on the corresponding - columns. However, if primary key is on a single column that has datatype INTEGER, - then that column is used internally as the actual key of the B-Tree for the table. - This means that the column may only hold unique integer values. (Except for this - one case, SQLite ignores the datatype specification of columns and allows any kind - of data to be put in a column regardless of its declared datatype.) If a table does - not have an INTEGER PRIMARY KEY column, then the B-Tree key will be a automatically - generated integer. The B-Tree key for a row can always be accessed using one of - the special names "ROWID", "OID", or "_ROWID_". This is true - regardless of whether or not there is an INTEGER PRIMARY KEY. An INTEGER PRIMARY - KEY column man also include the keyword AUTOINCREMENT. The AUTOINCREMENT keyword - modified the way that B-Tree keys are automatically generated. Additional detail - on automatic B-Tree key generation is available - separately.

-

- If the "TEMP" or "TEMPORARY" keyword occurs in between "CREATE" and "TABLE" then - the table that is created is only visible within that same database connection and - is automatically deleted when the database connection is closed. Any indices created - on a temporary table are also temporary. Temporary tables and indices are stored - in a separate file distinct from the main database file.

-

- If a <database-name> is specified, then the table is created in the named - database. It is an error to specify both a <database-name> and the TEMP keyword, - unless the <database-name> is "temp". If no database name is specified, and - the TEMP keyword is not present, the table is created in the main database.

-

- The optional conflict-clause following each constraint allows the specification - of an alternative default constraint conflict resolution algorithm for that constraint. The default is abort ABORT. Different constraints within the same table may have - different default conflict resolution algorithms. If an COPY, INSERT, or UPDATE - command specifies a different conflict resolution algorithm, then that algorithm - is used in place of the default algorithm specified in the CREATE TABLE statement. - See the section titled ON CONFLICT for additional - information.

-

- CHECK constraints are supported as of version 3.3.0. Prior to version 3.3.0, CHECK - constraints were parsed but not enforced.

-

- There are no arbitrary limits on the number of columns or on the number of constraints - in a table. The total amount of data in a single row is limited to about 1 megabytes - in version 2.8. In version 3.0 there is no arbitrary limit on the amount of data - in a row.

-

- The CREATE TABLE AS form defines the table to be the result set of a query. The - names of the table columns are the names of the columns in the result.

-

- The exact text of each CREATE TABLE statement is stored in the sqlite_master - table. Every time the database is opened, all CREATE TABLE statements are read from - the sqlite_master table and used to regenerate - SQLite's internal representation - of the table layout. If the original command was a CREATE TABLE AS then then an - equivalent CREATE TABLE statement is synthesized and store in sqlite_master - in place of the original command. The text of CREATE TEMPORARY TABLE statements - are stored in the sqlite_temp_master table. -

-

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

-

- Tables are removed using the DROP TABLE statement. -

-

-


-  

- -
-
- - + + + +SQLite Query Language: CREATE TABLE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

CREATE TABLE

create-table-stmt: +

+
+ syntax diagram create-table-stmt +

column-def: +

+ +

select-stmt: +

+ +

table-constraint: +

+ +
+ + +

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

  • Whether the table is a WITHOUT ROWID table. +

+ +

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

If a <database-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 + <database-name> and the TEMP or TEMPORARY keyword, unless the + <database-name> is "temp". If no database 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.

+ +

CREATE TABLE ... AS SELECT Statements

+ +

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

+ +
+
Expression Affinity Column Declared Type +
TEXT "TEXT" +
NUMERIC "NUM" +
INTEGER "INT" +
REAL "REAL" +
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. + + + +

Column Definitions

+ +

Unless it is a CREATE TABLE ... AS SELECT statement, a CREATE TABLE includes +one or more column definitions, optionally followed by a list of +table constraints. Each column definition consists of the +name of the column, optionally followed by the declared type of the column, +then one or more optional column constraints. 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 tables data, and are are +described under SQL Data Constraints below. + +

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

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. An explicit +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 provided that it does +not contain any sub-queries or string constants enclosed in double 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". +

+ +

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

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.

+ + + +

SQL Data Constraints

+ + + +

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 table-constraint, then the primary key of the table + consists of the list of columns specified as part of the PRIMARY KEY clause. + 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 + feature identical primary key values, it is a constraint violation. + According to the SQL standard, PRIMARY KEY should always imply NOT NULL. + Unfortunately, due to a bug in some early versions, this is not the + case in SQLite. Unless the column is an INTEGER PRIMARY KEY or + the table is a WITHOUT ROWID table or the column is declared NOT NULL, + SQLite allows NULL values in a PRIMARY KEY column. SQLite could be fixed to + conform to the standard, but doing so might break legacy applications. + Hence, it has been decided to merely document the fact that SQLite + allowing NULLs in most PRIMARY KEY columns. + + + +

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

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

    +
  1. CREATE TABLE t1(a, b UNIQUE); +

  2. CREATE TABLE t1(a, b PRIMARY KEY); +

  3. CREATE TABLE t1(a, b);
    + CREATE UNIQUE INDEX t1b ON t1(b); +

+ + + +

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 have been supported since version 3.3.0. Prior to + version 3.3.0, CHECK constraints were parsed but not enforced. + + + +

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

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

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

+ + Index: Doc/Extra/Core/lang_createtrigger.html ================================================================== --- Doc/Extra/Core/lang_createtrigger.html +++ Doc/Extra/Core/lang_createtrigger.html @@ -1,283 +1,474 @@ - - - - CREATE TABLE - - - - - - + + + + +

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.

+ +

The RAISE() function

+ +

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

+ +

raise-function:

+ syntax diagram raise-function +
+ + +

When one of RAISE(ROLLBACK,...), RAISE(ABORT,...) or RAISE(FAIL,...) +is called during trigger-program +execution, the specified ON CONFLICT processing is performed +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. +

+ + + +

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

+ + Index: Doc/Extra/Core/lang_createview.html ================================================================== --- Doc/Extra/Core/lang_createview.html +++ Doc/Extra/Core/lang_createview.html @@ -1,94 +1,231 @@ - - - - CREATE VIEW - - - - -
-
-

- SQL As Understood By SQLite

-

- CREATE VIEW

-

- - - - - -
- sql-command ::= - CREATE [TEMP - | TEMPORARY] - VIEW [database-name.] - view-name AS - select-statement
-

-

- 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 process that opened the database - and is automatically deleted when the database is closed.

-

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

-

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

-

-


-  

- -
-
- - + + + +SQLite Query Language: CREATE VIEW + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

CREATE VIEW

create-view-stmt: +

+
+ syntax diagram create-view-stmt +

select-stmt: +

+ +
+ + +

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 +process that opened the database and is automatically deleted when +the database is closed.

+ +

If a <database-name> is specified, then the view is created in +the named database. It is an error to specify both a <database-name> +and the TEMP keyword on a VIEW, unless the <database-name> is "temp". +If no database 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.

+ + Index: Doc/Extra/Core/lang_createvtab.html ================================================================== --- Doc/Extra/Core/lang_createvtab.html +++ Doc/Extra/Core/lang_createvtab.html @@ -1,99 +1,166 @@ - - - - CREATE VIRTUAL TABLE - - - - -
-
-

- SQL As Understood By SQLite

-

- CREATE VIRTUAL TABLE

-

- - - - - -
- sql-command ::= - CREATE VIRTUAL TABLE [database-name .] table-name USING module-name [( - arguments )]
-

-

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

-

-


-  

- -
-
- - + + + +SQLite Query Language: CREATE VIRTUAL TABLE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

CREATE VIRTUAL TABLE

create-virtual-table-stmt: +

+
+ syntax diagram create-virtual-table-stmt +
+ + +

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.

+ + ADDED Doc/Extra/Core/lang_datefunc.html Index: Doc/Extra/Core/lang_datefunc.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_datefunc.html @@ -0,0 +1,427 @@ + + + +SQLite Query Language: Date And Time Functions + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

Date And Time Functions

+ +

+SQLite supports five date and time functions as follows: +

+ +

+

    +
  1. date(timestring, modifier, modifier, ...)
  2. +
  3. time(timestring, modifier, modifier, ...)
  4. +
  5. datetime(timestring, modifier, modifier, ...)
  6. +
  7. julianday(timestring, modifier, modifier, ...)
  8. +
  9. strftime(format, timestring, modifier, modifier, ...)
  10. +
+ +

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

+ +

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

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

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

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

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

+ +

Time Strings

+ +

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

+ +
    +
  1. YYYY-MM-DD +
  2. YYYY-MM-DD HH:MM +
  3. YYYY-MM-DD HH:MM:SS +
  4. YYYY-MM-DD HH:MM:SS.SSS +
  5. YYYY-MM-DDTHH:MM +
  6. YYYY-MM-DDTHH:MM:SS +
  7. YYYY-MM-DDTHH:MM:SS.SSS +
  8. HH:MM +
  9. HH:MM:SS +
  10. HH:MM:SS.SSS +
  11. now +
  12. DDDDDDDDDD +
+ +

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

+ +

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

+ +
+2013-10-07 08:23:19.120
+2013-10-07T08:23:19.120Z
+2013-10-07 08: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. +

+ +

Modifiers

+ +

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

+ +
    +
  1. NNN days +
  2. NNN hours +
  3. NNN minutes +
  4. NNN.NNNN seconds +
  5. NNN months +
  6. NNN years +
  7. start of month +
  8. start of year +
  9. start of day +
  10. weekday N +
  11. unixepoch +
  12. localtime +
  13. utc +
+ +

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

+ +

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

+ +

The "weekday" modifier advances the date forward to the next date +where the weekday number is N. Sunday is 0, Monday is 1, and so forth.

+ +

The "unixepoch" modifier (11) only works if it immediately follows +a timestring in the DDDDDDDDDD format. +This modifier causes the DDDDDDDDDD to be interpreted not +as a Julian day number as it normally would be, but as +Unix Time - the +number of seconds since 1970. If the "unixepoch" modifier does not +follow a timestring of the form DDDDDDDDDD which expresses the number +of seconds since 1970 or if other modifiers +separate the "unixepoch" modifier from prior DDDDDDDDDD then the +behavior is undefined. +Due to precision limitations imposed by the implementations use +of 64-bit integers, 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 10675199167).

+ +

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

+ +

Examples

+ +

Compute the current date.

+ +

SELECT date('now');
+ +

Compute the last day of the current month.

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

Compute the date and time given a unix timestamp 1092941466.

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

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

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

Compute the current unix timestamp.

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

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

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

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

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

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

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

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

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

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 (julidan day numbers 1721059.5 through 5373484.5). +For dates outside that range, the results of these +functions are undefined.

+ +

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

+ +

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

+ + DELETED Doc/Extra/Core/lang_datetime.html Index: Doc/Extra/Core/lang_datetime.html ================================================================== --- Doc/Extra/Core/lang_datetime.html +++ /dev/null @@ -1,324 +0,0 @@ - - - - DateTime Functions - - - - -
-
-

Date and Time Functions

-

Five date and time functions are available, as follows: - -

    -
  1. date( timestring, modifier, modifier, ...) -
  2. time( timestring, modifier, modifier, ...) -
  3. datetime( timestring, modifier, modifier, ...) -
  4. julianday( timestring, modifier, modifier, ...) -
  5. strftime( format, timestring, modifier, modifier, ...) -
- -

All five functions take a time string as an argument. This -time string may be followed by zero or more modifiers. The -strftime() function also takes a format string as its first -argument. - -

The date() function returns the date in this format: YYYY-MM-DD. -The time() function returns the time as HH:MM:SS. The datetime() -function returns "YYYY-MM-DD HH:MM:SS". The julianday() function -returns the number of days since noon in Greenwich on November 24, 4714 B.C. -The julian day number is the preferred internal representation of -dates. The strftime() routine returns the date formatted according -to the format string specified as the first argument. The format string -supports most, but not all, of the more common substitutions found in -the strftime() function from the standard C library: - -

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

The %f and %J conversions are new. Notice that all of the other four -functions could be expressed in terms of strftime(). - -

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

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

Time Strings - -

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

    -
  1. YYYY-MM-DD -
  2. YYYY-MM-DD HH:MM -
  3. YYYY-MM-DD HH:MM:SS -
  4. YYYY-MM-DD HH:MM:SS.SSS -
  5. YYYY-MM-DDTHH:MM -
  6. YYYY-MM-DDTHH:MM:SS -
  7. YYYY-MM-DDTHH:MM:SS.SSS -
  8. HH:MM -
  9. HH:MM:SS -
  10. HH:MM:SS.SSS -
  11. now -
  12. DDDD.DDDD -
- -

In formats 5 through 7, the "T" is a literal character separating the date and the time, as required by the ISO-8601 standard. These formats are supported in SQLite 3.2.0 and later. -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. -Universal Coordinated Time (UTC) is used. -Format 12 is the julian day number expressed as a floating point value. - -

Modifiers - -

The time string can be followed by zero or more modifiers that alter the -date or alter the interpretation of the date. The available modifiers -are as follows. - -

    -
  1. NNN days -
  2. NNN hours -
  3. NNN minutes -
  4. NNN.NNNN seconds -
  5. NNN months (see #551 - and [1163] -) -
  6. NNN years (see #551 - and [1163] -) -
  7. start of month -
  8. start of year -
  9. start of week (withdrawn -- will not be implemented) -
  10. start of day -
  11. weekday N (see #551 - and [1163] -) -
  12. unixepoch -
  13. localtime -
  14. utc -
- -

The first six modifiers (1 through 6) simply add the specified amount -of time to the date specified by the preceding timestring. - -

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

The "weekday" modifier advances the date forward to the next date where -the weekday number is N. Sunday is 0, Monday is 1, and so forth. - -

The "unixepoch" modifier (12) only works if it immediately follows -a timestring in the DDDDDDDDDD format. This modifier causes the DDDDDDDDDD -to be interpreted not as a julian day number as it normally would be, but -as the number of seconds since 1970. This modifier allows unix-based times -to be converted to julian day numbers easily. - -

The "localtime" modifier (13) adjusts the previous time string so that it -displays the correct local time. "utc" undoes this. - -

Examples - -

Compute the current date. - -

-  SELECT date('now');
-
- -

Compute the last day of the current month. - -

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

Compute the date and time given a unix timestamp 1092941466. - -

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

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

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

Compute the current unix timestamp. - -

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

Compute the number of days since the battle of Hastings. - -

-  SELECT julianday('now') - julianday('1066-10-14','gregorian');
-
- -

Compute the number of seconds between two dates: - -

-  SELECT julianday('now')*86400 - julianday('2004-01-01 02:34:56')*86400;
-
- -

Compute the date of the first Tuesday in October (January + 9) for the current -year. - -

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

Caveats And Bugs - -

The computation of local time depends heavily on the whim of local -politicians and is thus difficult to get correct for all locales. In -this implementation, the standard C library function localtime() is -used to assist in the calculation of local time. -Note that localtime() is not -threadsafe, so use of the "localtime" modifier is not threadsafe. -Also, the localtime() 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. - -

Please surround uses of localtime() with sqliteOsEnterMutex() and sqliteOsLeaveMutex() so threads -using SQLite are protected, at least! --- e It is so. --drh - -

[Consider instead, using localtime_r which is reentrant and may be used -*without* expensive mutex locking. Although non-standard it's available -on most Unixes --hauk] But it is not available on windows, as far as I -am aware. --drh On windows localtime() is thread-safe if the MT C runtime is used. The MT runtime uses thread-local storage for the static variables, the kind functions use.--gr [What about using localtime_r, and on systems where it -is unavailable defining it as sqliteOsEnterMutext() ; locatime() ; sqliteOsLeaveMutex() -so that non-windows systems get the maximum advantage, with almost zero -code impact?] The autoconfigury and patch for localtime_r is here: ¤http://www.sqlite.org/cvstrac/tktview?tn=1906 . I'm curious why this obvious fix is not applied. gmtime() also suffers from this same threadsafety problem. - -

Date computations do not give correct results for dates before Julian -day number 0 (-4713-11-24 12:00:00). - -

All internal computations assume the Gregorian calendar system. - -


-An anonymous user adds:
- -For my use I added new functions and functionalities to the date functions that -come with the sqlite 3.3.0 (can be used in older versions as well with small effort). - -

In main lines they are as follows: - -

    -
  1. NNN days -
  2. NNN hours -
  3. NNN minutes -
  4. NNN.NNNN seconds -
  5. NNN months (see #551 - and [1163] -) -
  6. NNN years (see #551 - and [1163] -) -
  7. start of month -
  8. start of year -
  9. start of week (!!! implemented) -
  10. start of day -
  11. weekday N (see #551 - and [1163] -) -
  12. unixepoch -
  13. localtime -
  14. utc -
  15. julian (not implemented as of 2004-01-05) -
  16. gregorian (not implemented as of 2004-01-05) -
  17. start of minute -
  18. start of hour -
  19. end of minute -
  20. end of hour -
  21. end of day -
  22. end of week -
  23. end of month -
  24. end of year -
  25. group seconds by -
  26. group minutes by -
  27. group hours by -
  28. group days by -
  29. group weeks by -
  30. group months by -
  31. group years by -
- -

The "start of" modifiers (7 through 10 and 17 through 18) shift the date backwards to the beginning of the current minute, hour, week, month, year or day. - -

The "end of" modifiers (19 through 24) shift the date forwards to -the end of the current minute, hour, week, month, year or day. - -

The "group * by" modifiers (25 through 31) round the date to the closest backward multiple supplied, with some limitations, to the current seconds (1 through 30), minutes (1 through 30), hours (1 through 12), days (1 through 15), weeks (1 through 26), months (1 through 6), years (1 through 100), these limitations are due to dont complicate the calculations when a multiple can span beyound the unit modified. - -

Ex: - -

SELECT datetime('2006-02-04 20:09:23','group hours by 3'); => '2006-02-04 18:00:00' - -

SELECT datetime('2006-02-05 20:09:23','group days by 3'); => '2006-02-04 00:00:00' - -

New functions "week_number(date)" returns the week number of the year on the supplied date parameter, "datetime2seconds(datetime)" return the number of seconds from the supplied datetime parameter. -


- -
-
- - Index: Doc/Extra/Core/lang_delete.html ================================================================== --- Doc/Extra/Core/lang_delete.html +++ Doc/Extra/Core/lang_delete.html @@ -1,83 +1,365 @@ - - - - DELETE - - - - -
-
-

- SQL As Understood By SQLite

-

- DELETE

-

- - - - - -
- sql-statement ::= - DELETE FROM [database-name .] table-name [WHERE - expr]
-

-

- The DELETE command is used to remove records from a table. The command consists - of the "DELETE FROM" keywords followed by the - name of the table from which records - are to be removed. -

-

- Without a WHERE clause, all rows of the table are removed. If a WHERE clause is - supplied, then only those rows that match the expression are removed.

-

-


-  

- -
-
- - + + + +SQLite Query Language: DELETE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

DELETE

delete-stmt: +

+
+ syntax diagram delete-stmt +

expr: +

+ +

qualified-table-name: +

+ +

with-clause: +

+ +
+ + +

The DELETE command removes records from the table identified by the + qualified-table-name. + +

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 + result of evaluating the WHERE clause as a boolean expression is true are deleted. + +

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 + database-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.

    +
+ +

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:

+ +

delete-stmt-limited:

+ syntax diagram delete-stmt-limited +
+ + +

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

The Truncate Optimization

+ +

When the WHERE is omitted from a DELETE statement and the table +being deleted has no triggers, +SQLite uses an optimization to erase the entire table content +without having to visit each row of the table individually. +This "truncate" optimization makes the delete run much faster. +Prior to SQLite version 3.6.5, 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. + +

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.

+ + Index: Doc/Extra/Core/lang_detach.html ================================================================== --- Doc/Extra/Core/lang_detach.html +++ Doc/Extra/Core/lang_detach.html @@ -1,78 +1,150 @@ - - - - DETACH - - - - -
-
-

- SQL As Understood By SQLite

-

- DETACH

-

- - - - - -
- sql-command ::= - DETACH [DATABASE] database-name
-

-

- This statement detaches an additional database connection previously attached using - the ATTACH DATABASE statement. 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.

-

- This statement will fail if SQLite is in the middle of a transaction.

-

-


-  

- -
-
- - + + + +SQLite Query Language: DETACH DATABASE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

DETACH DATABASE

detach-stmt: +

+
+ syntax diagram detach-stmt +
+ + +

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 statement will fail if SQLite is in the middle of a transaction.

+ + + Index: Doc/Extra/Core/lang_dropindex.html ================================================================== --- Doc/Extra/Core/lang_dropindex.html +++ Doc/Extra/Core/lang_dropindex.html @@ -1,83 +1,143 @@ - - - - DROP INDEX - - - - -
-
-

- SQL As Understood By SQLite

-

- DROP INDEX

-

- - - - - -
- sql-command ::= - DROP INDEX [IF EXISTS] [database-name .] - index-name
-

-

- The DROP INDEX statement removes an index added with the - CREATE INDEX statement. The index named is completely removed from the disk. - The only way to recover the index is to reenter the appropriate CREATE INDEX command.

-

- The DROP INDEX statement does not reduce the size of the database file in the default - mode. Empty space in the database is retained for later INSERTs. To remove free - space in the database, use the - VACUUM command. If - AUTOVACUUM mode is enabled for a database then space will be freed automatically by DROP INDEX.

-

-


-  

- -
-
- - + + + +SQLite Query Language: DROP INDEX + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

DROP INDEX

drop-index-stmt: +

+
+ syntax diagram drop-index-stmt +
+ + +

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.

+ + Index: Doc/Extra/Core/lang_droptable.html ================================================================== --- Doc/Extra/Core/lang_droptable.html +++ Doc/Extra/Core/lang_droptable.html @@ -1,86 +1,163 @@ - - - - DROP TABLE - - - - -
-
-

- SQL As Understood By SQLite

-

- DROP TABLE

-

- - - - - -
- sql-command ::= - DROP TABLE [IF EXISTS] [database-name.] - table-name
-

-

- The DROP TABLE statement removes a table added with the CREATE TABLE statement. The - name specified is the table name. It is completely removed - from the database schema and the disk file. The table can not be recovered. All - indices associated with the table are also deleted.

-

- The DROP TABLE statement does not reduce the size of the database file in the default - mode. Empty space in the database is retained for later INSERTs. To remove free - space in the database, use the - VACUUM command. If - AUTOVACUUM mode is enabled for a database then space will be freed automatically by DROP TABLE.

-

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

-

-


-  

- -
-
- - + + + +SQLite Query Language: DROP TABLE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

DROP TABLE

drop-table-stmt: +

+
+ syntax diagram drop-table-stmt +
+ + +

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 <tbl> 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 <tbl> +is executed, so this cannot cause any triggers to fire. By contrast, an +implicit DELETE FROM <tbl> does cause any configured +foreign key actions to take place. +If the implicit DELETE FROM <tbl> 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 <tbl> 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. + + Index: Doc/Extra/Core/lang_droptrigger.html ================================================================== --- Doc/Extra/Core/lang_droptrigger.html +++ Doc/Extra/Core/lang_droptrigger.html @@ -1,77 +1,146 @@ - - - - DROP TRIGGER - - - -

-
-
-

- SQL As Understood By SQLite

-

- DROP TRIGGER

-

- - - - - -
- sql-statement ::= - DROP TRIGGER [database-name .] trigger-name
-

-

- The DROP TRIGGER statement removes a trigger created by the - CREATE TRIGGER statement. The trigger is deleted from the database schema. - Note that triggers are automatically dropped when the associated table is dropped.

-

-


-  

- -
-
- - + + + +SQLite Query Language: DROP TRIGGER + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

DROP TRIGGER

drop-trigger-stmt: +

+
+ syntax diagram drop-trigger-stmt +
+ + +

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_master (or sqlite_temp_master) 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. + + Index: Doc/Extra/Core/lang_dropview.html ================================================================== --- Doc/Extra/Core/lang_dropview.html +++ Doc/Extra/Core/lang_dropview.html @@ -1,76 +1,153 @@ - - - - DROP VIEW - - - -

-
-
-

- SQL As Understood By SQLite

-

- DROP VIEW

-

- - - - - -
- sql-command ::= - DROP VIEW view-name
-

-

- The DROP VIEW statement removes a view created by the CREATE VIEW statement. The - name specified is the view name. It is removed from the - database schema, but no actual data - in the underlying base tables is modified.

-

-


-  

- -
-
- - + + + +SQLite Query Language: DROP VIEW + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

DROP VIEW

drop-view-stmt: +

+
+ syntax diagram drop-view-stmt +
+ + +

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 + database-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. + + + Index: Doc/Extra/Core/lang_explain.html ================================================================== --- Doc/Extra/Core/lang_explain.html +++ Doc/Extra/Core/lang_explain.html @@ -1,82 +1,158 @@ - - - - EXPLAIN - - - -

-
-
-

- SQL As Understood By SQLite

-

- EXPLAIN

-

- - - - - -
- sql-statement ::= - EXPLAIN sql-statement
-

-

- The EXPLAIN command modifier is a non-standard extension. The idea comes from a similar command found in PostgreSQL, but the operation is completely different.

-

- If the EXPLAIN keyword appears before any - other SQLite SQL command then instead - of actually executing the command, the SQLite library will report back the sequence - of virtual machine instructions it would have used to execute the command had the - EXPLAIN keyword not been present. For additional information about virtual machine - instructions see the architecture description - or the documentation on available opcodes - for the virtual machine.

-

-  

-
- -
-
- - + + + +SQLite Query Language: EXPLAIN + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

EXPLAIN

sql-stmt:

+ syntax diagram sql-stmt +
+ + +

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. + + Index: Doc/Extra/Core/lang_expr.html ================================================================== --- Doc/Extra/Core/lang_expr.html +++ Doc/Extra/Core/lang_expr.html @@ -1,905 +1,745 @@ - - - - expression - - - - -

-
-
-

- SQL As Understood By SQLite

-

- expression

-

- - - - - - - - - -
- expr ::= - expr binary-op expr - |
-
expr - [NOT] - like-op - expr [ESCAPE expr] |
-
unary-op - expr - |
- (
expr - ) |
-
column-name - |
-
table-name - . column-name - |
-
database-name - . table-name - . column-name - |
-
literal-value - |
-
parameter - |
-
function-name - ( expr-list - | * ) - |
-
expr ISNULL - |
-
expr NOTNULL - |
-
expr - [NOT] BETWEEN - expr AND - expr - |
-
expr - [NOT] IN ( - value-list - ) |
-
expr - [NOT] IN ( - select-statement - ) |
-
expr - [NOT] IN - [database-name .] - table-name - |
-
[EXISTS] - ( select-statement - ) |
- CASE
[expr] ( - WHEN expr - THEN expr - )+ [ELSE - expr] END |
- CAST (
expr - AS type - )
- like-op ::= - LIKE | GLOB - | REGEXP | MATCH
-

-

- This section is different from the others. Most other sections of this document - talks about a particular SQL command. This section does not talk about a standalone - command but about "expressions" which are subcomponents of most other commands.

-

- SQLite understands the following binary operators, in order from highest to lowest - precedence:

-
-
|| * / % + - << >> & | < <= >
-  >= = == != <> IN AND OR
-
-
-

- Supported unary operators are these:

-
-
- + ! ~ NOT
-
-
-

- The unary operator [Operator +] is a no-op. It can be applied to strings, numbers, - or blobs and it always gives as its result the value of the operand.

-

- Note that there are two variations of the equals and not equals operators. Equals - can be either = or - ==. The non-equals operator can be either - != or <>. The - || operator is "concatenate" - it joins together the two - strings of its operands. The operator % - outputs the remainder of its left operand modulo its right operand.

-

- The result of any binary operator is a numeric value, except for the - || concatenation operator which gives a string result.

- -

- A literal value is an integer number or a floating point number. Scientific notation - is supported. 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. 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. For example:

-
-
X'53514697465'
-
-
-

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

-

- A parameter specifies a placeholder in the expression for a literal value that is - filled in at runtime using the sqlite3_bind - API. 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 999.
- ? - - A question mark that is not followed by a number holds a spot for the next unused - parameter.
- :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 the next unused - number. To avoid confusion, it is best to avoid mixing named and numbered parameters.
- @AAAA - - An "at" sign works exactly like a colon.
- $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 occurances - 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.
-

-
-
-

- Parameters that are not assigned values using - sqlite3_bind are treated as NULL.

- -

- The LIKE operator does a pattern matching comparison. The operand to the right contains - the pattern, the left hand operand contains the string to match against the pattern. - A percent symbol % in the pattern matches - any sequence of zero or more characters in the string. An underscore - _ in the pattern matches any single character in the string. - Any other character matches itself or it's lower/upper case equivalent (i.e. case-insensitive - matching). (A bug: SQLite only understands upper/lower case for 7-bit Latin characters. - Hence the LIKE operator is case sensitive for 8-bit iso8859 characters or UTF-8 - characters. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE - 'Æ' is FALSE.).

-

- 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 itself matches - a literal percent symbol, underscore or escape character in the string, respectively. - The infix LIKE operator is implemented by calling the user function - like(X,Y).

-

- The LIKE operator is not case sensitive and will match upper case characters on - one side against lower case characters on the other. (A bug: SQLite only understands - upper/lower case for 7-bit Latin characters. Hence the LIKE operator is case sensitive - for 8-bit iso8859 characters or UTF-8 characters. For example, the expression 'a' - LIKE 'A' is TRUE but 'æ' LIKE 'Æ' is FALSE.). -

-

-

-

- The infix LIKE operator is implemented by calling the user function - like(X,Y). If an ESCAPE clause is present, it adds a third parameter - to the function call. If the functionality of LIKE can be overridden by defining - an alternative implementation of the like() SQL function.

-

-

- -

- 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 user function glob(X,Y) - 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 a user-defined function named "regexp" is added at - run-time, that function will be called in order to implement the REGEXP operator.

- -

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

-

- 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_". - These special identifiers all describe the unique random integer key (the "row key") - associated with every row of every table. The special identifiers only refer to - the row key if the CREATE TABLE statement does not define a real column with the - same name. Row keys act like read-only columns. A row key can be used anywhere a - regular column can be used, except that you cannot change the value of a row key - in an UPDATE or INSERT statement. "SELECT * ..." does not return the row key.

-

- SELECT statements can appear in expressions as either the right-hand operand of - the IN operator, as a scalar quantity, or as the operand of an EXISTS operator. - As a scalar quantity or the operand of an IN operator, the SELECT should have only - a single column in its result. Compound SELECTs (connected with keywords like UNION - or EXCEPT) are allowed. With the EXISTS operator, the columns in the result set - of the SELECT are ignored and the expression returns TRUE if one or more rows exist - and FALSE if the result set is empty. If no terms in the SELECT expression refer - to value in the containing query, then the expression is evaluated once prior to - any other processing and the result is reused as necessary. If the SELECT expression - does contain variables from the outer query, then the SELECT is reevaluated every - time it is needed.

-

- When a SELECT is the right operand of the IN operator, the IN operator returns TRUE - if the result of the left operand is any of the values generated by the select. - The IN operator may be preceded by the NOT keyword to invert the sense of the test.

-

- When a SELECT appears within an expression but is not the right operand of an IN - operator, then the first row of the result of the SELECT becomes the value used - in the expression. If the SELECT yields more than one result row, all rows after the first are ignored. If the SELECT yields no rows, then the value of the SELECT - is NULL.

-

- A CAST expression changes the datatype of the - - - into the type specified by <type>. <type> can be any non-empty type - name that is valid for the type in a column definition of a CREATE TABLE statement.

-

- Both simple and aggregate functions are supported. A simple function can be used - in any expression. Simple functions return a result immediately based on their inputs. - Aggregate functions may only be used in a SELECT statement. Aggregate functions - compute their result across all rows of the result set.

-

- Core Functions -

-

- The core functions shown below are available by default. Additional functions may - be written in C and added to the database engine using the - sqlite3_create_function() API.

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- abs(X) - Return the absolute value of argument X.
- acos(X) - A mathematical function that returns the angle, in radians, whose cosine is the - specified double expression
- acosh(X) - Inverse hyperbolic cosine
- asin(X) - Returns the angle, in radians, whose sine is the specified double - expression
- asinh(X) - Inverse hyperbolic sine
- atan(X) - Returns the angle in radians whose tangent is a specified double - expression
- atanh(X) - Inverse hyperbolic tangent
- atn2(X,Y)
- atan2(X,Y)
- Returns the angle, in radians, between the positive x-axis and the ray from the - origin to the point (y, x), where x and y are the values of the two specified - double expressions
- ceil(X)
- ceiling(X)
- Returns the smallest integer greater than, or equal to, the specified numeric - expression
- charindex(X,Y[,Z]) - Returns the 1-based position of the string X inside the string Y - starting at position Z.  Returns 0 if not X is not found - within Y.
- coalesce(X,Y,...) - Return a copy of the first non-NULL argument. If all arguments are NULL then NULL - is returned. There must be at least 2 arguments.
- cos(X) - a mathematical function that returns the trigonometric cosine of the specified - angle, in radians, in the specified expression
- cosh(X) - Hyperbolic cosine
- cot(X) - A mathematical function that returns the trigonometric cotangent of the - specified angle, in radians, in the specified double expression
- coth(X) - Hyperbolic cotangent
- difference(X,Y) - Returns an integer value that indicates the difference between the SOUNDEX - values of two character expressions
- degrees(X) - Converts radians to degrees
- exp(X) - Returns the exponential value of the specified expression
- floor(X) - Returns the largest integer less than or equal to the specified numeric - expression
- glob(X,Y) - This function is used to implement the "X GLOB Y" syntax of SQLite. The sqlite3_create_function() interface - can be used to override this function and thereby change the operation of the GLOB operator.
- ifnull(X,Y) - Return a copy of the first non-NULL argument. If both arguments are NULL then NULL - is returned. This behaves the same as coalesce() above.
- last_insert_rowid() - Return the ROWID of the last row insert from this connection to the database. This - is the same value that would be returned from the sqlite_last_insert_rowid() - API function.
- last_rows_affected() - Returns the number of rows affected by the last insert/update operation
- leftstr(X,Y) - Returns the leftmost Y characters in string X.
- length(X) - Return the string length of X in characters. If SQLite is configured to support - UTF-8, then the number of UTF-8 characters is returned, not the number of bytes.
- like(X,Y [,Z]) - This function is used to implement the "X LIKE Y [ESCAPE Z]" syntax of SQL. - If the optional ESCAPE clause is present, then the user-function is invoked with - three arguments. Otherwise, it is invoked with two arguments only. The - sqlite_create_function() interface can be used to override this function and - thereby change the operation of the LIKE operator. When doing - this, 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.
- load_extension(X)
- load_extension(X,Y)
- Load SQLite extensions out of the shared library file named X using the entry - point Y. The result is a NULL. If Y is omitted then the default entry - point of sqlite3_extension_init is used. This function raises an exception - if the extension fails to load or initialize correctly. -
- log(X) - Returns the natural logarithm of the specified double expression
- log10(X) - Returns the base-10 logarithm of the specified double expression
- lower(X) - Return a copy of string X will all characters converted to lower case. The - C library tolower() routine is used for the conversion, which means that - this function might not work correctly on UTF-8 characters.
- max(X,Y,...) - Return the argument with the maximum value. Arguments may be strings in addition - to numbers. The maximum value is determined by the usual sort order. Note that - max() is a simple function when it has 2 or more arguments but converts to - an aggregate function if given only a single argument.
- min(X,Y,...) - Return the argument with the minimum value. Arguments may be strings in addition - to numbers. The minimum value is determined by the usual sort order. Note that - min() is a simple function when it has 2 or more arguments but converts to - an aggregate function if given only a single argument.
- nullif(X,Y) - Return the first argument if the arguments are different, otherwise return NULL.
- padc(X,Y) - Pads the given string X on the left and the right with spaces until it is - the specified length Y
- padl(X,Y) - Pads the given string X on the left with spaces until it is the specified - length Y
- padr(X,Y) - Pads the given string X on the right with spaces until it is the - specified length Y
- pi - Returns the value of pi
- power(X,Y) - Returns the value of the specified expression X to the specified power - Y
- proper(X) - Proper-case the given string X
- quote(X) - This routine returns a string which is the value of its argument suitable for inclusion - into another SQL statement. Strings are surrounded by single-quotes with escapes - on interior quotes as needed. BLOBs are encoded as hexadecimal literals. The current - implementation of - VACUUM uses this function. The function is also useful when writing - triggers to implement undo/redo functionality. -
- radians(X) - Converts degrees to radians
- random(*) - Return a pseudo-random integer between -9223372036854775808 and +9223372036854775807.
- replace(X,Y,Z) - Replace all occurances of Y inside string X with the replacement - text Z.  Case-sensitive.
- replicate(X,Y) - Return the concatenation of string X repeated Y times
- reverse(X) - Returns the string X reversed
- rightstr(X,Y) - Returns the right-most Y characters in string X.
- round(X)
- round(X,Y)
- Round off the number X to Y digits to the right of the decimal point. - If the Y argument is omitted, 0 is assumed.
- sign(X) - Returns the positive (+1), zero (0), or negative (-1) sign of the specified - expression
- sin(X) - Returns the trigonometric sine of the specified angle, in radians, and in an - approximate numeric, double, expression
- soundex(X) - Compute the soundex encoding of the string X. The string "?000" is - returned if the argument is NULL.
- sqlite_version(*) - Return the version string for the SQLite library that is running. Example: "3.6.0"
- sqrt(X) - Returns the square root of the specified value
- square(X) - Returns the square of the specified value
- strfilter(X,Y) - Given a source string X and the characters to filter Y, returns - X with all characters not found in Y removed.
- substr(X,Y,Z) - Return a substring of input string X that begins with the Y-th character - and which is Z characters long. The left-most character of X is number - 1. If Y is negative the the first character of the substring is found by - counting from the right rather than the left. If SQLite is configured to support - UTF-8, then characters indices refer to actual UTF-8 characters, not bytes.
- tan(X) - Returns the tangent of the input expression
- tanh(X) - Hyperbolic tangent
- typeof(X) - Return the type of the expression X. The only return values are "null", "integer", - "real", "text", and "blob". - SQLite's type handling is explained in - Datatypes in SQLite Version 3.
- upper(X) - Return a copy of input string X converted to all upper-case letters. The - implementation of this function uses the C library routine toupper() which - means it may not work correctly on UTF-8 strings.
-

-

- Aggregate Functions -

-

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

-

- In any aggregate function that takes a single argument, that argument can be preceeded - 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. -

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- avg(X) - Return 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 even if all inputs are integers. -

-

-
- count(X)
- count(*)
- The first form return a count of the number of times that X is not NULL in - a group. The second form (with no argument) returns the total number of rows in - the group.
- lower_quartile(X) - Returns the lower quartile of the given numbers in the set
- max(X) - Return the maximum value of all values in the group. The usual sort order is used - to determine the maximum.
- median(X) - Returns the middle value in a set of ordered numbers. (The medial value is - unlike the mean value, which is the sum of a set of numbers divided by the count - of numbers in the set). The median value is determined by choosing the smallest - value such that at least half of the values in the set are no greater than the - chosen value. If the number of values within the set is odd, the median value - corresponds to a single value. If the number of values within the set is even, - the median value corresponds to the sum of the two middle values divided by two.
- min(X) - Return the minimum non-NULL value of all values in the group. The usual sort order - is used to determine the minimum. NULL is only returned if all values in the group - are NULL.
- mode(X) - Computes the most frequently occurring value in a sample set
- stdev(X) - Returns the statistical standard deviation of all values in the specified - expression
- sum(X)
- total(X)
- Return the numeric sum of all non-NULL values in the group. If there are no non-NULL - input rows then sum() returns NULL but total() returns 0.0. NULL is not normally - a helpful result for the sum of no rows but the SQL standard requires it and most - other SQL database engines implement sum() that way so SQLite does it in the same - way in order to be compatible. The non-standard total() function is provided as - a convenient way to work around this design problem in the SQL language. -

-

-

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

-

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

-
- upper_quartile(X) - Returns the upper quartile of the numbers in the given set
-

-
- -
-
- - + + + +SQLite Query Language: expression + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

expression

expr: +

+
+ syntax diagram expr +

literal-value: +

+ +

raise-function: +

+ +

select-stmt: +

+ +

type-name: +

+ +
+ + +

This section is different from the others. Most other sections of +this document talks about a particular SQL command. This section does +not talk about a standalone command but about "expressions" which are +subcomponents of most other commands.

+ + + +

Operators

+

SQLite understands the following binary operators, in order from +highest to lowest precedence:

+ +
+||
+*    /    %
++    -
+<<   >>   &    |
+<    <=   >    >=
+=    ==   !=   <>   IS   IS NOT   IN   LIKE   GLOB   MATCH   REGEXP
+AND   
+OR
+
+ +

Supported unary prefix operators are these:

+ +
+-    +    ~    NOT
+
+ + + +

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

+ + +

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

+ +

Note that there are two variations of the equals and not equals +operators. Equals can be either + += or ==. +The non-equals operator can be either +!= or <>. +The || operator is "concatenate" - it joins together +the two strings of its operands. +The operator % outputs the value of its left +operand modulo its right operand.

+ +

The result of any binary operator is either a numeric value or +NULL, except for the || concatenation operator which always +evaluates to either NULL or a text value.

+

The IS and IS NOT operators work +like = and != except when one or both of the +operands are NULL. In this case, if both operands are NULL, then the +IS operator evaluates to 1 (true) and the IS NOT operator evaluates +to 0 (false). If one operand is NULL and the other is not, then the +IS operator evaluates to 0 (false) and the IS NOT operator is 1 (true). +It is not possible for an IS or IS NOT expression to evaluate to NULL. +Operators IS and IS NOT have the same +precedence as =. + +

Literal Values

+

+A literal value is a constant of some kind. +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:

+ +

numeric-literal:

+ syntax diagram numeric-literal +
+ + +

+If a numeric literal has a decimal point or an exponentiation +clause, 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.

+ +

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

+ +
+X'53514C697465'
+
+ +

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

+ + + +

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

+ +
+ + + + + + + + + + + + + + + + + + + + + +
?NNNA 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. +
:AAAAA 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.
@AAAAAn "at" sign works exactly like a colon, except that the name of +the parameter created is @AAAA.
$AAAAA 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 maximum parameter number is set at compile-time by +the SQLITE_MAX_VARIABLE_NUMBER macro. An individual database connections +D can reduce its maximum parameter number below the compile-time maximum +using the sqlite3_limit(D, SQLITE_LIMIT_VARIABLE_NUMBER,...) interface. +

+ + + +

The LIKE and GLOB 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). (A bug: 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' LIKE 'A' +is TRUE but 'æ' LIKE 'Æ' is FALSE.)

+ +

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 BETWEEN operator

+

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

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 basic 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 IN and NOT IN operators

+

The IN and NOT IN operators take a single scalar operand on the +left and a vector operand on the right +formed by an explicit list of zero or more scalars or by a +single subquery. +When the right operand of an IN or NOT IN operator is a subquery, the +subquery must have a single result column. +When the right operand is an empty set, the result of IN is false and the +result of NOT IN is true, regardless of the left operand and even if the +left operand is NULL. +The result of an IN or NOT IN operator is determined by the following +matrix: + +

+ + + + + + + +
Left operand
is NULL +
Right operand
contains NULL +
Right operand
is an empty set +
Left operand found
within right operand +
Result of
IN operator +
Result of
NOT IN operator +
no +no +no +no +false +true +
does not matter +no +yes +no +false +true +
no +does not matter +no +yes +true +false +
no +yes +no +no +NULL +NULL +
yes +does not matter +no +does not matter +NULL +NULL +
+
+ +

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

+ + + +

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

Scalar Subqueries

+ +

A SELECT statement enclosed in parentheses may appear as a scalar +quantity. A SELECT used as a scalar quantity must return a result set +with a single column. The result of the expression is the value of the +only column in the first row returned by the SELECT statement. If the SELECT +yields more than one result row, all rows after the first are ignored. If +the SELECT yields no rows, then the value of the expression is NULL. +The LIMIT of a scalar subquery is always 1. +Any other LIMIT value given in the SQL text is ignored. + +

All types of SELECT statement, including aggregate and compound SELECT +queries (queries with keywords like UNION or EXCEPT) are allowed as scalar +subqueries. + +

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_". +These special identifiers all describe the +unique integer key (the rowid) associated with every +row of every table. +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.

+ +

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

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

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, 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 first does a forced + conversion into REAL but then further converts the result into INTEGER if + and only if the conversion from REAL to INTEGER is lossless and reversible. + This is the only context in SQLite where the NUMERIC and INTEGER affinities + behave differently. +

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

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 NULL or zero value (integer value 0 or real value 0.0) is +considered to be false. 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. + +

Functions

+

Both simple and aggregate functions are supported. +(For presentation purposes, simple functions are further subdivided into +core functions and date-time functions.) +A simple function can be used in any expression. Simple functions return +a result immediately based on their inputs. Aggregate functions +may only be used in a SELECT statement. Aggregate functions compute +their result across all rows of the result set.

+ + ADDED Doc/Extra/Core/lang_indexedby.html Index: Doc/Extra/Core/lang_indexedby.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_indexedby.html @@ -0,0 +1,198 @@ + + + +SQLite Query Language: INDEXED BY + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

INDEXED BY

+

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 extension that is particular to SQLite and +is not portable to other SQL database engines. +The INDEXED BY phrase can be seen in the following syntax +diagrams:

+ +

qualified-table-name: +

+
+ syntax diagram qualified-table-name +
+ + +

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 INTEGER PRIMARY KEY +can still be used to look up entries even when "NOT INDEXED" is specified.

+ +

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

+ +

The INDEXED BY clause is not intended for use in tuning +the performance of a query. The intent of the INDEXED BY clause is +to raise a run-time error if a schema change, such as dropping or +creating an index, causes the query plan for a time-sensitive query +to change. The INDEXED BY clause is designed to help detect +undesirable query plan changes during regression testing. +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.

+ +

See Also:

+ +
    +
  1. 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.

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

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

    +
+ +
Index: Doc/Extra/Core/lang_insert.html ================================================================== --- Doc/Extra/Core/lang_insert.html +++ Doc/Extra/Core/lang_insert.html @@ -1,108 +1,270 @@ - - - - INSERT - - - - -
-
-

- SQL As Understood By SQLite

-

- INSERT

-

- - - - - -
- sql-statement ::= - INSERT [OR - conflict-algorithm] INTO [database-name .] - table-name - [(column-list)] VALUES(value-list) - |
- INSERT
[OR - conflict-algorithm] - INTO [database-name .] - table-name - [(column-list)] select-statement
-

-

- The INSERT statement comes in two basic forms. The first form (with the "VALUES" - keyword) creates a single new row in an existing table. If no column-list is specified - then the number of values must be the same as the number of columns in the table. - If a column-list is specified, then the number of values must match the number of - specified columns. Columns of the table that do not appear in the column list are - filled with the default value, or with NULL if not default value is specified. -

-

- The second form of the INSERT statement takes it data - from a SELECT statement. The - number of columns in the result of the SELECT must exactly match the number of columns - in the table if no column list is specified, or it must match the number of columns - name in the column list. A new entry is made in the table for every row of the SELECT - result. The SELECT may be simple or compound. If the SELECT statement has an ORDER - BY clause, the ORDER BY is ignored.

-

- The optional conflict-clause allows the specification of an alternative constraint conflict resolution algorithm to use during this one command. See the section titled - ON CONFLICT for additional information. For compatibility - with MySQL, the parser allows the use of the single keyword - REPLACE as an alias for "INSERT OR REPLACE". -

-

-


-  

- -
-
- - + + + +SQLite Query Language: INSERT + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

INSERT

insert-stmt: +

+
+ syntax diagram insert-stmt +

expr: +

+ +

select-stmt: +

+ +

with-clause: +

+ +
+ + +

The INSERT statement comes in three basic forms. +

    +
  • The first form (with the "VALUES" keyword) creates one or more +new rows in +an existing table. If no column-list is specified 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 in each term of +the VALUES list is inserted into the left-most column of the each new row, +and forth for each subsequent expression. If a +column-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. + +

  • 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. + +

  • 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 optional conflict-clause allows the specification of an alternative +constraint conflict resolution algorithm to use during this one INSERT command. +See the section titled +ON CONFLICT for additional information. +For compatibility with MySQL, the parser allows the use of the +single keyword REPLACE as an +alias for "INSERT OR REPLACE". + +

The optional "database-name." prefix on the table-name +is support 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. +

+ + ADDED Doc/Extra/Core/lang_keywords.html Index: Doc/Extra/Core/lang_keywords.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_keywords.html @@ -0,0 +1,337 @@ + + + +SQLite Query Language: SQLite Keywords + + + + +

+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

SQLite Keywords

+ +

The SQL standard specifies a huge 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.
[keyword]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.
`keyword`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. +Regardless of the compile-time configuration, any identifier that is not on +the following 124 element +list is not a keyword to the SQL parser in SQLite: +

+ +
+ +
+ABORT
+ACTION
+ADD
+AFTER
+ALL
+ALTER
+ANALYZE
+AND
+AS
+ASC
+ATTACH
+AUTOINCREMENT
+BEFORE
+BEGIN
+BETWEEN
+BY
+CASCADE
+CASE
+CAST
+CHECK
+COLLATE
+COLUMN
+COMMIT
+CONFLICT
+CONSTRAINT
+
CREATE
+CROSS
+CURRENT_DATE
+CURRENT_TIME
+CURRENT_TIMESTAMP
+DATABASE
+DEFAULT
+DEFERRABLE
+DEFERRED
+DELETE
+DESC
+DETACH
+DISTINCT
+DROP
+EACH
+ELSE
+END
+ESCAPE
+EXCEPT
+EXCLUSIVE
+EXISTS
+EXPLAIN
+FAIL
+FOR
+FOREIGN
+
FROM
+FULL
+GLOB
+GROUP
+HAVING
+IF
+IGNORE
+IMMEDIATE
+IN
+INDEX
+INDEXED
+INITIALLY
+INNER
+INSERT
+INSTEAD
+INTERSECT
+INTO
+IS
+ISNULL
+JOIN
+KEY
+LEFT
+LIKE
+LIMIT
+MATCH
+
NATURAL
+NO
+NOT
+NOTNULL
+NULL
+OF
+OFFSET
+ON
+OR
+ORDER
+OUTER
+PLAN
+PRAGMA
+PRIMARY
+QUERY
+RAISE
+RECURSIVE
+REFERENCES
+REGEXP
+REINDEX
+RELEASE
+RENAME
+REPLACE
+RESTRICT
+RIGHT
+
ROLLBACK
+ROW
+SAVEPOINT
+SELECT
+SET
+TABLE
+TEMP
+TEMPORARY
+THEN
+TO
+TRANSACTION
+TRIGGER
+UNION
+UNIQUE
+UPDATE
+USING
+VACUUM
+VALUES
+VIEW
+VIRTUAL
+WHEN
+WHERE
+WITH
+WITHOUT
+ +
+ ADDED Doc/Extra/Core/lang_naming.html Index: Doc/Extra/Core/lang_naming.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_naming.html @@ -0,0 +1,177 @@ + + + +SQLite Query Language: Database Object Name Resolution + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

Database Object Name Resolution

+ +

+ 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 database name is specified as part of an object reference, it must be + either "main", or "temp" or the name of an attached database. Like other + SQL identifiers, database names are case-insensitive. If a database name + is specified, then only the named database 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. + + Index: Doc/Extra/Core/lang_reindex.html ================================================================== --- Doc/Extra/Core/lang_reindex.html +++ Doc/Extra/Core/lang_reindex.html @@ -1,99 +1,159 @@ - - - - REINDEX - - - -

-
-
-

- SQL As Understood By SQLite

-

- REINDEX

-

- - - - - -
- sql-statement ::= - REINDEX collation - name
- - - - - -
- sql-statement ::= - REINDEX [database-name .] table/index-name
-

-

- The REINDEX command is used to delete and recreate indices from scratch. This is - useful when the definition of a collation sequence has changed. -

-

- In the first form, all indices in all attached databases that use the named collation - sequence are recreated. In the second form, if [database-name.]table/index-name - identifies a table, then all indices associated with the table are rebuilt. If an - index is identified, then only this specific index is deleted and recreated. -

-

- If no database-name is specified and there exists both a table or index and - a collation sequence of the specified name, then indices associated with the collation - sequence only are reconstructed. This ambiguity may be dispelled by always specifying - a database-name when reindexing a specific table or index. -

-

-


-  

- -
-
- - + + + +SQLite Query Language: REINDEX + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

REINDEX

reindex-stmt: +

+
+ syntax diagram reindex-stmt +
+ + +

The REINDEX command is used to delete and recreate indices from scratch. +This is useful when the definition of a collation sequence 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. + +

If no database-name is specified and there exists both a table or +index and a collation sequence of the specified name, SQLite interprets +this as a request to rebuild the indices that use the named collation sequence. +This ambiguity in the syntax may be avoided by always specifying a +database-name when reindexing a specific table or index. + + Index: Doc/Extra/Core/lang_replace.html ================================================================== --- Doc/Extra/Core/lang_replace.html +++ Doc/Extra/Core/lang_replace.html @@ -1,86 +1,138 @@ - - - - REPLACE - - - -

-
-
-

- SQL As Understood By SQLite

-

- REPLACE

-

- - - - - -
- sql-statement ::= - REPLACE INTO [database-name .] table-name [( - column-list )] VALUES ( value-list ) |
- REPLACE INTO
[database-name .] - table-name - [( column-list )] - select-statement
-

-

- The REPLACE command is an alias for the "INSERT OR REPLACE" variant of the - INSERT command. This alias is provided for compatibility with MySQL. See the - INSERT command documentation for additional information.

-

-


-  

- -
-
- - + + + +SQLite Query Language: REPLACE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

REPLACE

+ +

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.

+ + ADDED Doc/Extra/Core/lang_savepoint.html Index: Doc/Extra/Core/lang_savepoint.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_savepoint.html @@ -0,0 +1,244 @@ + + + +SQLite Query Language: SAVEPOINT + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

SAVEPOINT

savepoint-stmt: +

+
+ syntax diagram savepoint-stmt +
+ + +

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

  • +
+ + + +

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.

+ + Index: Doc/Extra/Core/lang_select.html ================================================================== --- Doc/Extra/Core/lang_select.html +++ Doc/Extra/Core/lang_select.html @@ -1,244 +1,1141 @@ - - - - SELECT - - - - -
-
-

- SQL As Understood By SQLite

-

- SELECT

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- sql-statement ::= - SELECT [ALL - | DISTINCT] - result - [FROM table-list]
-
[WHERE expr]
-
[GROUP BY - expr-list]
-
[HAVING expr]
-
[compound-op select]*
-
[ORDER BY - sort-expr-list]
-
[LIMIT integer [( - OFFSET | , - ) integer]]
- result ::= - result-column [, - result-column]*
- result-column ::= - * | - table-name - . * | - expr - [ [AS] string - ]
- table-list ::= - table [join-op table - join-args]*
- table ::= - table-name [AS - alias] - |
- (
select - ) [AS - alias]
- join-op ::= - , | - [NATURAL] - [LEFT | - RIGHT | FULL] - [OUTER | - INNER | CROSS] JOIN
- join-args ::= - [ON expr] - [USING ( - id-list )]
- sort-expr-list ::= - expr [sort-order] [, - expr - [sort-order]]*
- sort-order ::= - [ COLLATE - collation-name - ] [ ASC - | DESC ]
- compound_op ::= - UNION | UNION - ALL | INTERSECT | EXCEPT
-

-

- 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. The number of - columns in the result is specified by the expression list in between the SELECT - and FROM keywords. Any arbitrary expression can be used as a result. If a result - expression is * then all columns of all - tables are substituted for that one expression. If the expression is the name of - a table followed by .* then the result is - all columns in that one table.

-

- The DISTINCT keyword causes a subset of result rows to be returned, in which each - result row is different. NULL values are not treated as distinct from each other. - The default behavior is that all result rows be returned, which can be made explicit - with the keyword ALL.

-

- The query is executed against one or more tables specified after the FROM keyword. - If multiple tables names are separated by commas, then the query is against the - cross join of the various tables. The full SQL-92 join syntax can also be used to - specify joins. A sub-query in parentheses may be substituted for any table name - in the FROM clause. The entire FROM clause may be omitted, in which case the result - is a single row consisting of the values of the expression list. -

-

- The WHERE clause can be used to limit the number of rows over which the query operates.

-

- The GROUP BY clauses causes one or more rows of the result to be combined into a - single row of output. This is especially useful when the result contains aggregate - functions. The expressions in the GROUP BY clause do not have to be expressions - that appear in the result. The HAVING clause is similar to WHERE except that HAVING - applies after grouping has occurred. The HAVING expression may refer to values, - even aggregate functions, that are not in the result.

-

- The ORDER BY clause causes the output rows to be sorted. The argument to ORDER BY - is a list of expressions that are used as the key for the sort. The expressions - do not have to be part of the result for a simple SELECT, but in a compound SELECT - each sort expression must exactly match one of the result columns. Each sort expression - may be optionally followed by a COLLATE keyword and the name of a collating function - used for ordering text and/or keywords ASC or DESC to specify the sort order.

-

- The LIMIT clause places an upper bound on the number of rows returned in the result. - A negative LIMIT indicates no upper bound. The optional OFFSET following LIMIT specifies - how many rows to skip at the beginning of the result set. In a compound query, the - LIMIT clause may only appear on the final SELECT statement. The limit is applied - to the entire query not to the individual SELECT statement to which it is attached. - Note that if the OFFSET keyword is used in the LIMIT clause, then the limit is the - first number and the offset is the second number. If a comma is used instead of - the OFFSET keyword, then the offset is the first number and the limit is the second - number. This seeming contradition is intentional - it maximizes compatibility with - legacy SQL database systems. -

-

- A compound SELECT is formed from two or more simple SELECTs connected by one of - the operators UNION, UNION ALL, INTERSECT, or EXCEPT. In a compound SELECT, all - the constituent SELECTs must specify the same number of result columns. There may - be only a single ORDER BY clause at the end of the compound SELECT. The UNION and - UNION ALL operators combine the results of the SELECTs to the right and left into - a single big table. The difference is that in UNION all result rows are distinct - where in UNION ALL there may be duplicates. The INTERSECT operator takes the intersection - of the results of the left and right SELECTs. EXCEPT takes the result of left SELECT - after removing the results of the right SELECT. When three or more SELECTs are connected - into a compound, they group from left to right.

-

-  

-
- -
-
- - + + + +SQLite Query Language: SELECT + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

SELECT

select-stmt: +

+
+ syntax diagram select-stmt +

common-table-expression: +

+ +

compound-operator: +

+ +

expr: +

+ +

join-clause: +

+ +

ordering-term: +

+ +

result-column: +

+ +

table-or-subquery: +

+ +
+ + + +

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 "select-stmt" 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 "factored-select-stmt" is an alternative +syntax diagrams that expresses the same syntax but tries to break the syntax +down into smaller chunks. + +

factored-select-stmt: +

+ + + +

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

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

Simple Select Processing

+ +

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

simple-select-stmt: +

+
+ syntax diagram simple-select-stmt +

common-table-expression: +

+ +

expr: +

+ +

ordering-term: +

+ +

select-core: +

+
+ syntax diagram select-core +

join-clause: +

+ +

result-column: +

+ +

table-or-subquery: +

+ +
+
+ + +

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

    +
  1. 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. +

  2. WHERE clause processing: The input data is filtered using the WHERE + clause expression. +

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

  4. DISTINCT/ALL keyword processing: If the query is a "SELECT + DISTINCT" query, duplicate rows are removed from the set of result rows. +

+ +

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

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

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

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

If a FROM clause is specified, the data on which a simple SELECT query +operates comes from the one or more tables or subqueries (SELECT statements +in parenthesis) 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 join-operator and +join-constraint 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×Nright +rows, each containing +Mleft+Mright columns. + +

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

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

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

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

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

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

+ +

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

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

2. WHERE clause filtering. + +

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

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

3. Generation of the set of result rows. + + + + +

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

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

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

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

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

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

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

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

    + +

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

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

+ +

4. Removal of duplicate rows (DISTINCT processing). + + + + +

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

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

compound-select-stmt: +

+
+ syntax diagram compound-select-stmt +

common-table-expression: +

+ +

expr: +

+ +

ordering-term: +

+ +

select-core: +

+ +
+ + +

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

+ + + +

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

Each ORDER BY expression is processed as follows:

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

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

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

    +
  1. If the ORDER BY expression is assigned a collation sequence using + the postfix COLLATE operator, then the specified collation sequence is + used. +

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

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

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

+ + + +

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

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". There is no advantage to using one form +over the other. Both forms yield the same result and both forms use +the same amount of memory and processing time. + +

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

+ + +

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. + + + Index: Doc/Extra/Core/lang_transaction.html ================================================================== --- Doc/Extra/Core/lang_transaction.html +++ Doc/Extra/Core/lang_transaction.html @@ -1,165 +1,277 @@ - - - - TRANSACTIONS - - - -

-
-
-

- SQL As Understood By SQLite

-

- BEGIN TRANSACTION

-

- - - - - -
- sql-statement ::= - BEGIN [ DEFERRED - | IMMEDIATE | EXCLUSIVE ] [TRANSACTION [name]]
- - - - - -
- sql-statement ::= - END [TRANSACTION - [name]]
- - - - - -
- sql-statement ::= - COMMIT [TRANSACTION - [name]]
- - - - - -
- sql-statement ::= - ROLLBACK [TRANSACTION - [name]]
-

-

- Beginning in version 2.0, SQLite supports transactions with rollback and atomic - commit.

-

- The optional transaction name is ignored. SQLite currently does not allow nested - transactions.

-

- No changes can be made to the database except within a transaction. Any command - that changes the database (basically, any SQL command - other than SELECT) will automatically start a transaction if one is not already in effect. Automatically started transactions - are committed at the conclusion of the command. -

-

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

-

- In SQLite version 3.0.8 and later, transactions can be deferred, immediate, or exclusive. - Deferred means that no locks are acquired on the database until the database is - first accessed. Thus with a deferred transaction, the BEGIN statement itself does - nothing. Locks are not acquired until the first read or write operation. The first - read operation against a database creates a SHARED lock and the first write operation - creates a RESERVED lock. Because the acquisition of locks is deferred until they - are needed, it is possible that another thread or process could create a separate - transaction and write to the database after the BEGIN on the current thread has - executed. If the transaction is immediate, then RESERVED locks are acquired on all - databases as soon as the BEGIN command is executed, without waiting for the database - to be used. After a BEGIN IMMEDIATE, you are guaranteed that no other thread or - process will be able to write to the database or do a BEGIN IMMEDIATE or BEGIN EXCLUSIVE. - Other processes can continue to read from the database, however. An exclusive transaction - causes EXCLUSIVE locks to be acquired on all databases. After a BEGIN EXCLUSIVE, - you are guaranteed that no other thread or process will be able to read or write - the database until the transaction is complete. -

-

- A description of the meaning of SHARED, RESERVED, and EXCLUSIVE locks is available - separately. -

-

- The default behavior for SQLite version 3.0.8 is a deferred transaction. For SQLite - version 3.0.0 through 3.0.7, deferred is the only kind of transaction available. - For SQLite version 2.8 and earlier, all transactions are exclusive. -

-

- The COMMIT command does not actually perform a commit until all pending SQL commands - finish. Thus if two or more SELECT statements are in the middle of processing and - a COMMIT is executed, the commit will not actually occur until all SELECT statements - finish. -

-

- An attempt to execute COMMIT might result in an SQLITE_BUSY return code. This indicates - that another thread or process had a read lock on the database that prevented the - database from being updated. 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. -

-

-


-  

- -
-
- - + + + +SQLite Query Language: BEGIN TRANSACTION + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

BEGIN TRANSACTION

begin-stmt: +

+
+ syntax diagram begin-stmt +
+ + +

+No changes can be made to the database except within a transaction. +Any command that changes the database (basically, any SQL command +other than SELECT) will automatically start a transaction if +one is not already in effect. Automatically started transactions +are committed when the last query 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.

+ + + +

+Transactions can be deferred, immediate, or exclusive. +The default transaction behavior is deferred. +Deferred means that no locks are acquired +on the database until the database is first accessed. Thus with a +deferred transaction, the BEGIN statement itself does nothing to the +filesystem. Locks +are not acquired until the first read or write operation. The first read +operation against a database creates a SHARED lock and the first +write operation creates a RESERVED lock. Because the acquisition of +locks is deferred until they are needed, it is possible that another +thread or process could create a separate transaction and write to +the database after the BEGIN on the current thread has executed. +If the transaction is immediate, then RESERVED locks +are acquired on all databases as soon as the BEGIN command is +executed, without waiting for the +database to be used. After a BEGIN IMMEDIATE, +no other database connection will be able to write to the database or +do a BEGIN IMMEDIATE or BEGIN EXCLUSIVE. Other processes can continue +to read from the database, however. An exclusive transaction causes +EXCLUSIVE locks to be acquired on all databases. After a BEGIN +EXCLUSIVE, no other database connection except for read_uncommitted +connections will be able to read the database and no other connection without +exception will be able to write the database until the transaction is +complete. +

+ +

+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 +prepared statement is reset or +finalized. An open sqlite3_blob used for +incremental BLOB I/O 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 a shared lock on the database +that prevented the database from being updated. 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. +

+ +

+The ROLLBACK will fail with an error code SQLITE_BUSY if there +are any pending queries. Both read-only and read/write queries will +cause a ROLLBACK to fail. A ROLLBACK must fail if there are pending +read operations (unlike COMMIT which can succeed) because bad things +will happen if the in-memory image of the database is changed out from under +an active query. +

+ +

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

+ +

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:

+ + + +

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

+ + DELETED Doc/Extra/Core/lang_types.html Index: Doc/Extra/Core/lang_types.html ================================================================== --- Doc/Extra/Core/lang_types.html +++ /dev/null @@ -1,135 +0,0 @@ - - - - TYPES - - - - -
-
-

- SQL As Understood By SQLite (sortof)

-

- TYPES

-

- - - - - - - - - -
- sql-statement ::= - TYPES [datatype name][,datatype name][,datatype - name][,...] ; select-stmt
- select-stmt ::= - see SELECT
-

-

- Use the TYPES keyword before a SELECT statement to provide the SQLite ADO.NET provider - a list of return datatypes to expect from the subsequent SELECT statement.  -

-

- This is a language extension (aka hack) to SQLite specifically for the ADO.NET data - provider.  It is a pseudo-statement, meaning only the ADO.NET provider understands - it.

-

- Background

-

- Due to SQLite's typeless nature, there are certain kinds of queries for which the - ADO.NET provider cannot determine the proper return data type.  Scalar and - aggregate functions pose a particular problem because - there is no requirement for a given scalar or aggregate function to return any particular - datatype.  As a matter of fact, scalar functions could theoretically return - a different datatype for every row or column in a query and this is perfectly legal - from SQLite's point of view.

-

- Since ADO.NET is designed around a typed system and we're shoe-horning SQLite into - it, this keyword helps the provider out in cases where the return type cannot be easily determined.

-

- This command must be used in conjunction with a SELECT statement.  It only - works when both the TYPES keyword and its value(s) are passed along with a SELECT - statement as a single semi-colon separated unit.

-

- Examples

-

- TYPES [bigint], [int], [smallint], [tinyint];
- SELECT 1, 2, 3, 4;

-

- The above query would return the columns as types System.Int64, System.Int32, System.Int16 - and System.Byte respectively.

-

- TYPES [bigint], [int], , [tinyint];
- SELECT 1, 2, 3, 4;

-

- In this sample, only columns 1, 2 and 4 would have explicit typing.  Column - 3's datatype would pass though the system and be discovered normally.

-

- TYPES real;
- SELECT SUM(Cost) FROM [Products];

-

- The above query explicitly tells the provider that the SUM aggregate function returns - a System.Double.

-

- Usage Notes

-
    -
  • You cannot use parameters in the TYPES statement.
  • -
  • The TYPES statement must be immediately followed by a SELECT statement.
  • -
  • It is legal to pass multiple TYPES and SELECT statements in a multi-statement - command.
  • -
  • You may enclose datatypes in quotes "" or brackets [] - or those `` thingies if you want.
    -
  • -
-
- -
-
- - Index: Doc/Extra/Core/lang_update.html ================================================================== --- Doc/Extra/Core/lang_update.html +++ Doc/Extra/Core/lang_update.html @@ -1,100 +1,351 @@ - - - - UPDATE - - - - -
-
-

- SQL As Understood By SQLite

-

- UPDATE

-

- - - - - - - - - -
- sql-statement ::= - UPDATE [ OR - conflict-algorithm - ] [database-name .] table-name
- SET
assignment - [, - assignment]*
-
[WHERE expr]
- assignment ::= - column-name = expr
-

-

- The UPDATE statement is used to change the value of columns in selected rows of - a table. Each assignment in an UPDATE specifies a column - name to the left of the - equals sign and an arbitrary expression to the right. The expressions may use the - values of - other columns. All expressions are evaluated before any assignments are - made. A WHERE clause can be used to restrict which rows are updated.

-

- The optional conflict-clause allows the specification of an alternative constraint conflict resolution algorithm to use during this one command. See the section titled - ON CONFLICT for additional information.

-

-


-  

- -
-
- - + + + +SQLite Query Language: UPDATE + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

UPDATE

update-stmt: +

+
+ syntax diagram update-stmt +

expr: +

+ +

qualified-table-name: +

+ +

with-clause: +

+ +
+ + +

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 +qualified-table-name specified as part of the UPDATE statement. + +

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 result of evaluating the WHERE clause expression as a +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. + +

The optional conflict-clause 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. + +

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 + database-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. +

+ +

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:

+ +

update-stmt-limited:

+ syntax diagram update-stmt-limited +
+ + +

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. + + Index: Doc/Extra/Core/lang_vacuum.html ================================================================== --- Doc/Extra/Core/lang_vacuum.html +++ Doc/Extra/Core/lang_vacuum.html @@ -1,96 +1,195 @@ - - - - TYPES - - - -

-
-
-

- SQL As Understood By SQLite

-

- VACUUM

-

- - - - - -
- sql-statement ::= - VACUUM [index-or-tablename]
-

-

- The VACUUM command is an SQLite extension modeled after a similar command found - in PostgreSQL. If VACUUM is invoked with the name of a table or index then it is - suppose to clean up the named table or index. In version 1.0 of SQLite, the VACUUM - command would invoke gdbm_reorganize() to clean up the backend database file.

-

- VACUUM became a no-op when the GDBM backend was removed from SQLITE in version 2.0.0. - VACUUM was reimplemented in version 2.8.1. The index or table name argument is now - ignored. -

-

- When an object (table, index, or trigger) is dropped from the database, it leaves - behind empty space. This makes the database file larger than it needs to be, but - can speed up inserts. In time inserts and deletes can leave the database file structure - fragmented, which slows down disk access to the database contents. The VACUUM command - cleans the main database by copying its contents to a temporary database file and - reloading the original database file from the copy. This eliminates free pages, - aligns table data to be contiguous, and otherwise cleans up the database file structure. - It is not possible to perform the same process on an attached database file.

-

- This command will fail if there is an active transaction. This command has no effect - on an in-memory database.

-

- As of SQLite version 3.1, an alternative to using the VACUUM command is auto-vacuum - mode, enabled using the auto_vacuum pragma.

-

-  

-
- -
-
- - + + + +SQLite Query Language: VACUUM + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

VACUUM

vacuum-stmt: +

+
+ syntax diagram vacuum-stmt +
+ + +

+ The VACUUM command rebuilds the entire database. 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. + +

  • 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. +

+ +

VACUUM only works on the main database. It is not possible to VACUUM an +attached database file. + +

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 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, or if there are one or +more active SQL statements when it is run. + +

As of SQLite version 3.1, 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. + +

+ + + ADDED Doc/Extra/Core/lang_with.html Index: Doc/Extra/Core/lang_with.html ================================================================== --- /dev/null +++ Doc/Extra/Core/lang_with.html @@ -0,0 +1,796 @@ + + + +SQLite Query Language: WITH clause + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ +

SQL As Understood By SQLite

[Top]

WITH clause

with-clause: +

+
+ syntax diagram with-clause +

cte-table-name: +

+ +

select-stmt: +

+ +
+ + +

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 expression +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. + + + +

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

Recursive Common Table Expressions

+ +

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

    +
  1. The "select-stmt" + must be a compound select where the right-most compound-operator is + either UNION or UNION ALL. +
  2. The table named on the left-hand side of the AS keyword must appear + exactly once in the FROM clause of the right-most SELECT statement + of the compound select, and nowhere else. +
+ +

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

recursive-cte: +

+
+ syntax diagram recursive-cte +

cte-table-name: +

+ +
+ + +

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

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

    +
  1. Run the initial-select and add the results to a queue. +
  2. While the queue is not empty: +
      +
    1. Extract a single row from the queue. +
    2. Insert that single row into the recursive table +
    3. 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; 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.) +

+ + + +

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

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;
+
+ + + +

Queries Against A Graph

+ +

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

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

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

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

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

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

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.name=under_alice.boss
+     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.name=under_alice.boss
+     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. + + + + +

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<1.2),
+  yaxis(y) AS (VALUES(-1.0) UNION ALL SELECT y+0.1 FROM yaxis WHERE y<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) < 4.0 AND iter<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 into 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<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. + +

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

+ + Index: Doc/Extra/Core/pragma.html ================================================================== --- Doc/Extra/Core/pragma.html +++ Doc/Extra/Core/pragma.html @@ -1,644 +1,1545 @@ - - - - PRAGMA - - - - -
-
-

- SQL As Understood By SQLite

-

- PRAGMA

-

- The PRAGMA command is a special command used to modify the - operation of the SQLite library or to query the library for internal (non-table) - data. The PRAGMA command is issued using the same interface as other SQLite commands - (e.g. SELECT, INSERT) but is different in the following important respects: -

-
    -
  • Specific pragma statements may be removed and others added in future releases - of SQLite. Use with caution!
  • -
  • No error messages are generated if an unknown pragma is issued. Unknown pragmas - are simply ignored. This means if there is a typo in a pragma statement the library - does not inform the user of the fact.
  • -
  • Some pragmas take effect during the SQL compilation stage, not the execution stage. - This means if using the C-language sqlite3_compile(), sqlite3_step(), sqlite3_finalize() - API (or similar in a wrapper interface), the pragma may be applied to the library - during the sqlite3_compile() call.
  • -
  • The pragma command is unlikely to be compatible with any other SQL engine.
  • -
-

- The available pragmas fall into four basic categories:

- -
- -

- PRAGMA command syntax

-

- - - - - -
- sql-statement ::= - PRAGMA name [= - value] - |
- PRAGMA
function(arg)
-

-

- The pragmas that take an integer value also accept symbolic names. - The strings "on", "true", and "yes" are equivalent to 1. - The strings "off", "false", and "no" are equivalent to 0. - These strings are case- insensitive, and do not require quotes. An unrecognized - string will be treated as 1, and will not generate an error. When the value - is returned it is as an integer.

-
- -

- Pragmas to modify library operation

-
    - -
  • -

    - PRAGMA auto_vacuum; -
    - PRAGMA auto_vacuum =
    0 | 1;

    -

    - Query or set the auto-vacuum flag in the database.

    -

    - Normally, when a transaction that deletes data from a database is committed, the - database file remains the same size. Unused database file pages are marked as such - and reused later on, when data is inserted into the database. In this mode the VACUUM command is used to reclaim unused space.

    -

    - When the auto-vacuum flag is set, the database file shrinks when a transaction that - deletes data is committed (The VACUUM command is not useful in a database with the - auto-vacuum flag set). To support this functionality the database stores extra information - internally, resulting in slightly larger database files than would otherwise be - possible.

    -

    - It is only possible to modify the value of the auto-vacuum flag before any tables - have been created in the database. No error message is returned if an attempt to - modify the auto-vacuum flag is made after one or more tables have been created. -

    -
  • -
  • -

    - PRAGMA cache_size; -
    - PRAGMA cache_size =
    Number-of-pages;

    -

    - Query or change the maximum number of database disk pages that SQLite will hold - in memory at once. Each page uses about 1.5K of memory. The default cache size is - 2000. If you are doing UPDATEs or DELETEs that change many rows of a database and - you do not mind if SQLite uses more memory, you can increase the cache size for - a possible speed improvement.

    -

    - When you change the cache size using the cache_size pragma, the change only endures - for the current session. The cache size reverts to the default value when the database - is closed and reopened. Use the default_cache_size - pragma to check the cache size permanently.

    -
  • -
  • -

    - PRAGMA case_sensitive_like; -
    - PRAGMA case_sensitive_like =
    0 | 1;

    -

    - The default behavior of the LIKE operator is to ignore case for latin1 characters. - Hence, by default 'a' LIKE 'A' is true. The case_sensitive_like pragma can - be turned on to change this behavior. When case_sensitive_like is enabled, 'a' - LIKE 'A' is false but 'a' LIKE 'a' is still true.

    -
  • -
  • -

    - PRAGMA count_changes; -
    - PRAGMA count_changes =
    0 | 1;

    -

    - Query or change the count-changes flag. Normally, when the count-changes flag is - not set, INSERT, UPDATE and DELETE statements return no data. When count-changes - is set, each of these commands returns a single row of data consisting of one integer - value - the number of rows inserted, modified or deleted by the command. The returned - change count does not include any insertions, modifications or deletions performed - by triggers.

    -
  • -
  • -

    - PRAGMA default_cache_size; -
    - PRAGMA default_cache_size =
    Number-of-pages;

    -

    - Query or change the maximum number of database disk pages that SQLite will hold - in memory at once. Each page uses 1K on disk and about 1.5K in memory. This pragma - works like the cache_size pragma with the - additional feature that it changes the cache size persistently. With this pragma, - you can set the cache size once and that setting is retained and reused every time - you reopen the database.

    -
  • -
  • -

    - PRAGMA default_synchronous;

    -

    - This pragma was available in version 2.8 but was removed in version 3.0. It is a - dangerous pragma whose use is discouraged. To help dissuide users of version 2.8 - from employing this pragma, the documentation will not tell you what it does.

    -
  • -
  • -

    - PRAGMA empty_result_callbacks; -
    - PRAGMA empty_result_callbacks =
    0 | 1;

    -

    - Query or change the empty-result-callbacks flag.

    -

    - The empty-result-callbacks flag affects the sqlite3_exec API only. Normally, when - the empty-result-callbacks flag is cleared, the callback function supplied to the - sqlite3_exec() call is not invoked for commands that return zero rows of data. When - empty-result-callbacks is set in this situation, the callback function is invoked - exactly once, with the third parameter set to 0 (NULL). This is to enable programs - that use the sqlite3_exec() API to retrieve column-names even when a query returns - no data. -

    -
  • -
  • -

    - PRAGMA encoding; -
    - PRAGMA encoding = "UTF-8"; -
    - PRAGMA encoding = "UTF-16"; -
    - PRAGMA encoding = "UTF-16le"; -
    - PRAGMA encoding = "UTF-16be";

    -

    - In first form, if the main database has already been created, then this pragma returns - the text encoding used by the main database, one of "UTF-8", "UTF-16le" (little-endian - UTF-16 encoding) or "UTF-16be" (big-endian UTF-16 encoding). If the main database - has not already been created, then the value returned is the text encoding that - will be used to create the main database, if it is created by this session.

    -

    - The second and subsequent forms of this pragma are only useful if the main database - has not already been created. In this case the pragma sets the encoding that the - main database will be created with if it is created by this session. The string - "UTF-16" is interpreted as "UTF-16 encoding using native machine byte-ordering". - If the second and subsequent forms are used after the database file has already - been created, they have no effect and are silently ignored.

    -

    - Once an encoding has been set for a database, it cannot be changed.

    -

    - Databases created by the ATTACH command always use the same encoding as the main - database.

    -
  • -
  • -

    - PRAGMA full_column_names; -
    - PRAGMA full_column_names =
    0 | 1;

    -

    - Query or change the full-column-names flag. This flag affects the way SQLite names - columns of data returned by SELECT statements when the expression for the column - is a table-column name or the wildcard "*". Normally, such result columns are named - <table-name/alias><column-name> if the SELECT statement joins two or - more tables together, or simply <column-name> if the SELECT statement queries - a single table. When the full-column-names flag is set, such columns are always - named <table-name/alias> <column-name> regardless of whether or not - a join is performed. -

    -

    - If both the short-column-names and full-column-names are set, then the behaviour - associated with the full-column-names flag is exhibited. -

    -
  • -
  • -

    - PRAGMA fullfsync -
    - PRAGMA fullfsync =
    0 | 1;

    -

    - Query or change the fullfsync flag. This flag affects determines whether or not - the F_FULLFSYNC syncing method is used on systems that support it. The default value - is off. As of this writing (2006-02-10) only Mac OS X supports F_FULLFSYNC. -

    -
  • -
  • -

    - PRAGMA legacy_file_format; -
    - PRAGMA legacy_file_format = ON | OFF

    -

    - This pragma sets or queries the value of the legacy_file_format flag. When this - flag is on, new SQLite databases are created in a file format that is readable and - writable by all versions of SQLite going back to 3.0.0. When the flag is off, new - databases are created using the latest file format which might to be readable or - writable by older versions of SQLite.

    -

    - This flag only effects newly created databases. It has no effect on databases that - already exists.

    -
  • -
  • -

    - PRAGMA page_size; -
    - PRAGMA page_size =
    bytes;

    -

    - Query or set the page-size of the database. The page-size may only be set if the - database has not yet been created. The page size must be a power of two greater - than or equal to 512 and less than or equal to 8192. The upper limit may be modified - by setting the value of macro SQLITE_MAX_PAGE_SIZE during compilation. The maximum - upper bound is 32768. -

    -
  • -
  • -

    - PRAGMA read_uncommitted; -
    - PRAGMA read_uncommitted =
    0 | 1;

    -

    - Query, set, or clear READ UNCOMMITTED isolation. The default isolation level for - SQLite is SERIALIZABLE. Any process or thread can select READ UNCOMMITTED isolation, - but SERIALIZABLE will still be used except between connections that share a common - page and schema cache. Cache sharing is enabled using the - sqlite3_enable_shared_cache() API and is only available between connections - running the same thread. Cache sharing is off by default. -

    -
  • -
  • -

    - PRAGMA short_column_names; -
    - PRAGMA short_column_names =
    0 | 1;

    -

    - Query or change the short-column-names flag. This flag affects the way SQLite names - columns of data returned by SELECT statements when the expression for the column - is a table-column name or the wildcard "*". Normally, such result columns are named - <table-name/alias>lt;column-name> if the SELECT statement joins two or - more tables together, or simply <column-name> if the SELECT statement queries - a single table. When the short-column-names flag is set, such columns are always - named <column-name> regardless of whether or not a join is performed. -

    -

    - If both the short-column-names and full-column-names are set, then the behaviour - associated with the full-column-names flag is exhibited. -

    -
  • -
  • -

    - PRAGMA synchronous; -
    - PRAGMA synchronous = FULL;
    (2) -
    - PRAGMA synchronous = NORMAL;
    (1) -
    - PRAGMA synchronous = OFF;
    (0)

    -

    - Query or change the setting of the "synchronous" flag. The first (query) form will - return the setting as an integer. When synchronous is FULL (2), the SQLite database - engine will pause at critical moments to make sure that data has actually been written - to the disk surface before continuing. This ensures that if the operating system - crashes or if there is a power failure, the database will be uncorrupted after rebooting. - FULL synchronous is very safe, but it is also slow. When synchronous is NORMAL, - the SQLite database engine will still pause at the most critical moments, but less - often than in FULL mode. There is a very small (though non-zero) chance that a power - failure at just the wrong time could corrupt the database in NORMAL mode. But in - practice, you are more likely to suffer a catastrophic disk failure or some other - unrecoverable hardware fault. With synchronous OFF (0), SQLite continues without - pausing as soon as it has handed data off to the operating system. If the application - running SQLite crashes, the data will be safe, but the database might become corrupted - if the operating system crashes or the computer loses power before that data has - been written to the disk surface. On the other hand, some operations are as much - as 50 or more times faster with synchronous OFF. -

    -

    - In SQLite version 2, the default value is NORMAL. For version 3, the default was - changed to FULL. -

    -
  • -
  • -

    - PRAGMA temp_store; -
    - PRAGMA temp_store = DEFAULT;
    (0) -
    - PRAGMA temp_store = FILE;
    (1) -
    - PRAGMA temp_store = MEMORY;
    (2)

    -

    - Query or change the setting of the "temp_store" parameter. When temp_store - is DEFAULT (0), the compile-time C preprocessor macro TEMP_STORE is used to determine - where temporary tables and indices are stored. When temp_store is MEMORY (2) temporary - tables and indices are kept in memory. When temp_store is FILE (1) temporary tables - and indices are stored in a file. The temp_store_directory - pragma can be used to specify the directory containing this file. FILE is - specified. When the temp_store setting is changed, all existing temporary tables, - indices, triggers, and views are immediately deleted.

    -

    - It is possible for the library compile-time C preprocessor symbol TEMP_STORE to - override this pragma setting. The following table summarizes the interaction of - the TEMP_STORE preprocessor macro and the temp_store pragma:

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - TEMP_STORE - PRAGMA
    - temp_store
    - Storage used for
    - TEMP tables and indices
    - 0 - any - file
    - 1 - 0 - file
    - 1 - 1 - file
    - 1 - 2 - memory
    - 2 - 0 - memory
    - 2 - 1 - file
    - 2 - 2 - memory
    - 3 - any - memory
    -
    -
    -
  • -
  • -

    - PRAGMA temp_store_directory; -
    - PRAGMA temp_store_directory = 'directory-name';

    -

    - Query or change the setting of the "temp_store_directory" - the directory where - files used for storing temporary tables and indices are kept. This setting lasts - for the duration of the current connection only and resets to its default value - for each new connection opened. -

    -

    - When the temp_store_directory setting is changed, all existing temporary tables, - indices, triggers, and viewers are immediately deleted. In practice, temp_store_directory - should be set immediately after the database is opened. -

    -

    - The value directory-name should be enclosed in single quotes. To revert the - directory to the default, set the directory-name to an empty string, e.g., - PRAGMA temp_store_directory = ''. An error is raised if directory-name - is not found or is not writable. -

    -

    - The default directory for temporary files depends on the OS. For Unix/Linux/OSX, - the default is the is the first writable directory found in the list of: /var/tmp, - /usr/tmp, /tmp, and current-directory. For Windows NT, the default - directory is determined by Windows, generally C:\Documents and Settings\user-name\Local - Settings\Temp\. Temporary files created by SQLite are unlinked immediately - after opening, so that the operating system can automatically delete the files when - the SQLite process exits. Thus, temporary files are not normally visible through - ls or dir commands.

    -
  • -
-
- -

- Pragmas to query the database schema

-
    - -
  • -

    - PRAGMA database_list;

    -

    - For each open database, invoke the callback function once with information about - that database. Arguments include the index and the name the database was attached - with. The first row will be for the main database. The second row will be for the - database used to store temporary tables.

    -
  • -
  • -

    - PRAGMA foreign_key_list(table-name);

    -

    - For each foreign key that references a column in the argument table, invoke the - callback function with information about that foreign key. The callback function - will be invoked once for each column in each foreign key.

    -
  • -
  • -

    - PRAGMA index_info(index-name);

    -

    - For each column that the named index references, invoke the callback function once - with information about that column, including the column name, and the column number.

    -
  • -
  • -

    - PRAGMA index_list(table-name);

    -

    - For each index on the named table, invoke the callback function once with information - about that index. Arguments include the index name and a flag to indicate whether - or not the index must be unique.

    -
  • -
  • -

    - PRAGMA table_info(table-name);

    -

    - For each column in the named table, invoke the callback function once with information - about that column, including the column name, data type, whether or not the column - can be NULL, and the default value for the column.

    -
  • -
-
- -

- Pragmas to query/modify version values

-
    - -
  • -

    - PRAGMA [database.]schema_version; -
    - PRAGMA [database.]schema_version =
    integer ; -
    - PRAGMA [database.]user_version; -
    - PRAGMA [database.]user_version =
    integer ; -

    -

    - The pragmas schema_version and user_version are used to set or get the value of - the schema-version and user-version, respectively. Both the schema-version and the - user-version are 32-bit signed integers stored in the database header.

    -

    - The schema-version is usually only manipulated internally by SQLite. It is incremented - by SQLite whenever the database schema is modified (by creating or dropping a table - or index). The schema version is used by SQLite each time a query is executed to - ensure that the internal cache of the schema used when compiling the SQL query matches - the schema of the database against which the compiled query is actually executed. - Subverting this mechanism by using "PRAGMA schema_version" to modify the schema-version - is potentially dangerous and may lead to program crashes or database corruption. - Use with caution!

    -

    - The user-version is not used internally by SQLite. It may be used by applications - for any purpose.

    -
  • -
-
- -

- Pragmas to debug the library

-
    - -
  • -

    - PRAGMA integrity_check;

    -

    - The command does an integrity check of the entire database. It looks for out-of-order - records, missing pages, malformed records, and corrupt indices. If any problems - are found, then a single string is returned which is a description of all problems. - If everything is in order, "ok" is returned.

    -
  • -
  • -

    - PRAGMA parser_trace = ON; (1) -
    - PRAGMA parser_trace = OFF;
    (0)

    -

    - Turn tracing of the SQL parser inside of the SQLite library on and off. This is - used for debugging. This only works if the library is compiled without the NDEBUG - macro. -

    -
  • -
  • -

    - PRAGMA vdbe_trace = ON; (1) -
    - PRAGMA vdbe_trace = OFF;
    (0)

    -

    - Turn tracing of the virtual database engine inside of the SQLite library on and - off. This is used for debugging. See the VDBE documentation - for more information.

    -
  • -
  • -

    - PRAGMA vdbe_listing = ON; (1) -
    - PRAGMA vdbe_listing = OFF;
    (0)

    -

    - Turn listings of virtual machine programs on and off. With listing is on, the entire - content of a program is printed just prior to beginning execution. This is like - automatically executing an EXPLAIN prior to each statement. The statement executes - normally after the listing is printed. This is used for debugging. See the - VDBE documentation for more information.

    -
  • -
-

-


-  

- -
-
- - + + + +Pragma statements supported by SQLite + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ + +

PRAGMA Statements

+ + + +

The PRAGMA statement is an SQL extension specific to SQLite and used to +modify the operation of the SQLite library or to query the SQLite library for +internal (non-table) data. The PRAGMA statement is issued using the same +interface as other SQLite commands (e.g. SELECT, INSERT) but is +different in the following important respects: +

+
    +
  • Specific pragma statements may be removed and others added in future + releases of SQLite. There is no guarantee of backwards compatibility. +
  • No error messages are generated if an unknown pragma is issued. + Unknown pragmas are simply ignored. This means if there is a typo in + a pragma statement the library does not inform the user of the fact. +
  • Some pragmas take effect during the SQL compilation stage, not the + execution stage. This means if using the C-language sqlite3_prepare(), + sqlite3_step(), sqlite3_finalize() API (or similar in a wrapper + interface), the pragma may run during the sqlite3_prepare() call, + not during the sqlite3_step() call as normal SQL statements do. + Or the pragma might run during sqlite3_step() just like normal + SQL statements. Whether or not the pragma runs during sqlite3_prepare() + or sqlite3_step() depends on the pragma and on the specific release + of SQLite. +
  • The pragma command is specific to SQLite and is very unlikely + to be compatible with any other SQL database engine. +
+ +

The C-language API for SQLite provides the SQLITE_FCNTL_PRAGMA +file control which gives VFS implementations the +opportunity to add new PRAGMA statements or to override the meaning of +built-in PRAGMA statements.

+ + +
+

PRAGMA command syntax

+

pragma-stmt: +

+
+ syntax diagram pragma-stmt +

pragma-value: +

+
+ syntax diagram pragma-value +

signed-number: +

+ +
+
+ + +

+A pragma can take either zero or one argument. The argument is may be either +in parentheses or it may be separated from the pragma name by an equal sign. +The two syntaxes yield identical results. +In many pragmas, the argument is a boolean. The boolean can be one of: +

+ +
+1 yes true on
0 no false off
+
+ +

Keyword arguments can optionally appear in quotes. +(Example: 'yes' [FALSE].) Some pragmas +takes a string literal as their argument. When pragma takes a keyword +argument, it will usually also take a numeric equivalent as well. +For example, "0" and "no" mean the same thing, as does "1" and "yes". +When querying the value of a setting, many pragmas return the number +rather than the keyword.

+ +

A pragma may have an optional database name before the pragma name. +The database name is the name of an ATTACH-ed database or it can be +"main" or "temp" for the main and the TEMP databases. If the optional +database name is omitted, "main" is assumed. In some pragmas, the database +name is meaningless and is simply ignored.

+ + + +
+

List Of PRAGMAs

+ + +
+

Notes: +

    +
  1. Pragmas whose names are marked through in the list above +are deprecated that are maintained for historical compatibility only. +Do not use the deprecated pragmas in new applications. +Remove deprecated pragmas +from existing applications at your earliest opportunity. +
  2. These pragmas are used for debugging SQLite itself and +are only available when SQLite is compiled using SQLITE_DEBUG.

+ +
+

PRAGMA application_id; +
PRAGMA application_id =
integer ; + +

The application_id PRAGMA is used to query or set the 32-bit + unsigned big-endian "Application ID" integer located at offset + 68 into the database header. Applications that use SQLite as their + application file-format should set the Application ID integer to + a unique integer so that utilities such as + file(1) can determine the specific + file type rather than just reporting "SQLite3 Database". A list of + assigned application IDs can be seen by consulting the + magic.txt file in the SQLite source repository. + +


+

PRAGMA auto_vacuum;
+ PRAGMA auto_vacuum =
+ 0 | NONE | 1 | FULL | 2 | INCREMENTAL;

+ +

Query or set the auto-vacuum status in the database.

+ +

The default setting for auto-vacuum is 0 or "none", + unless the SQLITE_DEFAULT_AUTOVACUUM compile-time option is used. + The "none" setting means that auto-vacuum is disabled. + When auto-vacuum is disabled and data is deleted data from a database, + the database file remains the same size. Unused database file + pages are added to a "freelist" and reused for subsequent inserts. So + no database file space is lost. However, the database file does not + shrink. In this mode the VACUUM + command can be used to rebuild the entire database file and + thus reclaim unused disk space.

+ +

When the auto-vacuum mode is 1 or "full", the freelist pages are + moved to the end of the database file and the database file is truncated + to remove the freelist pages at every transaction commit. + Note, however, that auto-vacuum only truncates the freelist pages + from the file. Auto-vacuum does not defragment the database nor + repack individual database pages the way that the + VACUUM command does. In fact, because + it moves pages around within the file, auto-vacuum can actually + make fragmentation worse.

+ +

Auto-vacuuming is only possible if the database stores some + additional information that allows each database page to be + traced backwards to its referrer. Therefore, auto-vacuuming must + be turned on before any tables are created. It is not possible + to enable or disable auto-vacuum after a table has been created.

+ +

When the value of auto-vacuum is 2 or "incremental" then the additional + information needed to do auto-vacuuming is stored in the database file + but auto-vacuuming does not occur automatically at each commit as it + does with auto_vacuum=full. In incremental mode, the separate + incremental_vacuum pragma must + be invoked to cause the auto-vacuum to occur.

+ +

The database connection can be changed between full and incremental + autovacuum mode at any time. However, changing from + "none" to "full" or "incremental" can only occur when the database + is new (no tables + have yet been created) or by running the VACUUM command. To + change auto-vacuum modes, first use the auto_vacuum pragma to set + the new desired mode, then invoke the VACUUM command to + reorganize the entire database file. To change from "full" or + "incremental" back to "none" always requires running VACUUM even + on an empty database. +

+ +

When the auto_vacuum pragma is invoked with no arguments, it + returns the current auto_vacuum mode.

+ +
+

PRAGMA automatic_index; +
PRAGMA automatic_index =
boolean;

+ +

Query, set, or clear the automatic indexing capability. +

Automatic indexing is enabled by default as of version 3.7.17, + but this might change in future releases of SQLite. + +


+

PRAGMA busy_timeout; +
PRAGMA busy_timeout =
milliseconds;

+

Query or change the setting of the + busy timeout. + This pragma is an alternative to the sqlite3_busy_timeout() C-language + interface which is made available as a pragma for use with language + bindings that do not provide direct access to sqlite3_busy_timeout(). + +


+

PRAGMA cache_size; +
PRAGMA cache_size =
pages; +
PRAGMA cache_size = -
kibibytes;

+

Query or change the suggested maximum number of database disk pages + that SQLite will hold in memory at once per open database file. Whether + or not this suggestion is honored is at the discretion of the + Application Defined Page Cache. + The default page cache that is built into SQLite honors the request, + however alternative application-defined page cache implementations + may choose to interpret the suggested cache size in different ways + or to ignore it all together. + The default suggested cache size is 2000 pages.

+ +

If the argument N is positive then the suggested cache size is set + to N. If the argument N is negative, then the + number of cache pages is adjusted to use approximately N*1024 bytes + of memory. + Backwards compatibility note: + The behavior of cache_size with a negative N + was different in SQLite versions prior to 3.7.10. In + version 3.7.9 and earlier, the number of pages in the cache was set + to the absolute value of N.

+ +

When you change the cache size using the cache_size pragma, the + change only endures for the current session. The cache size reverts + to the default value when the database is closed and reopened.

+ + + +
+

PRAGMA cache_spill; +
PRAGMA cache_spill=
boolean;

+ +

The cache_spill pragma enables or disables the ability of the pager + to spill dirty cache pages to the database file in the middle of a + transaction. Cache_spill is enabled by default and most applications + should leave it that way as cache spilling is usually advantageous. + However, a cache spill has the side-effect of acquiring an + EXCLUSIVE lock on the database file. Hence, some applications that + have large long-running transactions may want to disable cache spilling + in order to prevent the application from acquiring an exclusive lock + on the database until the moment that the transaction COMMITs. + +


+

PRAGMA case_sensitive_like = boolean;

+

The default behavior of the LIKE operator is to ignore case + for ASCII characters. Hence, by default 'a' LIKE 'A' is + true. The case_sensitive_like pragma installs a new application-defined + LIKE function that is either case sensitive or insensitive depending + on the value of the case_sensitive_like pragma. + When case_sensitive_like is disabled, the default LIKE behavior is + expressed. When case_sensitive_like is enabled, case becomes + significant. So, for example, + 'a' LIKE 'A' is false but 'a' LIKE 'a' is still true.

+ +

This pragma uses sqlite3_create_function() to overload the + LIKE and GLOB functions, which may override previous implementations + of LIKE and GLOB registered by the application.

+ +
+

PRAGMA checkpoint_fullfsync +
PRAGMA checkpoint_fullfsync =
boolean;

+

Query or change the fullfsync flag for checkpoint operations. + If this flag is set, then the F_FULLFSYNC syncing method is used + during checkpoint operations on systems that support F_FULLFSYNC. + The default value of the checkpoint_fullfsync flag + is off. Only Mac OS-X supports F_FULLFSYNC.

+ +

If the fullfsync flag is set, then the F_FULLFSYNC syncing + method is used for all sync operations and the checkpoint_fullfsync + setting is irrelevant.

+ +
+

PRAGMA collation_list;

+

Return a list of the collating sequences defined for the current + database connection.

+ +
+

PRAGMA compile_options;

+

This pragma returns the names of compile-time options used when + building SQLite, one option per row. The "SQLITE_" prefix is omitted + from the returned option names. See also the + sqlite3_compileoption_get() C/C++ interface and the + sqlite_compileoption_get() SQL functions.

+ +
+

PRAGMA count_changes; +
PRAGMA count_changes =
boolean;

+ +

Query or change the count-changes flag. Normally, when the + count-changes flag is not set, INSERT, UPDATE and DELETE statements + return no data. When count-changes is set, each of these commands + returns a single row of data consisting of one integer value - the + number of rows inserted, modified or deleted by the command. The + returned change count does not include any insertions, modifications + or deletions performed by triggers, or any changes made automatically + by foreign key actions.

+ +

Another way to get the row change counts is to use the + sqlite3_changes() or sqlite3_total_changes() interfaces. + There is a subtle different, though. When an INSERT, UPDATE, or + DELETE is run against a view using an INSTEAD OF trigger, + the count_changes pragma reports the number of rows in the view + that fired the trigger, whereas sqlite3_changes() and + sqlite3_total_changes() do not. + + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA data_store_directory; +
PRAGMA data_store_directory = '
directory-name';

+

Query or change the value of the sqlite3_data_directory global + variable, which windows operating-system interface backends use to + determine where to store database files specified using a relative + pathname.

+ +

Changing the data_store_directory setting is not threadsafe. + Never change the data_store_directory setting if another thread + within the application is running any SQLite interface at the same time. + Doing so results in undefined behavior. Changing the data_store_directory + setting writes to the sqlite3_data_directory global + variable and that global variable is not protected by a mutex.

+ +

This facility is provided for WinRT which does not have an OS + mechanism for reading or changing the current working directory. + The use of this pragma in any other context is discouraged and may + be disallowed in future releases.

+ + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA database_list;

+

This pragma works like a query to return one row for each database + attached to the current database connection. + The second column is the "main" for the main database file, "temp" + for the database file used to store TEMP objects, or the name of the + ATTACHed database for other database files. + The third column is the name of the database file itself, or an empty + string if the database is not associated with a file.

+ +
+ PRAGMA default_cache_size; +
PRAGMA default_cache_size =
Number-of-pages;

+ +

This pragma queries or sets the suggested maximum number of pages + of disk cache that will be allocated per open database file. + The difference between this pragma and cache_size is that the + value set here persists across database connections. + The value of the default cache size is stored in the 4-byte + big-endian integer located at offset 48 in the header of the + database file. +

+ + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA defer_foreign_keys +
PRAGMA defer_foreign_keys =
boolean;

+

When the defer_foreign_keys PRAGMA is on, + enforcement of all foreign key constraints is delayed until the + outermost transaction is committed. The defer_foreign_keys pragma + defaults to OFF so that foreign key constraints are only deferred if + they are created as "DEFERRABLE INITIALLY DEFERRED". The + defer_foreign_keys pragma is automatically switched off at each + COMMIT or ROLLBACK. Hence, the defer_foreign_keys pragma must be + separately enabled for each transaction. This pragma is + only meaningful if foreign key constraints are enabled, of course.

+ +

The sqlite3_db_status(db,SQLITE_DBSTATUS_DEFERRED_FKS,...) + C-language interface can be used during a transaction to determine + if there are deferred and unresolved foreign key constraints.

+ +
+

PRAGMA empty_result_callbacks; +
PRAGMA empty_result_callbacks =
boolean;

+ +

Query or change the empty-result-callbacks flag.

+ +

The empty-result-callbacks flag affects the sqlite3_exec() API only. + Normally, when the empty-result-callbacks flag is cleared, the + callback function supplied to the sqlite3_exec() is not invoked + for commands that return zero rows of data. When empty-result-callbacks + is set in this situation, the callback function is invoked exactly once, + with the third parameter set to 0 (NULL). This is to enable programs + that use the sqlite3_exec() API to retrieve column-names even when + a query returns no data.

+ + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA encoding; +
PRAGMA encoding = "UTF-8"; +
PRAGMA encoding = "UTF-16"; +
PRAGMA encoding = "UTF-16le"; +
PRAGMA encoding = "UTF-16be";

+

In first form, if the main database has already been + created, then this pragma returns the text encoding used by the + main database, one of "UTF-8", "UTF-16le" (little-endian UTF-16 + encoding) or "UTF-16be" (big-endian UTF-16 encoding). If the main + database has not already been created, then the value returned is the + text encoding that will be used to create the main database, if + it is created by this session.

+ +

The second through fifth forms of this pragma + set the encoding that the main database will be created with if + it is created by this session. The string "UTF-16" is interpreted + as "UTF-16 encoding using native machine byte-ordering". It is not + possible to change the text encoding of a database after it has been + created and any attempt to do so will be silently ignored.

+ +

Once an encoding has been set for a database, it cannot be changed.

+ +

Databases created by the ATTACH command always use the same encoding + as the main database. An attempt to ATTACH a database with a different + text encoding from the "main" database will fail.

+ +
+

PRAGMA foreign_key_check; +
PRAGMA foreign_key_check(
table-name);

+ +

The foreign_key_check pragma checks the database, or the table + called "table-name", for + foreign key constraints that are violated and returns one row of + output for each violation. There are four columns in each result row. + The first column is the name of the table that contains the REFERENCES + clause. The second column is the rowid of the row that + contains the invalid REFERENCES clause. The third column is the name + of the table that is referred to. The fourth column is the index of + the specific foreign key constraint that failed. The fourth column + in the output of the foreign_key_check pragma is the same integer as + the first column in the output of the foreign_key_list pragma. + When a "table-name" is specified, the only foreign key constraints + checked are those created by REFERENCES clauses in the + CREATE TABLE statement for table-name.

+ +
+

PRAGMA foreign_key_list(table-name);

+ +

This pragma returns one row for each foreign key constraint + created by a REFERENCES clause in the CREATE TABLE statement of + table "table-name". + +


+

PRAGMA foreign_keys; +
PRAGMA foreign_keys =
boolean;

+

Query, set, or clear the enforcement of foreign key constraints. + +

This pragma is a no-op within a transaction; foreign key constraint + enforcement may only be enabled or disabled when there is no pending + BEGIN or SAVEPOINT. + +

Changing the foreign_keys setting affects the execution of + all statements prepared + using the database connection, including those prepared before the + setting was changed. Any existing statements prepared using the legacy + sqlite3_prepare() interface may fail with an SQLITE_SCHEMA error + after the foreign_keys setting is changed. + +

As of SQLite version 3.6.19, the default setting for foreign + key enforcement is OFF. However, that might change in a future + release of SQLite. The default setting for foreign key enforcement + can be specified at compile-time using the SQLITE_DEFAULT_FOREIGN_KEYS + preprocessor macro. To minimize future problems, applications should + set the foreign key enforcement flag as required by the application + and not depend on the default setting. + +


+

PRAGMA freelist_count;

+

Return the number of unused pages in the database file.

+ +
+

PRAGMA full_column_names; +
PRAGMA full_column_names =
boolean;

+ +

Query or change the full_column_names flag. This flag together + with the short_column_names flag determine + the way SQLite assigns names to result columns of SELECT statements. + Result columns are named by applying the following rules in order: +

    +
  1. If there is an AS clause on the result, then the name of + the column is the right-hand side of the AS clause.

  2. +
  3. If the result is a general expression, not a just the name of + a source table column, + then the name of the result is a copy of the expression text.

  4. +
  5. If the short_column_names pragma is ON, then the name of the + result is the name of the source table column without the + source table name prefix: COLUMN.

  6. +
  7. If both pragmas short_column_names and full_column_names + are OFF then case (2) applies. +

  8. +
  9. The name of the result column is a combination of the source table + and source column name: TABLE.COLUMN

  10. +
+ + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA fullfsync +
PRAGMA fullfsync =
boolean;

+

Query or change the fullfsync flag. This flag + determines whether or not the F_FULLFSYNC syncing method is used + on systems that support it. The default value of the fullfsync flag + is off. Only Mac OS X supports F_FULLFSYNC.

+ +

See also checkpoint_fullfsync.

+ +
+

PRAGMA ignore_check_constraints = boolean;

+ +

This pragma enables or disables the enforcement of CHECK constraints. + The default setting is off, meaning that CHECK constraints are + enforced by default.

+ +
+

PRAGMA incremental_vacuum(N);

+

The incremental_vacuum pragma causes up to N pages to + be removed from the freelist. The database file is truncated by + the same amount. The incremental_vacuum pragma has no effect if + the database is not in + auto_vacuum=incremental mode + or if there are no pages on the freelist. If there are fewer than + N pages on the freelist, or if N is less than 1, or + if N is omitted entirely, then the entire freelist is cleared.

+ +
+

PRAGMA index_info(index-name);

+

This pragma returns one row each column in the named index. + The first column of the result is the rank of the column within the index. + The second column of the result is the rank of the column within the + table. The third column of output is the name of the column being indexed. +

+ +
+

PRAGMA index_list(table-name);

+

This pragma returns one row for each index associated with the + given table. + Columns of the result set include the + index name and a flag to indicate whether or not the index is UNIQUE. +

+ +
+

PRAGMA integrity_check; +
PRAGMA integrity_check(
N)

+

This pragma does an integrity check of the entire database. The + integrity_check pragma + looks for out-of-order records, missing pages, malformed records, and + corrupt indices. + If the integrity_check pragma finds problems, strings are returned + (as multiple rows with a single column per row) which describe + the problems. Pragma integrity_check will return at most N + errors will be reported before the analysis quits, with N defaulting + to 100. If pragma integrity_check finds no errors are found, a + single row with the value 'ok' is returned.

+ +
+

PRAGMA journal_mode; +
PRAGMA
database.journal_mode; +
PRAGMA journal_mode + = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF +
PRAGMA
database.journal_mode + = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF

+ +

This pragma queries or sets the journal mode for databases + associated with the current database connection.

+ +

The first two forms of this pragma query the current journaling + mode for database. When database is omitted, the + "main" database is queried.

+ +

The last two forms change the journaling mode. The 4th form + changes the journaling mode for a specific database connection named. + Use "main" for the main database (the database that was opened by + the original sqlite3_open(), sqlite3_open16(), or + sqlite3_open_v2() interface call) and use "temp" for database + that holds TEMP tables. The 3rd form changes the journaling mode + on all databases attached to the connection. + The new journal mode is returned. If the journal mode + could not be changed, the original journal mode is returned.

+ +

The DELETE journaling mode is the normal behavior. In the DELETE + mode, the rollback journal is deleted at the conclusion of each + transaction. Indeed, the delete operation is the action that causes + the transaction to commit. + (See the document titled + Atomic Commit In SQLite for additional detail.)

+ +

The TRUNCATE journaling mode commits transactions by truncating + the rollback journal to zero-length instead of deleting it. On many + systems, truncating a file is much faster than deleting the file since + the containing directory does not need to be changed.

+ +

The PERSIST journaling mode prevents the rollback journal from + being deleted at the end of each transaction. Instead, the header + of the journal is overwritten with zeros. This will prevent other + database connections from rolling the journal back. The PERSIST + journaling mode is useful as an optimization on platforms where + deleting or truncating a file is much more expensive than overwriting + the first block of a file with zeros. See also: + PRAGMA journal_size_limit and SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT.

+ +

The MEMORY journaling mode stores the rollback journal in + volatile RAM. This saves disk I/O but at the expense of database + safety and integrity. If the application using SQLite crashes in + the middle of a transaction when the MEMORY journaling mode is set, + then the database file will very likely go corrupt.

+ +

The WAL journaling mode uses a write-ahead log instead of a + rollback journal to implement transactions. The WAL journaling mode + is persistent; after being set it stays in effect + across multiple database connections and after closing and + reopening the database. A database in WAL journaling mode + can only be accessed by SQLite version 3.7.0 or later.

+ +

The OFF journaling mode disables the rollback journal completely. + No rollback journal is ever created and hence there is never a rollback + journal to delete. The OFF journaling mode disables the atomic + commit and rollback capabilities of SQLite. The ROLLBACK command + no longer works; it behaves in an undefined way. Applications must + avoid using the ROLLBACK command when the journal mode is OFF. + If the application crashes + in the middle of a transaction when the OFF journaling mode is + set, then the database file will very likely go corrupt.

+ +

Note that the journal_mode for an in-memory database + is either MEMORY or OFF and can not be changed to a different value. + An attempt to change the journal_mode of an in-memory database to + any setting other than MEMORY or OFF is ignored. Note also that + the journal_mode cannot be changed while a transaction is active.

+ +
+

+ PRAGMA journal_size_limit
+ PRAGMA journal_size_limit =
N ; + +

If a database connection is operating in + exclusive locking mode or in + persistent journal mode + (PRAGMA journal_mode=persist) then + after committing a transaction the rollback journal file may remain in + the file-system. This increases performance for subsequent transactions + since overwriting an existing file is faster than append to a file, + but it also consumes + file-system space. After a large transaction (e.g. a VACUUM), + the rollback journal file may consume a very large amount of space. + +

Similarly, in WAL mode, the write-ahead log file is not truncated + following a checkpoint. Instead, SQLite reuses the existing file + for subsequent WAL entries since overwriting is faster than appending. + +

The journal_size_limit pragma may be used to limit the size of + rollback-journal and WAL files left + in the file-system after transactions or checkpoints. + Each time a transaction is committed or a WAL file resets, SQLite + compares the size of the rollback journal file or WAL file left in + the file-system to the size limit + set by this pragma and if the journal or WAL file is larger + it is truncated to the limit. + +

The second form of the pragma listed above is used to set a new limit + in bytes for the specified database. A negative number implies no limit. + To always truncate rollback journals and WAL files to their minimum size, + set the journal_size_limit to zero. + Both the first and second forms of the pragma listed above return a single + result row containing a single integer column - the value of the journal + size limit in bytes. The default journal size limit is -1 (no limit). The + SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT preprocessor macro can be used to change + the default journal size limit at compile-time.

+ +

This pragma only operates on the single database specified prior + to the pragma name (or on the "main" database if no database is specified.) + There is no way to change the journal size limit on all attached databases + using a single PRAGMA statement. The size limit must be set separately for + each attached database. + +


+

PRAGMA legacy_file_format; +
PRAGMA legacy_file_format = boolean

+

This pragma sets or queries the value of the legacy_file_format + flag. When this flag is on, new SQLite databases are created in + a file format that is readable and writable by all versions of + SQLite going back to 3.0.0. When the flag is off, new databases + are created using the latest file format which might not be + readable or writable by versions of SQLite prior to 3.3.0.

+ +

When the legacy_file_format pragma is issued with no argument, + it returns the setting of the flag. This pragma does not tell + which file format the current database is using; it tells what format + will be used by any newly created databases.

+ +

The legacy_file_format pragma is initialized to OFF when an existing + database in the newer file format is first opened.

+ +

The default file format is set by the + SQLITE_DEFAULT_FILE_FORMAT compile-time option.

+ +
+

PRAGMA locking_mode; +
PRAGMA locking_mode = NORMAL | EXCLUSIVE

+

This pragma sets or queries the database connection locking-mode. + The locking-mode is either NORMAL or EXCLUSIVE. + +

In NORMAL locking-mode (the default unless overridden at compile-time + using SQLITE_DEFAULT_LOCKING_MODE), a database connection + unlocks the database file at the conclusion of each read or + write transaction. When the locking-mode is set to EXCLUSIVE, the + database connection never releases file-locks. The first time the + database is read in EXCLUSIVE mode, a shared lock is obtained and + held. The first time the database is written, an exclusive lock is + obtained and held.

+ +

Database locks obtained by a connection in EXCLUSIVE mode may be + released either by closing the database connection, or by setting the + locking-mode back to NORMAL using this pragma and then accessing the + database file (for read or write). Simply setting the locking-mode to + NORMAL is not enough - locks are not released until the next time + the database file is accessed.

+ +

There are three reasons to set the locking-mode to EXCLUSIVE. +

    +
  1. The application wants to prevent other processes from + accessing the database file. +
  2. The number of system calls for filesystem operations is reduced, + possibly resulting in a small performance increase. +
  3. WAL databases can be accessed in EXCLUSIVE mode without the + use of shared memory. + (Additional information) +
+

+ +

When the locking_mode pragma specifies a particular database, + for example:

+ +
+PRAGMA main.locking_mode=EXCLUSIVE; +
+ +

Then the locking mode applies only to the named database. If no + database name qualifier precedes the "locking_mode" keyword then + the locking mode is applied to all databases, including any new + databases added by subsequent ATTACH commands.

+ +

The "temp" database (in which TEMP tables and indices are stored) + and in-memory databases + always uses exclusive locking mode. The locking mode of temp and + in-memory databases cannot + be changed. All other databases use the normal locking mode by default + and are affected by this pragma.

+ +

If the locking mode is EXCLUSIVE when first entering + WAL journal mode, then the locking mode cannot be changed to + NORMAL until after exiting WAL journal mode. + If the locking mode is NORMAL when first entering WAL + journal mode, then the locking mode can be changed between NORMAL and + EXCLUSIVE and back again at any time and without needing to exit + WAL journal mode.

+ +
+

PRAGMA max_page_count; +
PRAGMA max_page_count =
N;

+

Query or set the maximum number of pages in the database file. + Both forms of the pragma return the maximum page count. The second + form attempts to modify the maximum page count. The maximum page + count cannot be reduced below the current database size. +

+ +
+


PRAGMA database.mmap_size; +
PRAGMA
database.mmap_size=N

+ +

Query or change the maximum number of bytes that are set + aside for memory-mapped I/O on a single database. The first form + (without an argument) queries the current limit. The second + form (with a numeric argument) sets the limit for the specified + database, or for all databases if the optional database name is + omitted. In the second form, if the database name is omitted, the + limit that is set becomes the default limit for all databases that + are added to the database connection by subsequent ATTACH + statements.

+ +

The argument N is the maximum number of bytes of the database file + that will be accessed using memory-mapped I/O. If N is zero then + memory mapped I/O is disabled. If N is negative, then the limit + reverts to the default value determined by the most recent + sqlite3_config(SQLITE_CONFIG_MMAP_SIZE), or to the compile + time default determined by SQLITE_DEFAULT_MMAP_SIZE if not + start-time limit has been set.

+ +

The PRAGMA mmap_size statement will never increase the amount + of address space used for memory-mapped I/O above the + hard limit set by the SQLITE_MAX_MMAP_SIZE compile-time option, + nor the hard limit set start-time by the second argument to + sqlite3_config(SQLITE_CONFIG_MMAP_SIZE)

+ +

The size of the memory-mapped I/O region cannot be changed while + the memory-mapped I/O region is in active use, to avoid unmapping + memory out from under running SQL statements. For this reason, + the mmap_size pragma may be a no-op if the prior mmap_size is non-zero + and there are other SQL statements running concurrently on the same + database connection.

+ +
+

PRAGMA page_count;

+

Return the total number of pages in the database file.

+ +
+

PRAGMA page_size; +
PRAGMA page_size =
bytes;

+

Query or set the page size of the database. The page + size must be a power of two between 512 and 65536 inclusive. +

+ +

When a new database is created, SQLite assigned a default page size + based on information received from the xSectorSize and + xDeviceCharacteristics methods of the sqlite3_io_methods object + of the newly created database file. The page_size pragma will only + cause an immediate change in the + page size if it is issued while the database is still empty, prior + to the first CREATE TABLE statement. If the page_size pragma is + used to specify a new page size just prior to + running the VACUUM command and if the database is not in + WAL journal mode then VACUUM will change the page + size to the new value.

+ +

If SQLite is compiled with the SQLITE_ENABLE_ATOMIC_WRITE option, + then the default page size is chosen to be the largest page size + less than or equal to SQLITE_MAX_DEFAULT_PAGE_SIZE for which atomic + write is enabled according to the + xDeviceCharacteristics method of the sqlite3_io_methods object for + the database file. If the SQLITE_ENABLE_ATOMIC_WRITE option is + disabled or if xDeviceCharacteristics reports no suitable atomic + write page sizes, then the default page size is the larger of + SQLITE_DEFAULT_PAGE_SIZE + and the sector size as reported by the xSectorSize method of the + sqlite3_io_methods object, but not more than + SQLITE_MAX_DEFAULT_PAGE_SIZE. The normal configuration for SQLite + running on workstations is for atomic write to be + disabled, for the maximum page size to be set to 65536, for + SQLITE_DEFAULT_PAGE_SIZE to be 1024, and for the + maximum default page size to be set to 8192. The default xSectorSize + method on unix workstation implementations always reports a sector size + of 512 bytes. Hence, + the default page size chosen by SQLite on unix is usually 1024 bytes. + On windows, the GetDiskFreeSpace() interface is used to obtain the + actual device sector size and hence the default page size on windows + will sometimes be greater than 1024.

+ +
+

PRAGMA parser_trace = boolean;

+ +

If SQLite has been compiled with the SQLITE_DEBUG compile-time + option, then the parser_trace pragma can be used to turn on tracing + for the SQL parser used internally by SQLite. + This feature is used for debugging SQLite itself.

+ + +

+ This pragma is intended for use when debugging SQLite itself. It + is only contained in the build when the SQLITE_DEBUG compile-time option + is used.

+ + +
+

PRAGMA query_only; +
PRAGMA query_only =
boolean;

+ +

The query_only pragma prevents all changes to database files when + enabled.

+ +
+

PRAGMA quick_check; +
PRAGMA quick_check(
N)

+

The pragma is like integrity_check except that it does not verify + that index content matches table content. By skipping the verification + of index content, quick_check is able to run much faster than + integrity_check. Otherwise the two pragmas are the same. +

+ +
+

PRAGMA read_uncommitted; +
PRAGMA read_uncommitted =
boolean;

+

Query, set, or clear READ UNCOMMITTED isolation. The default isolation + level for SQLite is SERIALIZABLE. Any process or thread can select + READ UNCOMMITTED isolation, but SERIALIZABLE will still be used except + between connections that share a common page and schema cache. + Cache sharing is enabled using the sqlite3_enable_shared_cache() API. + Cache sharing is disabled by default. +

+ +

See SQLite Shared-Cache Mode for additional information.

+ +
+

PRAGMA recursive_triggers; +
PRAGMA recursive_triggers =
boolean;

+

Query, set, or clear the recursive trigger capability. + +

Changing the recursive_triggers setting affects the execution of + all statements prepared + using the database connection, including those prepared before the + setting was changed. Any existing statements prepared using the legacy + sqlite3_prepare() interface may fail with an SQLITE_SCHEMA error + after the recursive_triggers setting is changed. + +

Prior to SQLite version 3.6.18, recursive triggers were not + supported. The behavior of SQLite was always as if this pragma was + set to OFF. Support for recursive triggers was added in version 3.6.18 + but was initially turned OFF by default, for compatibility. Recursive + triggers may be turned on by default in future versions of SQLite. +

+ +

The depth of recursion for triggers has a hard upper limit set by + the SQLITE_MAX_TRIGGER_DEPTH compile-time option and a run-time + limit set by sqlite3_limit(db,SQLITE_LIMIT_TRIGGER_DEPTH,...).

+ +
+

PRAGMA reverse_unordered_selects; +
PRAGMA reverse_unordered_selects =
boolean;

+

When enabled, this PRAGMA causes SELECT statements without + an ORDER BY clause to emit their results in the reverse order of what + they normally would. This can help debug applications that are + making invalid assumptions about the result order.

SQLite makes no + guarantees about the order of results if a SELECT omits the ORDER BY + clause. Even so, the order of results does not change from one + run to the next, and so many applications mistakenly come to depend + on the arbitrary output order whatever that order happens to be. However, + sometimes new versions of SQLite will contain optimizer enhancements + that will cause the output order of queries without ORDER BY clauses + to shift. When that happens, applications that depend on a certain + output order might malfunction. By running the application multiple + times with this pragma both disabled and enabled, cases where the + application makes faulty assumptions about output order can be + identified and fixed early, reducing problems + that might be caused by linking against a different version of SQLite. +

+ +
+

PRAGMA schema_version; +
PRAGMA schema_version =
integer ; +
PRAGMA user_version; +
PRAGMA user_version =
integer ; + + +

The pragmas schema_version and user_version are used to set or get + the value of the schema-version and user-version, respectively. The + schema-version and the user-version are big-endian 32-bit signed + integers stored in the database header at offsets 40 and 60, + respectively.

+ +

The schema-version is usually only manipulated internally by SQLite. + It is incremented by SQLite whenever the database schema is modified + (by creating or dropping a table or index). The schema version is + used by SQLite each time a query is executed to ensure that the + internal cache of the schema used when compiling the SQL query matches + the schema of the database against which the compiled query is actually + executed. Subverting this mechanism by using "PRAGMA schema_version" + to modify the schema-version is potentially dangerous and may lead + to program crashes or database corruption. Use with caution!

+ +

The user-version is not used internally by SQLite. It may be used by + applications for any purpose.

+ +
+

PRAGMA secure_delete; +
PRAGMA
database.secure_delete; +
PRAGMA secure_delete =
boolean +
PRAGMA
database.secure_delete = + boolean

+

Query or change the secure-delete setting. When secure-delete + on, SQLite overwrites deleted content with zeros. The default + setting is determined by the SQLITE_SECURE_DELETE + compile-time option. + +

+ When there are attached databases and no database + is specified in the pragma, all databases have their secure-delete + setting altered. + The secure-delete setting for newly attached databases is the setting + of the main database at the time the ATTACH command is evaluated. + +

+ When multiple database connections share the same cache, changing + the secure-delete flag on one database connection changes it for them + all. +

+ +
+

PRAGMA short_column_names; +
PRAGMA short_column_names =
boolean;

+ +

Query or change the short-column-names flag. This flag affects + the way SQLite names columns of data returned by SELECT statements. + See the full_column_names pragma for full details. +

+ + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA shrink_memory

+ +

This pragma causes the database connection on which it is invoked + to free up as much memory as it can, by calling + sqlite3_db_release_memory(). +

+ +
+

PRAGMA soft_heap_limit
+ PRAGMA soft_heap_limit=
N

+ +

This pragma invokes the sqlite3_soft_heap_limit64() interface with + the argument N, if N is specified and is a non-negative integer. + The soft_heap_limit pragma always returns the same integer + that would be returned by the sqlite3_soft_heap_limit64(-1) C-language + function. +

+ +
+

PRAGMA stats;

+

This pragma returns auxiliary information about tables and + indices. The returned information is used during testing to help + verify that the query planner is operating correctly. The format + and meaning of this pragma will likely change from release + to the next. Because of its volatility, the behavior and output + format of this pragma are deliberately undocumented. This pragma is + intended for interactive, debugging, and testing use only. + Applications should avoid using this pragma.

+ +
+

PRAGMA synchronous; +
PRAGMA synchronous =
+ 0 | OFF | 1 | NORMAL | 2 | FULL;

+ +

Query or change the setting of the "synchronous" flag. + The first (query) form will return the synchronous setting as an + integer. When synchronous is FULL (2), the SQLite database engine will + use the xSync method of the VFS to ensure that all content is safely + written to the disk surface prior to continuing. + This ensures that an operating system crash or power failure will + not corrupt the database. + FULL synchronous is very safe, but it is also slower. + When synchronous is NORMAL (1), the SQLite database + engine will still sync at the most critical moments, but less often + than in FULL mode. There is a very small (though non-zero) chance that + a power failure at just the wrong time could corrupt the database in + NORMAL mode. But in practice, you are more likely to suffer + a catastrophic disk failure or some other unrecoverable hardware + fault. + With synchronous OFF (0), SQLite continues without syncing + as soon as it has handed data off to the operating system. + If the application running SQLite crashes, the data will be safe, but + the database might become corrupted if the operating system + crashes or the computer loses power before that data has been written + to the disk surface. On the other hand, some + operations are as much as 50 or more times faster with synchronous OFF. +

+ +

In WAL mode when synchronous is NORMAL (1), the WAL file is + synchronized before each checkpoint and the database file is + synchronized after each completed checkpoint and the WAL file + header is synchronized when a WAL file begins to be reused after + a checkpoint, but no sync operations occur during most transactions. + With synchronous=FULL in WAL mode, an additional + sync operation of the WAL file happens after each transaction commit. + The extra WAL sync following each transaction help ensure that + transactions are durable across a power loss, but they do not aid + in preserving consistency. + If durability is not a concern, then synchronous=NORMAL is normally + all one needs in WAL mode.

+ +

The default setting is synchronous=FULL.

+ +

See also the fullfsync and checkpoint_fullfsync pragmas.

+ +
+

PRAGMA table_info(table-name);

+

This pragma returns one row for each column in the named table. + Columns in the result set include the column name, + data type, whether or not the column can be NULL, and the default + value for the column. The "pk" column in the result set is zero + for columns that are not part of the primary key, and is the index of + the column in the primary key for columns that are part of the primary + key.

+ +
+

PRAGMA temp_store; +
PRAGMA temp_store =
+ 0 | DEFAULT | 1 | FILE | 2 | MEMORY;

+ +

Query or change the setting of the "temp_store" parameter. + When temp_store is DEFAULT (0), the compile-time C preprocessor macro + SQLITE_TEMP_STORE is used to determine where temporary tables and indices + are stored. When + temp_store is MEMORY (2) temporary tables and indices are kept in + as if they were pure in-memory databases memory. + When temp_store is FILE (1) temporary tables and indices are stored + in a file. The temp_store_directory pragma can be used to specify + the directory containing temporary files when + FILE is specified. When the temp_store setting is changed, + all existing temporary tables, indices, triggers, and views are + immediately deleted.

+ +

It is possible for the library compile-time C preprocessor symbol + SQLITE_TEMP_STORE to override this pragma setting. + The following table summarizes + the interaction of the SQLITE_TEMP_STORE preprocessor macro and the + temp_store pragma:

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SQLITE_TEMP_STOREPRAGMA
temp_store
Storage used for
TEMP tables and indices
0anyfile
10file
11file
12memory
20memory
21file
22memory
3anymemory
+
+ +
+

PRAGMA temp_store_directory; +
PRAGMA temp_store_directory = '
directory-name';

+

Query or change the value of the sqlite3_temp_directory global + variable, which many operating-system interface backends use to + determine where to store temporary tables and indices.

+ +

When the temp_store_directory setting is changed, all existing temporary + tables, indices, triggers, and viewers in the database connection that + issued the pragma are immediately deleted. In + practice, temp_store_directory should be set immediately after the first + database connection for a process is opened. If the temp_store_directory + is changed for one database connection while other database connections + are open in the same process, then the behavior is undefined and + probably undesirable.

+ +

Changing the temp_store_directory setting is not threadsafe. + Never change the temp_store_directory setting if another thread + within the application is running any SQLite interface at the same time. + Doing so results in undefined behavior. Changing the temp_store_directory + setting writes to the sqlite3_temp_directory global + variable and that global variable is not protected by a mutex.

+ +

The value directory-name should be enclosed in single quotes. + To revert the directory to the default, set the directory-name to + an empty string, e.g., PRAGMA temp_store_directory = ''. An + error is raised if directory-name is not found or is not + writable.

+ +

The default directory for temporary files depends on the OS. Some + OS interfaces may choose to ignore this variable and place temporary + files in some other directory different from the directory specified + here. In that sense, this pragma is only advisory.

+ + +

+ This pragma is deprecated and exists + for backwards compatibility only. New applications + should avoid using this pragma. Older applications should discontinue + use of this pragma at the earliest opportunity. This pragma may be omitted + from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED. +

+ + +
+

PRAGMA vdbe_addoptrace = boolean;

+ +

If SQLite has been compiled with the SQLITE_DEBUG compile-time + option, then the vdbe_addoptrace pragma can be used to cause a complete + VDBE opcodes to be displayed as they are created during code generation. + This feature is used for debugging SQLite itself. See the + VDBE documentation for more + information.

+ + +

+ This pragma is intended for use when debugging SQLite itself. It + is only contained in the build when the SQLITE_DEBUG compile-time option + is used.

+ + +
+

PRAGMA vdbe_debug = boolean;

+ +

If SQLite has been compiled with the SQLITE_DEBUG compile-time + option, then the vdbe_debug pragma is a shorthand for three other + debug-only pragmas: vdbe_addoptrace, vdbe_listing, and vdbe_trace. + This feature is used for debugging SQLite itself. See the + VDBE documentation for more + information.

+ + +

+ This pragma is intended for use when debugging SQLite itself. It + is only contained in the build when the SQLITE_DEBUG compile-time option + is used.

+ + +
+

PRAGMA vdbe_listing = boolean;

+ +

If SQLite has been compiled with the SQLITE_DEBUG compile-time + option, then the vdbe_listing pragma can be used to cause a complete + listing of the virtual machine opcodes to appear on standard output + as each statement is evaluated. + With listing is on, the entire content of a program is printed + just prior to beginning execution. The statement + executes normally after the listing is printed. + This feature is used for debugging SQLite itself. See the + VDBE documentation for more + information.

+ + +

+ This pragma is intended for use when debugging SQLite itself. It + is only contained in the build when the SQLITE_DEBUG compile-time option + is used.

+ + +
+

PRAGMA vdbe_trace = boolean;

+ +

If SQLite has been compiled with the SQLITE_DEBUG compile-time + option, then the vdbe_trace pragma can be used to cause virtual machine + opcodes to be printed on standard output as they are evaluated. + This feature is used for debugging SQLite. See the + VDBE documentation for more + information.

+ + +

+ This pragma is intended for use when debugging SQLite itself. It + is only contained in the build when the SQLITE_DEBUG compile-time option + is used.

+ + +
+

PRAGMA wal_autocheckpoint;
+ PRAGMA wal_autocheckpoint=
N;

+ +

This pragma queries or sets the write-ahead log + auto-checkpoint interval. + When the write-ahead log is enabled (via the + journal_mode pragma) a checkpoint will be run automatically whenever + the write-ahead log equals or exceeds N pages in length. + Setting the auto-checkpoint size to zero or a negative value + turns auto-checkpointing off.

+ +

This pragma is a wrapper around the + sqlite3_wal_autocheckpoint() C interface.

+ +

Autocheckpointing is enabled by default with an interval + of 1000 or SQLITE_DEFAULT_WAL_AUTOCHECKPOINT.

+ + +
+

PRAGMA database.wal_checkpoint;
+ PRAGMA database.wal_checkpoint(PASSIVE);
+ PRAGMA database.wal_checkpoint(FULL);
+ PRAGMA database.wal_checkpoint(RESTART); +

+ +

If the write-ahead log is enabled (via the journal_mode pragma), + this pragma causes a checkpoint operation to run on database + database, or on all attached databases if database + is omitted. If write-ahead log mode is disabled, this pragma is a + harmless no-op.

+ +

Invoking this pragma is equivalent to calling the + sqlite3_wal_checkpoint_v2() C interface with a + 3rd parameter + corresponding to the argument of the PRAGMA. Invoking this + pragma without an argument is equivalent to calling the + sqlite3_wal_checkpoint() C interface.

+ +

The wal_checkpoint pragma returns a single row with three + integer columns. The first column is usually 0 but will be + 1 if a RESTART or FULL checkpoint was blocked from completing, + for example because another thread or process was actively + using the database. In other words, the first column is 0 if the + equivalent call to sqlite3_wal_checkpoint_v2() would have returned + SQLITE_OK or 1 if the equivalent call would have returned SQLITE_BUSY. + The second column is the number of modified pages that have been + written to the write-ahead log file. + The third column is the number of pages in the write-ahead log file + that have been successfully moved back into the database file at + the conclusion of the checkpoint. + The second and third column are -1 if there is no + write-ahead log, for example if this pragma is invoked on a database + connection that is not in WAL mode.

+ +
+

PRAGMA writable_schema = boolean;

+ +

When this pragma is on, the SQLITE_MASTER tables in which database + can be changed using ordinary UPDATE, INSERT, and DELETE + statements. Warning: misuse of this pragma can easily result in + a corrupt database file.

+ +
+ DELETED Doc/Extra/Core/syntax.html Index: Doc/Extra/Core/syntax.html ================================================================== --- Doc/Extra/Core/syntax.html +++ /dev/null @@ -1,214 +0,0 @@ - - - - SQLite Query Syntax - - - - -
-
-

- SQL As Understood By SQLite

-

- The SQLite library understands most of the standard SQL language. But it does omit - some features while at the same time adding a few features of its own. This document - attempts to describe precisely what parts of the SQL language SQLite does and does - not support. A list of keywords is also provided. In all of the syntax diagrams - that follow, literal text is shown in bold blue. Non-terminal symbols are shown - in italic red. Operators that are part of the syntactic markup itself are shown - in black roman. This document is just an overview of the SQL syntax implemented - by SQLite. -

-

- SQLite implements the follow syntax:

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - ALTER TABLE
- - ANALYZE
- - ATTACH DATABASE
- - BEGIN TRANSACTION
- - comment
- - COMMIT TRANSACTION
- CREATE INDEX
- CREATE TABLE
- CREATE TRIGGER
- CREATE VIEW
- - CREATE VIRTUAL TABLE
- - DELETE
- - DETACH DATABASE
- DROP INDEX
- DROP TABLE
- DROP TRIGGER
- DROP VIEW
- - END TRANSACTION
- - EXPLAIN
- - expression
- - INSERT
- - ON CONFLICT clause
- - PRAGMA
- - REINDEX
- - REPLACE
- - ROLLBACK TRANSACTION
- - SELECT
- - TYPES
- - UPDATE
- - VACUUM
-

-
- -
-
- - ADDED Doc/Extra/Core/syntaxdiagrams.html Index: Doc/Extra/Core/syntaxdiagrams.html ================================================================== --- /dev/null +++ Doc/Extra/Core/syntaxdiagrams.html @@ -0,0 +1,572 @@ + + + +Syntax Diagrams For SQLite + + + + +
+ + + +
+
Small. Fast. Reliable.
Choose any three.
+ + + + +
+ + + + +

Syntax Diagrams For SQLite

+ + +

sql-stmt-list:

+



+References:   sql-stmt

+See also:   lang.html +
+ + +

sql-stmt:

+

+Used by:   sql-stmt-list

+References:   alter-table-stmt   analyze-stmt   attach-stmt   begin-stmt   commit-stmt   create-index-stmt   create-table-stmt   create-trigger-stmt   create-view-stmt   create-virtual-table-stmt   delete-stmt   delete-stmt-limited   detach-stmt   drop-index-stmt   drop-table-stmt   drop-trigger-stmt   drop-view-stmt   insert-stmt   pragma-stmt   reindex-stmt   release-stmt   rollback-stmt   savepoint-stmt   select-stmt   update-stmt   update-stmt-limited   vacuum-stmt

+See also:   lang.html   lang_explain.html +
+ + +

alter-table-stmt:

+

+Used by:   sql-stmt

+References:   column-def

+See also:   lang_altertable.html +
+ + +

analyze-stmt:

+

+Used by:   sql-stmt

+See also:   lang_analyze.html +
+ + +

attach-stmt:

+

+Used by:   sql-stmt

+References:   expr

+See also:   lang_attach.html +
+ + +

begin-stmt:

+

+Used by:   sql-stmt

+See also:   lang_transaction.html +
+ + +

commit-stmt:

+

+Used by:   sql-stmt +
+ + +

rollback-stmt:

+

+Used by:   sql-stmt +
+ + +

savepoint-stmt:

+

+Used by:   sql-stmt

+See also:   lang_savepoint.html +
+ + +

release-stmt:

+

+Used by:   sql-stmt +
+ + +

create-index-stmt:

+

+Used by:   sql-stmt

+References:   expr   indexed-column

+See also:   lang_createindex.html   partialindex.html +
+ + +

indexed-column:

+

+Used by:   create-index-stmt   table-constraint

+See also:   lang_createindex.html   lang_createtable.html   partialindex.html +
+ + +

create-table-stmt:

+

+Used by:   sql-stmt

+References:   column-def   select-stmt   table-constraint

+See also:   lang_createtable.html +
+ + +

column-def:

+

+Used by:   alter-table-stmt   create-table-stmt

+References:   column-constraint   type-name

+See also:   lang_altertable.html   lang_createtable.html   lang_createtable.html#tablecoldef +
+ + +

type-name:

+

+Used by:   column-def   expr

+References:   signed-number

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

column-constraint:

+

+Used by:   column-def

+References:   conflict-clause   expr   foreign-key-clause   literal-value   signed-number

+See also:   lang_altertable.html   lang_createtable.html   lang_createtable.html#tablecoldef +
+ + +

signed-number:

+

+Used by:   column-constraint   pragma-value   type-name

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html   pragma.html#syntax +
+ + +

table-constraint:

+

+Used by:   create-table-stmt

+References:   conflict-clause   expr   foreign-key-clause   indexed-column

+See also:   lang_createtable.html   lang_createtable.html#primkeyconst   lang_createtable.html#tablecoldef +
+ + +

foreign-key-clause:

+

+Used by:   column-constraint   table-constraint

+See also:   lang_altertable.html   lang_createtable.html +
+ + +

conflict-clause:

+

+Used by:   column-constraint   table-constraint

+See also:   lang_altertable.html   lang_conflict.html   lang_createtable.html   lang_createtable.html#notnullconst +
+ + +

create-trigger-stmt:

+

+Used by:   sql-stmt

+References:   delete-stmt   expr   insert-stmt   select-stmt   update-stmt

+See also:   lang_createtrigger.html +
+ + +

create-view-stmt:

+

+Used by:   sql-stmt

+References:   select-stmt

+See also:   lang_createview.html +
+ + +

create-virtual-table-stmt:

+

+Used by:   sql-stmt

+See also:   lang_createvtab.html +
+ + +

with-clause:

+

+Used by:   delete-stmt   delete-stmt-limited   insert-stmt   update-stmt   update-stmt-limited

+References:   cte-table-name   select-stmt

+See also:   lang_createtrigger.html   lang_delete.html   lang_insert.html   lang_update.html   lang_with.html +
+ + +

cte-table-name:

+

+Used by:   recursive-cte   with-clause

+See also:   lang_createtrigger.html   lang_delete.html   lang_insert.html   lang_update.html   lang_with.html   lang_with.html#recursivecte +
+ + +

recursive-cte:

+



+References:   cte-table-name

+See also:   lang_with.html#recursivecte +
+ + +

common-table-expression:

+

+Used by:   compound-select-stmt   factored-select-stmt   select-stmt   simple-select-stmt

+References:   select-stmt

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

delete-stmt:

+

+Used by:   create-trigger-stmt   sql-stmt

+References:   expr   qualified-table-name   with-clause

+See also:   lang_createtrigger.html   lang_delete.html +
+ + +

delete-stmt-limited:

+

+Used by:   sql-stmt

+References:   expr   ordering-term   qualified-table-name   with-clause

+See also:   lang_delete.html +
+ + +

detach-stmt:

+

+Used by:   sql-stmt

+See also:   lang_detach.html +
+ + +

drop-index-stmt:

+

+Used by:   sql-stmt

+See also:   lang_dropindex.html +
+ + +

drop-table-stmt:

+

+Used by:   sql-stmt

+See also:   lang_droptable.html +
+ + +

drop-trigger-stmt:

+

+Used by:   sql-stmt

+See also:   lang_droptrigger.html +
+ + +

drop-view-stmt:

+

+Used by:   sql-stmt

+See also:   lang_dropview.html +
+ + +

expr:

+

+Used by:   attach-stmt   column-constraint   compound-select-stmt   create-index-stmt   create-trigger-stmt   delete-stmt   delete-stmt-limited   factored-select-stmt   insert-stmt   join-constraint   ordering-term   result-column   select-core   select-stmt   simple-select-stmt   table-constraint   update-stmt   update-stmt-limited

+References:   literal-value   raise-function   select-stmt   type-name

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

raise-function:

+

+Used by:   expr

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createtrigger.html#undef_before   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

literal-value:

+

+Used by:   column-constraint   expr

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

numeric-literal:

+



+See also:   lang_expr.html#litvalue +
+ + +

insert-stmt:

+

+Used by:   create-trigger-stmt   sql-stmt

+References:   expr   select-stmt   with-clause

+See also:   lang_createtrigger.html   lang_insert.html +
+ + +

pragma-stmt:

+

+Used by:   sql-stmt

+References:   pragma-value

+See also:   pragma.html#syntax +
+ + +

pragma-value:

+

+Used by:   pragma-stmt

+References:   signed-number

+See also:   pragma.html#syntax +
+ + +

reindex-stmt:

+

+Used by:   sql-stmt

+See also:   lang_reindex.html +
+ + +

select-stmt:

+

+Used by:   common-table-expression   create-table-stmt   create-trigger-stmt   create-view-stmt   expr   insert-stmt   sql-stmt   table-or-subquery   with-clause

+References:   common-table-expression   compound-operator   expr   join-clause   ordering-term   result-column   table-or-subquery

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   lang_with.html#recursivecte   partialindex.html +
+ + +

join-clause:

+

+Used by:   select-core   select-stmt   table-or-subquery

+References:   join-constraint   join-operator   table-or-subquery

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

select-core:

+

+Used by:   compound-select-stmt   factored-select-stmt   simple-select-stmt

+References:   expr   join-clause   result-column   table-or-subquery

+See also:   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect +
+ + +

factored-select-stmt:

+



+References:   common-table-expression   compound-operator   expr   ordering-term   select-core

+See also:   lang_select.html +
+ + +

simple-select-stmt:

+



+References:   common-table-expression   expr   ordering-term   select-core

+See also:   lang_select.html#simpleselect +
+ + +

compound-select-stmt:

+



+References:   common-table-expression   expr   ordering-term   select-core

+See also:   lang_select.html#compound +
+ + +

table-or-subquery:

+

+Used by:   join-clause   select-core   select-stmt

+References:   join-clause   select-stmt

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

result-column:

+

+Used by:   select-core   select-stmt

+References:   expr

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

join-operator:

+

+Used by:   join-clause

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#fromclause   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

join-constraint:

+

+Used by:   join-clause

+References:   expr

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#fromclause   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

ordering-term:

+

+Used by:   compound-select-stmt   delete-stmt-limited   factored-select-stmt   select-stmt   simple-select-stmt   update-stmt-limited

+References:   expr

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   partialindex.html +
+ + +

compound-operator:

+

+Used by:   factored-select-stmt   select-stmt

+See also:   lang_altertable.html   lang_attach.html   lang_createindex.html   lang_createtable.html   lang_createtrigger.html   lang_createview.html   lang_delete.html   lang_expr.html   lang_insert.html   lang_select.html   lang_select.html#compound   lang_select.html#simpleselect   lang_update.html   lang_with.html   lang_with.html#recursivecte   partialindex.html +
+ + +

update-stmt:

+

+Used by:   create-trigger-stmt   sql-stmt

+References:   expr   qualified-table-name   with-clause

+See also:   lang_createtrigger.html   lang_update.html +
+ + +

update-stmt-limited:

+

+Used by:   sql-stmt

+References:   expr   ordering-term   qualified-table-name   with-clause

+See also:   lang_update.html +
+ + +

qualified-table-name:

+

+Used by:   delete-stmt   delete-stmt-limited   update-stmt   update-stmt-limited

+See also:   lang_createtrigger.html   lang_delete.html   lang_indexedby.html   lang_update.html +
+ + +

vacuum-stmt:

+

+Used by:   sql-stmt

+See also:   lang_vacuum.html +
+ + +

comment-syntax:

+



+See also:   lang_comment.html +
+ + ADDED Doc/Extra/Provider/lang_types.html Index: Doc/Extra/Provider/lang_types.html ================================================================== --- /dev/null +++ Doc/Extra/Provider/lang_types.html @@ -0,0 +1,135 @@ + + + + TYPES + + + + +
+
+

+ SQL As Understood By SQLite (sortof)

+

+ TYPES

+

+ + + + + + + + + +
+ sql-statement ::= + TYPES [datatype name][,datatype name][,datatype + name][,...] ; select-stmt
+ select-stmt ::= + see SELECT
+

+

+ Use the TYPES keyword before a SELECT statement to provide the SQLite ADO.NET provider + a list of return datatypes to expect from the subsequent SELECT statement.  +

+

+ This is a language extension (aka hack) to SQLite specifically for the ADO.NET data + provider.  It is a pseudo-statement, meaning only the ADO.NET provider understands + it.

+

+ Background

+

+ Due to SQLite's typeless nature, there are certain kinds of queries for which the + ADO.NET provider cannot determine the proper return data type.  Scalar and + aggregate functions pose a particular problem because + there is no requirement for a given scalar or aggregate function to return any particular + datatype.  As a matter of fact, scalar functions could theoretically return + a different datatype for every row or column in a query and this is perfectly legal + from SQLite's point of view.

+

+ Since ADO.NET is designed around a typed system and we're shoe-horning SQLite into + it, this keyword helps the provider out in cases where the return type cannot be easily determined.

+

+ This command must be used in conjunction with a SELECT statement.  It only + works when both the TYPES keyword and its value(s) are passed along with a SELECT + statement as a single semi-colon separated unit.

+

+ Examples

+

+ TYPES [bigint], [int], [smallint], [tinyint];
+ SELECT 1, 2, 3, 4;

+

+ The above query would return the columns as types System.Int64, System.Int32, System.Int16 + and System.Byte respectively.

+

+ TYPES [bigint], [int], , [tinyint];
+ SELECT 1, 2, 3, 4;

+

+ In this sample, only columns 1, 2 and 4 would have explicit typing.  Column + 3's datatype would pass though the system and be discovered normally.

+

+ TYPES real;
+ SELECT SUM(Cost) FROM [Products];

+

+ The above query explicitly tells the provider that the SUM aggregate function returns + a System.Double.

+

+ Usage Notes

+
    +
  • You cannot use parameters in the TYPES statement.
  • +
  • The TYPES statement must be immediately followed by a SELECT statement.
  • +
  • It is legal to pass multiple TYPES and SELECT statements in a multi-statement + command.
  • +
  • You may enclose datatypes in quotes "" or brackets [] + or those `` thingies if you want.
    +
  • +
+
+ +
+
+ + ADDED Doc/Extra/Provider/syntax.html Index: Doc/Extra/Provider/syntax.html ================================================================== --- /dev/null +++ Doc/Extra/Provider/syntax.html @@ -0,0 +1,88 @@ + + + + SQLite Query Syntax + + + + +
+
+

+ SQL As Understood By System.Data.SQLite

+

+ The SQLite library understands most of the standard SQL language. But it does omit + some features while at the same time adding a few features of its own. This document + attempts to describe precisely what parts of the SQL language SQLite does and does + not support. A list of keywords is also provided. In all of the syntax diagrams + that follow, literal text is shown in bold blue. Non-terminal symbols are shown + in italic red. Operators that are part of the syntactic markup itself are shown + in black roman. This document is just an overview of the SQL syntax implemented + by SQLite. +

+

+ The SQLite core library implements the follow syntax:

+

+ + + + +
+ + SQL As Understood By SQLite
+

+

+ The System.Data.SQLite provider implements the follow additional syntax:

+

+ + + + +
+ + TYPES
+

+
+ +
+
+ + Index: Doc/Extra/Provider/version.html ================================================================== --- Doc/Extra/Provider/version.html +++ Doc/Extra/Provider/version.html @@ -44,10 +44,11 @@

Version History

1.0.91.0 - February XX, 2014 (release scheduled)

  • Updated to SQLite 3.8.3.
  • +
  • Refresh all included SQLite core library documentation (e.g. SQL syntax).
  • Add support for Entity Framework 6.
  • Add support for per-connection mappings between type names and DbType values. Pursuant to [e87af1d06a].
  • Modify the namespace used for all internal classes in the System.Data.SQLite.Linq assembly. ** Potentially Incompatible Change **
  • Add SQLiteCompileOptions and InteropCompileOptions properties to the SQLiteConnection class to return the compile-time options for the SQLite core library and interop assembly, respectively.
  • Add BindInvariantText and ConvertInvariantText connection flags to force the invariant culture to be used when converting parameter values to/from strings.
  • Index: Doc/SQLite.NET.hhc ================================================================== --- Doc/SQLite.NET.hhc +++ Doc/SQLite.NET.hhc @@ -28,20 +28,32 @@
  • +
  • + + + +
  • + + +
  • - - + +
      +
    • + + +
    • @@ -51,20 +63,20 @@
    • - - - -
    • - +
    • - - + + + +
    • + +
    • @@ -82,10 +94,14 @@
    • +
    • + + +
    • @@ -106,33 +122,33 @@
    • -
    • - - -
    • - + +
    • + + +
    • - - + +
    • - - + +
    • @@ -139,21 +155,50 @@
    • - - + +
    • +
    • + + + +
    • + + + +
    • + + + +
    • + + +
    • +
    • + + + +
    • + + + +
    • + + +
    + Index: Doc/SQLite.NET.hhp ================================================================== --- Doc/SQLite.NET.hhp +++ Doc/SQLite.NET.hhp @@ -8,42 +8,51 @@ Full-text search=Yes Language=0x409 English (United States) Title=SQLite.NET Help [FILES] +Core\lang.html +Core\lang_aggfunc.html Core\lang_altertable.html Core\lang_analyze.html Core\lang_attach.html Core\lang_comment.html Core\lang_conflict.html +Core\lang_corefunc.html Core\lang_createindex.html Core\lang_createtable.html Core\lang_createtrigger.html Core\lang_createview.html Core\lang_createvtab.html -Core\lang_datetime.html +Core\lang_datefunc.html Core\lang_delete.html Core\lang_detach.html Core\lang_dropindex.html Core\lang_droptable.html Core\lang_droptrigger.html Core\lang_dropview.html Core\lang_explain.html Core\lang_expr.html +Core\lang_indexedby.html Core\lang_insert.html +Core\lang_keywords.html +Core\lang_naming.html Core\lang_reindex.html Core\lang_replace.html +Core\lang_savepoint.html Core\lang_select.html Core\lang_transaction.html -Core\lang_types.html Core\lang_update.html Core\lang_vacuum.html +Core\lang_with.html Core\pragma.html -Core\syntax.html +Core\syntaxdiagrams.html Include\ndoc.css Provider\dbfactorysupport.html Provider\designer.html Provider\environment.html +Provider\lang_types.html Provider\limitations.html Provider\optimizing.html +Provider\syntax.html Provider\version.html Provider\welcome.html Index: Doc/buildChm.tcl ================================================================== --- Doc/buildChm.tcl +++ Doc/buildChm.tcl @@ -24,25 +24,132 @@ puts -nonewline $file_id $data close $file_id return "" } -proc readFileAsSubSpec { fileName } { - set data [readFile $fileName] +proc escapeSubSpec { data } { regsub -all -- {&} $data {\\\&} data regsub -all -- {\\(\d+)} $data {\\\\\1} data return $data } + +proc readFileAsSubSpec { fileName } { + return [escapeSubSpec [readFile $fileName]] +} proc getFileHash { fileName } { if {[catch { exec fossil.exe sha1sum [file nativename $fileName] } result] == 0} then { return [string trim [lindex [split $result " "] 0]] } return "" } + +# +# HACK: This procedure checks all the "href" attribute values in the specified +# core documentation file. For each value, this procedure checks if the +# reference conforms to one of the following general categories: +# +# 1. A relative reference to a named anchor within the same document. +# 2. An absolute reference using HTTP or HTTPS. +# 3. A relative reference to an existing local file. +# 4. An absolute reference to a local file. +# +# Otherwise, this procedure transforms the "href" attribute value into +# an absolute reference using the specified base URL. +# +proc transformCoreDocumentationFile { fileName url } { + # + # NOTE: Grab the name of the directory containing the file. + # + set directory [file dirname $fileName] + + # + # NOTE: Read all the textual data from the file. + # + set data [readFile $fileName] + + # + # NOTE: No replacements made yet. + # + set count 0 + + # + # NOTE: Process all "href" attribute values from the data. This pattern is + # not univeral; however, as of this writing (Feb 2014), the core docs + # are using it consistently. + # + foreach {dummy href} [regexp -all -inline -nocase -- {href="(.*?)"} $data] { + # + # NOTE: Skip all references to other items on this page. + # + if {[string index $href 0] eq "#"} then { + continue + } + + # + # NOTE: Skip all absolute HTTP/HTTPS references. + # + if {[string range $href 0 6] eq "http://" || \ + [string range $href 0 7] eq "https://"} then { + continue + } + + # + # NOTE: Split on the "#" character to get the file name. There are some + # places within the core docs that refer to named anchors within + # other files. + # + set parts [split $href #]; set part1 [lindex $parts 0] + + # + # NOTE: If there is no file name part, skip the reference. + # + if {[string length $part1] == 0} then { + continue + } + + # + # NOTE: If it does not appear to be relative, skip it. + # + if {[file pathtype $part1] ne "relative"} then { + continue + } + + # + # NOTE: If the referenced file name exists locally, skip it. + # + if {[file exists [file join $directory $part1]]} then { + continue + } + + # + # NOTE: Replace the reference with an absolute reference using the base + # URL specified by the caller, escaping it as necessary for use + # with [regsub]. + # + set pattern "***=$dummy"; # NOTE: Use literal string syntax. + set subSpec "href=\"[escapeSubSpec $url$href]\"" + + # + # NOTE: Perform the replacements, if any, keeping track of how many were + # done. + # + incr count [regsub -all -- $pattern $data $subSpec data] + } + + # + # NOTE: If some replacements were performed on the data from the file, then + # overwrite it with the new data; otherwise, issue a warning. + # + if {$count > 0} then { + writeFile $fileName $data + } else { + puts stdout "*WARNING* File \"$fileName\" does not match: href=\"(.*?)\"" + } +} # # HACK: Copy our local [fixed] copy of the MSDN documenter assembly into the # installed location of NDoc3, if necessary. Actually copying the file # will require elevated administrator privileges; otherwise, it will @@ -79,10 +186,13 @@ puts stdout \ "skipped copying \"$sourceFileName\" to \"$destinationFileName\"" } } +# +# NOTE: This is the entry point for this script. +# set path [file normalize [file dirname [info script]]] set nDocExtPath [file join [file dirname $path] Externals NDoc3] set nDocInstPath [file join $env(ProgramFiles) NDoc3] @@ -146,10 +256,12 @@ # TODO: If the NDoc version number ever changes, the next line of code will # probably need to be updated. # set outputPath [file join Output] set temporaryPath [file join $outputPath ndoc3_msdn_temp] +set corePath [file join $temporaryPath Core] +set providerPath [file join $temporaryPath Provider] if {[file isdirectory $nDocExtPath]} then { copyMsdnDocumenter $nDocExtPath $nDocInstPath } @@ -156,15 +268,24 @@ set code [catch {exec [file join $nDocInstPath bin NDoc3Console.exe] \ "-project=[file nativename $projectFile]"} result] puts stdout $result; if {$code != 0} then {exit $code} -set fileNames [list SQLite.NET.hhp SQLite.NET.hhc] +############################################################################### + +foreach fileName [glob -nocomplain [file join $corePath *.html]] { + set fileName [file join $path $fileName] + + if {![file isfile $fileName]} then { + puts stdout "Cannot find core file: $fileName" + exit 1 + } -foreach fileName [glob -nocomplain [file join $temporaryPath *.html]] { - lappend fileNames [file tail $fileName] + transformCoreDocumentationFile $fileName http://www.sqlite.org/ } + +############################################################################### set patterns(.hhc,1) {
      } set patterns(.hhp,1) {Default topic=~System\.Data\.SQLite\.html} @@ -205,18 +326,28 @@ set subSpecs(.html,5) {"\1~Overloads.html"} set subSpecs(.html,6) {"\1~Overloads.html"} set subSpecs(.html,7) {"\1~Overloads.html"} set subSpecs(.html,8) {"\1~Overloads.html"} -foreach fileName $fileNames { - set fileName [file join $path $temporaryPath $fileName] +############################################################################### + +set providerFileNames [list \ + [file join $temporaryPath SQLite.NET.hhp] \ + [file join $temporaryPath SQLite.NET.hhc]] + +foreach fileName [glob -nocomplain [file join $providerPath *.html]] { + lappend providerFileNames $fileName +} + +foreach fileName $providerFileNames { + set fileName [file join $path $fileName] # # NOTE: Make sure the file we need actually exists. # if {![file isfile $fileName]} then { - puts stdout "Cannot find file: $fileName" + puts stdout "Cannot find provider file: $fileName" exit 1 } # # NOTE: Read the entire file into memory. Index: Setup/verify.lst ================================================================== --- Setup/verify.lst +++ Setup/verify.lst @@ -18,47 +18,124 @@ set sds_manifests(source) { Doc/ Doc/buildChm.tcl Doc/Extra/ Doc/Extra/Core/ + Doc/Extra/Core/images/ + Doc/Extra/Core/images/sqlite370_banner.gif + Doc/Extra/Core/images/syntax/ + Doc/Extra/Core/images/syntax/a.gif + Doc/Extra/Core/images/syntax/alter-table-stmt.gif + Doc/Extra/Core/images/syntax/analyze-stmt.gif + Doc/Extra/Core/images/syntax/attach-stmt.gif + Doc/Extra/Core/images/syntax/begin-stmt.gif + Doc/Extra/Core/images/syntax/column-constraint.gif + Doc/Extra/Core/images/syntax/column-def.gif + Doc/Extra/Core/images/syntax/comment-syntax.gif + Doc/Extra/Core/images/syntax/commit-stmt.gif + Doc/Extra/Core/images/syntax/common-table-expression.gif + Doc/Extra/Core/images/syntax/compound-operator.gif + Doc/Extra/Core/images/syntax/compound-select-stmt.gif + Doc/Extra/Core/images/syntax/conflict-clause.gif + Doc/Extra/Core/images/syntax/create-index-stmt.gif + Doc/Extra/Core/images/syntax/create-table-stmt.gif + Doc/Extra/Core/images/syntax/create-trigger-stmt.gif + Doc/Extra/Core/images/syntax/create-view-stmt.gif + Doc/Extra/Core/images/syntax/create-virtual-table-stmt.gif + Doc/Extra/Core/images/syntax/cte-table-name.gif + Doc/Extra/Core/images/syntax/delete-stmt-limited.gif + Doc/Extra/Core/images/syntax/delete-stmt.gif + Doc/Extra/Core/images/syntax/detach-stmt.gif + Doc/Extra/Core/images/syntax/drop-index-stmt.gif + Doc/Extra/Core/images/syntax/drop-table-stmt.gif + Doc/Extra/Core/images/syntax/drop-trigger-stmt.gif + Doc/Extra/Core/images/syntax/drop-view-stmt.gif + Doc/Extra/Core/images/syntax/expr.gif + Doc/Extra/Core/images/syntax/factored-select-stmt.gif + Doc/Extra/Core/images/syntax/floating-point-literal.gif + Doc/Extra/Core/images/syntax/foreign-key-clause.gif + Doc/Extra/Core/images/syntax/foreign-key-clause2.gif + Doc/Extra/Core/images/syntax/indexed-column.gif + Doc/Extra/Core/images/syntax/insert-stmt.gif + Doc/Extra/Core/images/syntax/join-clause.gif + Doc/Extra/Core/images/syntax/join-constraint.gif + Doc/Extra/Core/images/syntax/join-op.gif + Doc/Extra/Core/images/syntax/join-operator.gif + Doc/Extra/Core/images/syntax/join-source.gif + Doc/Extra/Core/images/syntax/literal-value.gif + Doc/Extra/Core/images/syntax/numeric-literal.gif + Doc/Extra/Core/images/syntax/ordering-term.gif + Doc/Extra/Core/images/syntax/pragma-stmt.gif + Doc/Extra/Core/images/syntax/pragma-value.gif + Doc/Extra/Core/images/syntax/qualified-table-name.gif + Doc/Extra/Core/images/syntax/raise-function.gif + Doc/Extra/Core/images/syntax/recursive-cte.gif + Doc/Extra/Core/images/syntax/reindex-stmt.gif + Doc/Extra/Core/images/syntax/release-stmt.gif + Doc/Extra/Core/images/syntax/result-column.gif + Doc/Extra/Core/images/syntax/rollback-stmt.gif + Doc/Extra/Core/images/syntax/savepoint-stmt.gif + Doc/Extra/Core/images/syntax/select-core.gif + Doc/Extra/Core/images/syntax/select-stmt.gif + Doc/Extra/Core/images/syntax/signed-number.gif + Doc/Extra/Core/images/syntax/simple-select-stmt.gif + Doc/Extra/Core/images/syntax/single-source.gif + Doc/Extra/Core/images/syntax/sql-stmt-list.gif + Doc/Extra/Core/images/syntax/sql-stmt.gif + Doc/Extra/Core/images/syntax/table-constraint.gif + Doc/Extra/Core/images/syntax/table-or-subquery.gif + Doc/Extra/Core/images/syntax/type-name.gif + Doc/Extra/Core/images/syntax/update-stmt-limited.gif + Doc/Extra/Core/images/syntax/update-stmt.gif + Doc/Extra/Core/images/syntax/vacuum-stmt.gif + Doc/Extra/Core/images/syntax/with-clause.gif + Doc/Extra/Core/lang.html + Doc/Extra/Core/lang_aggfunc.html Doc/Extra/Core/lang_altertable.html Doc/Extra/Core/lang_analyze.html Doc/Extra/Core/lang_attach.html Doc/Extra/Core/lang_comment.html Doc/Extra/Core/lang_conflict.html + Doc/Extra/Core/lang_corefunc.html Doc/Extra/Core/lang_createindex.html Doc/Extra/Core/lang_createtable.html Doc/Extra/Core/lang_createtrigger.html Doc/Extra/Core/lang_createview.html Doc/Extra/Core/lang_createvtab.html - Doc/Extra/Core/lang_datetime.html + Doc/Extra/Core/lang_datefunc.html Doc/Extra/Core/lang_delete.html Doc/Extra/Core/lang_detach.html Doc/Extra/Core/lang_dropindex.html Doc/Extra/Core/lang_droptable.html Doc/Extra/Core/lang_droptrigger.html Doc/Extra/Core/lang_dropview.html Doc/Extra/Core/lang_explain.html Doc/Extra/Core/lang_expr.html + Doc/Extra/Core/lang_indexedby.html Doc/Extra/Core/lang_insert.html + Doc/Extra/Core/lang_keywords.html + Doc/Extra/Core/lang_naming.html Doc/Extra/Core/lang_reindex.html Doc/Extra/Core/lang_replace.html + Doc/Extra/Core/lang_savepoint.html Doc/Extra/Core/lang_select.html Doc/Extra/Core/lang_transaction.html - Doc/Extra/Core/lang_types.html Doc/Extra/Core/lang_update.html Doc/Extra/Core/lang_vacuum.html + Doc/Extra/Core/lang_with.html Doc/Extra/Core/pragma.html - Doc/Extra/Core/syntax.html + Doc/Extra/Core/syntaxdiagrams.html Doc/Extra/Include/ Doc/Extra/Include/ndoc.css Doc/Extra/Provider/ Doc/Extra/Provider/dbfactorysupport.html Doc/Extra/Provider/designer.html Doc/Extra/Provider/environment.html + Doc/Extra/Provider/lang_types.html Doc/Extra/Provider/limitations.html Doc/Extra/Provider/optimizing.html + Doc/Extra/Provider/syntax.html Doc/Extra/Provider/version.html Doc/Extra/Provider/welcome.html Doc/SQLite.NET.chm Doc/SQLite.NET.hhc Doc/SQLite.NET.hhp Index: readme.htm ================================================================== --- readme.htm +++ readme.htm @@ -211,10 +211,11 @@

      1.0.91.0 - February XX, 2014 (release scheduled)

      • Updated to SQLite 3.8.3.
      • +
      • Refresh all included SQLite core library documentation (e.g. SQL syntax).
      • Add support for Entity Framework 6.
      • Add support for per-connection mappings between type names and DbType values. Pursuant to [e87af1d06a].
      • Modify the namespace used for all internal classes in the System.Data.SQLite.Linq assembly. ** Potentially Incompatible Change **
      • Add SQLiteCompileOptions and InteropCompileOptions properties to the SQLiteConnection class to return the compile-time options for the SQLite core library and interop assembly, respectively.
      • Add BindInvariantText and ConvertInvariantText connection flags to force the invariant culture to be used when converting parameter values to/from strings.
      • Index: www/news.wiki ================================================================== --- www/news.wiki +++ www/news.wiki @@ -5,10 +5,11 @@

        1.0.91.0 - February XX, 2014 (release scheduled)

        • Updated to [http://www.sqlite.org/releaselog/3_8_3.html|SQLite 3.8.3].
        • +
        • Refresh all included SQLite core library documentation (e.g. SQL syntax).
        • Add support for [http://entityframework.codeplex.com/|Entity Framework 6].
        • Add support for per-connection mappings between type names and DbType values. Pursuant to [e87af1d06a].
        • Modify the namespace used for all internal classes in the System.Data.SQLite.Linq assembly. ** Potentially Incompatible Change **
        • Add SQLiteCompileOptions and InteropCompileOptions properties to the SQLiteConnection class to return the compile-time options for the SQLite core library and interop assembly, respectively.
        • Add BindInvariantText and ConvertInvariantText connection flags to force the invariant culture to be used when converting parameter values to/from strings.