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.
Runs the prepared query (or queries) and returns results. The returned results includes metadata.
- 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
results
is empty for write operations such asUPDATE
,DELETE
, orINSERT
.- When using TypeScript, you can pass a type parameter to
D1PreparedStatement::run
to return a typed result object. D1PreparedStatement::run
is 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
results
property of the return object.
Example of returning only the results
results
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})
.
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
With parameter columnNames: true
:
- When using TypeScript, you can pass a type parameter to
D1PreparedStatement::raw
to 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.
columnName
: String Optional- Specify a
columnName
to 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
columnName
was specified.
-
null
: null- If the query returns no rows.
Example of return values
Get all the columns from the first row:
Get a specific column from the first row:
- If the query returns rows but
column
does not exist, thenD1PreparedStatement::first
throws theD1_ERROR
exception. D1PreparedStatement::first
does not alter the SQL query. To improve performance, consider appendingLIMIT 1
to your statement.- When using TypeScript, you can pass a type parameter to
D1PreparedStatement::first
to return a typed result object.