Prepared statement methods
This chapter documents the various ways you can run and retrieve the results of a query after you have prepared your statement.
Binds a parameter to the prepared statement.
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);Variable: string- The variable to be appended into the prepared statement. See guidance below.
D1PreparedStatement: Object- A
D1PreparedStatementwhere the input parameter has been included in the statement.
- A
-
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 ?NNNOrdered 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
.bindmethod.Order and anonymous examples:
const stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind("");const stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?").bind("Alfreds Futterkiste", 1);const stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ?2 AND CustomerId = ?1").bind(1, "Alfreds Futterkiste");
D1 API supports static statements. Static statements are SQL statements where the variables have been hard coded. When writing a static statement, you manually type the variable within the statement string.
Example of a prepared statement with dynamically bound value:
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);// A variable (someVariable) will replace the placeholder '?' in the query.// `stmt` is a prepared statement.Example of a static statement:
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = Bs Beverages");// "Bs Beverages" is hard-coded into the query.// `stmt` is a static statement.Runs the prepared query (or queries) and returns results. The returned results includes metadata.
const returnValue = await stmt.run();- None.
D1Result: Object- An object containing the success status, a meta object, and an array of objects containing the query results.
- For more information on the object, refer to
D1Result.
Example of return values
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);const returnValue = await stmt.run();return Response.json(returnValue);{ "success": true, "meta": { "served_by": "miniflare.db", "duration": 1, "changes": 0, "last_row_id": 0, "changed_db": false, "size_after": 8192, "rows_read": 4, "rows_written": 0 }, "results": [ { "CustomerId": 11, "CompanyName": "Bs Beverages", "ContactName": "Victoria Ashworth" }, { "CustomerId": 13, "CompanyName": "Bs Beverages", "ContactName": "Random Name" } ]}resultsis empty for write operations such asUPDATE,DELETE, orINSERT.- When using TypeScript, you can pass a type parameter to
D1PreparedStatement::runto return a typed result object. D1PreparedStatement::runis functionally equivalent toD1PreparedStatement::all, and can be treated as an alias.- You can choose to extract only the results you expect from the statement by simply returning the
resultsproperty of the return object.
Example of returning only the results
resultsreturn Response.json(returnValue.results);[ { "CustomerId": 11, "CompanyName": "Bs Beverages", "ContactName": "Victoria Ashworth" }, { "CustomerId": 13, "CompanyName": "Bs Beverages", "ContactName": "Random Name" }]Runs the prepared query (or queries), and returns the results as an array of arrays. The returned results do not include metadata.
Column names are not included in the result set by default. To include column names as the first row of the result array, set .raw({columnNames: true}).
const returnValue = await stmt.raw();columnNames: Object Optional- A boolean object which includes column names as the first row of the result array.
Array: Array- An array of arrays. Each sub-array represents a row.
Example of return values
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);const returnValue = await stmt.raw();return Response.json(returnValue);[ [11, "Bs Beverages", "Victoria Ashworth" ], [13, "Bs Beverages", "Random Name" ]]With parameter columnNames: true:
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);const returnValue = await stmt.raw({columnNames:true});return Response.json(returnValue)[ [ "CustomerId", "CompanyName", "ContactName" ], [11, "Bs Beverages", "Victoria Ashworth" ], [13, "Bs Beverages", "Random Name" ]]- When using TypeScript, you can pass a type parameter to
D1PreparedStatement::rawto return a typed result array.
Runs the prepared query (or queries), and returns the first row of the query result as an object. This does not return any metadata. Instead, it directly returns the object.
const values = await stmt.first();columnName: String Optional- Specify a
columnNameto return a value from a specific column in the first row of the query result.
- Specify a
- None.
- Do not pass a parameter to obtain all columns from the first row.
-
firstRow: Object Optional- An object containing the first row of the query result.
- The return value will be further filtered to a specific attribute if
columnNamewas specified.
-
null: null- If the query returns no rows.
Example of return values
Get all the columns from the first row:
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);const returnValue = await stmt.first();return Response.json(returnValue){ "CustomerId": 11, "CompanyName": "Bs Beverages", "ContactName": "Victoria Ashworth"}Get a specific column from the first row:
const someVariable = `Bs Beverages`;const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);const returnValue = await stmt.first(CustomerId);return Response.json(returnValue)11- If the query returns rows but
columndoes not exist, thenD1PreparedStatement::firstthrows theD1_ERRORexception. D1PreparedStatement::firstdoes not alter the SQL query. To improve performance, consider appendingLIMIT 1to your statement.- When using TypeScript, you can pass a type parameter to
D1PreparedStatement::firstto return a typed result object.