D1 client API
 Prepared and static statements
As part of our Client API, both static and prepared statements are supported. Best practice is to use prepared statements which are precompiled objects used by the database to run the SQL. This is because prepared statements lead to overall faster execution and prevent SQL injection attacks.
Below is an example of a prepared statement:
However, if you still choose to use a static statement you can use the following as an example:
 Parameter binding
D1 follows the SQLite convention for prepared statements parameter binding. Currently, D1 only supports Ordered (?NNNN) and Anonymous (?) parameters. In the future, D1 will support named parameters as well.
| Syntax | Type | Description | 
|---|---|---|
| ?NNN | Ordered | A question mark followed by a number NNNholds a spot for theNNN-th parameter.NNNmust be between1andSQLITE_MAX_VARIABLE_NUMBER | 
| ? | Anonymous | A question mark that is not followed by a number creates a parameter with a number one greater than the largest parameter number already assigned. If this means the parameter number is greater than SQLITE_MAX_VARIABLE_NUMBER, it is an error. This parameter format is provided for compatibility with other database engines. But because it is easy to miscount the question marks, the use of this parameter format is discouraged. Programmers are encouraged to use one of the symbolic formats below or the ?NNNformat above instead | 
To bind a parameter, use the stmt.bind() method.
 Order and anonymous examples:
 Type conversion
D1 automatically converts supported JavaScript (including TypeScript) types passed as parameters via the client API to their associated D1 types. The type conversion is as follows:
| JavaScript | D1 | 
|---|---|
| null | NULL | 
| Number | REAL | 
| Number 1 | INTEGER | 
| String | TEXT | 
| Boolean 2 | INTEGER | 
| ArrayBuffer | BLOB | 
| undefined | Not supported. Queries with undefinedvalues will return aD1_TYPE_ERROR | 
1 D1 supports 64-bit signed INTEGER values internally, however BigInts are not currently supported in the API yet. JavaScript integers are safe up to Number.MAX_SAFE_INTEGER.
2 Booleans will be cast to an INTEGER type where 1 is TRUE and 0 is FALSE.
 Return object
The methods stmt.run(), stmt.all() and db.batch() return a typed D1Result object that contains the results (if applicable), the success status, and a meta object with the internal duration of the operation in milliseconds.
Example:
The db.exec() method returns a D1ExecResult object:
 Query statement methods
The D1 API supports the following query statement methods:
- await stmt.first( [column] )
- await stmt.all()
- await stmt.raw()
- await stmt.run()
- await db.dump()
- await db.exec()
 await stmt.first([column])
Returns the first row of the results. This does not return metadata like the other methods. Instead, it returns the object directly.
Get a specific column from the first row:
Get all the the columns from the first row:
If the query returns no rows, then first() will return null.
If the query returns rows, but column does not exist, then first() will throw the D1_ERROR exception.
stmt.first() does not alter the SQL query. To improve performance, consider appending LIMIT 1 to your statement.
 await stmt.all()
Returns all rows and metadata.
 await stmt.raw()
Same as stmt.all(), but returns an array of rows instead of objects.
 await stmt.run()
Runs the query (or queries), but returns no results. Instead, run() returns the metrics only. Useful for write operations like UPDATE, DELETE or INSERT.
 await db.dump()
Dumps the entire D1 database to an SQLite compatible file inside an ArrayBuffer.
 await db.exec()
Executes one or more queries directly without prepared statements or parameters binding. This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe. Only use this method for maintenance and one-shot tasks (for example, migration jobs). The input can be one or multiple queries separated by \n.
If an error occurs, an exception is thrown with the query and error messages, execution stops and further statements are not executed. Refer to Errors to learn more.
 Reusing prepared statements
Prepared statements can be reused with new bindings:
 Searching with LIKE
Perform a search using SQL’s LIKE operator:
 Batch statements
Batching sends multiple SQL statements inside a single call to the database. This can have a huge performance impact as it reduces latency from network round trips to D1. D1 operates in auto-commit. Our implementation guarantees that each statement in the list will execute and commit, sequentially, non-concurrently.
Batched statements are SQL transactions. If a statement in the sequence fails, then an error is returned for that specific statement, and it aborts or rolls back the entire sequence.
 db.batch()
To send batch statements, provide batch() a list of prepared statements and get the results in the same order.
You can construct batches reusing the same prepared statement:
 PRAGMA statements
D1 supports the following SQLite PRAGMA statements:
| PRAGMA | Description | 
|---|---|
| table_list | Returns information about the tables and views in the schema, one table per row of output. | 
| table_info | 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. | 
| foreign_keys | Query, set, or clear the enforcement of foreign key constraints. | 
Other PRAGMAs are disabled because of D1 implementation specifics.
 Errors
The stmt. and db. methods will throw an Error object whenever an error occurs.
To capture exceptions, log the Error.message value. For example, the code below has a query with an invalid keyword - INSERTZ instead of INSERT:
The code above would throw the following error message:
 Error list
D1 will return the following error constants, in addition to the extended (detailed) error message:
| Message | Cause | 
|---|---|
| D1_ERROR | Generic error. | 
| D1_TYPE_ERROR | Returned when there is a mismatch in the type between a column and a value. A common cause is supplying an undefinedvariable (unsupported) instead ofnull. | 
| D1_COLUMN_NOTFOUND | Column not found. | 
| D1_DUMP_ERROR | Database dump error. | 
| D1_EXEC_ERROR | Exec error in line x: y error. |