|
| 1 | +--- |
| 2 | +title: D1 Query SQL Statements |
| 3 | +pcx_content_type: concept |
| 4 | +sidebar: |
| 5 | + order: 4 |
| 6 | +--- |
| 7 | + |
| 8 | +import { Type, MetaInfo, Details } from "~/components"; |
| 9 | + |
| 10 | +## Description |
| 11 | + |
| 12 | +## Methods |
| 13 | + |
| 14 | +### await stmt.all() |
| 15 | + |
| 16 | +Returns all rows as an array of objects, with each result row represented as an object on the `results` property of the `D1Result` type. |
| 17 | + |
| 18 | +```js |
| 19 | +const { results } = await stmt.all(); |
| 20 | +``` |
| 21 | + |
| 22 | +#### Parameters |
| 23 | + |
| 24 | +- None. |
| 25 | + |
| 26 | +#### Return values |
| 27 | + |
| 28 | +- <code>Array</code>: <Type text="Array"/> |
| 29 | + - An array of objects. |
| 30 | + - Each row represents a row. |
| 31 | + - Each object is created on the `results` property of the `D1Result` type. |
| 32 | + |
| 33 | +<Details header="Example of return values" open = {false}> |
| 34 | +```js |
| 35 | +const stmt = db.prepare("SELECT name, age FROM users LIMIT 3"); |
| 36 | +const { results } = await stmt.all(); |
| 37 | +console.log(results); |
| 38 | +``` |
| 39 | + |
| 40 | +```js output |
| 41 | +[ |
| 42 | + { |
| 43 | + name: "John", |
| 44 | + age: 42, |
| 45 | + }, |
| 46 | + { |
| 47 | + name: "Anthony", |
| 48 | + age: 37, |
| 49 | + }, |
| 50 | + { |
| 51 | + name: "Dave", |
| 52 | + age: 29, |
| 53 | + }, |
| 54 | + ] |
| 55 | +``` |
| 56 | +</Details> |
| 57 | + |
| 58 | +#### Guidance |
| 59 | + |
| 60 | +- When joining tables with identical column names, only the leftmost column will be included in the row object. Use [`stmt.raw()`](#await-stmtraw) to return all rows as an array of arrays. |
| 61 | +- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `all()` to return a typed result object. |
| 62 | + |
| 63 | +### await stmt.raw() |
| 64 | + |
| 65 | +Returns results as an array of arrays, with each row represented by an array. The return type is an array of arrays, and does not include query metadata. |
| 66 | + |
| 67 | +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})`. |
| 68 | + |
| 69 | +```js |
| 70 | +const rows = await stmt.raw(); |
| 71 | +``` |
| 72 | + |
| 73 | +#### Parameters |
| 74 | + |
| 75 | +- <code>columnNames</code>: <Type text="Boolean"/> <MetaInfo text="Optional"/> |
| 76 | + - A boolean flag which includes column names as the first row of the result array. |
| 77 | + |
| 78 | +#### Return values |
| 79 | + |
| 80 | +- <code>Array</code>: <Type text="Array"/> |
| 81 | + - An array of arrays. |
| 82 | + - Each array represents a row. |
| 83 | + |
| 84 | +<Details header="Example of return values" open = {false}> |
| 85 | +```js |
| 86 | +const stmt = db.prepare("SELECT name, age FROM users LIMIT 3"); |
| 87 | +const rows = await stmt.raw(); |
| 88 | +console.log(rows); |
| 89 | +``` |
| 90 | +```js output |
| 91 | +[ |
| 92 | + [ "John", 42 ], |
| 93 | + [ "Anthony", 37 ], |
| 94 | + [ "Dave", 29 ], |
| 95 | +] |
| 96 | +``` |
| 97 | + |
| 98 | +With parameter `columnNames: true`: |
| 99 | +```js |
| 100 | +const stmt = db.prepare("SELECT name, age FROM users LIMIT 3"); |
| 101 | +const [columns, ...rows] = await stmt.raw({ columnNames: true }); |
| 102 | +console.log(columns); |
| 103 | +``` |
| 104 | +```js output |
| 105 | +[ "name", age ], // The first result array includes the column names |
| 106 | +``` |
| 107 | +</Details> |
| 108 | + |
| 109 | +#### Guidance |
| 110 | + |
| 111 | +- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `raw()` to return a typed result array. |
| 112 | + |
| 113 | +### await stmt.first() |
| 114 | + |
| 115 | +Returns the first row of the query result. This does not return metadata like the other methods. Instead, it directly returns the object. |
| 116 | + |
| 117 | +```js |
| 118 | +const values = await stmt.first(); |
| 119 | +const total = await stmt.first("columnName"); |
| 120 | +``` |
| 121 | + |
| 122 | +#### Parameters |
| 123 | + |
| 124 | +- <code>columnName</code>: <Type text="String"/> <MetaInfo text="Optional"/> |
| 125 | + - Specify a `columnName` to return the value from a specific column in the first row of the query result. |
| 126 | +- None. |
| 127 | + - Do not pass a parameter to obtain all columns from the first row. |
| 128 | + |
| 129 | +#### Return values |
| 130 | + |
| 131 | +- <code>firstRow</code>: <Type text="Object"/> |
| 132 | + - An object containing the first row of the query result. |
| 133 | + |
| 134 | +- `null`: <Type text="null"/> |
| 135 | + - If the query returns no rows. |
| 136 | + |
| 137 | +<Details header ="Example of return values" open = {false}> |
| 138 | + |
| 139 | +Get all the columns from the first row: |
| 140 | + |
| 141 | +```js |
| 142 | +const stmt = db.prepare("SELECT COUNT(*) AS total FROM users"); |
| 143 | +const values = await stmt.first(); |
| 144 | +console.log(values); |
| 145 | +``` |
| 146 | +```js output |
| 147 | +{ total: 50 } |
| 148 | +``` |
| 149 | + |
| 150 | +Get a specific column from the first row: |
| 151 | + |
| 152 | +```js |
| 153 | +const stmt = db.prepare("SELECT COUNT(*) AS total FROM users"); |
| 154 | +const total = await stmt.first("total"); |
| 155 | +console.log(total); |
| 156 | +``` |
| 157 | +```js output |
| 158 | +50 // NEED CONFIRMING |
| 159 | +``` |
| 160 | +</Details> |
| 161 | + |
| 162 | +#### Guidance |
| 163 | + |
| 164 | +- If the query returns rows but `column` does not exist, then `first()` throws the `D1_ERROR` exception. |
| 165 | +- `stmt.first()` does not alter the SQL query. To improve performance, consider appending `LIMIT 1` to your statement. |
| 166 | +- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `first()` to return a typed result object. |
| 167 | + |
| 168 | +### await stmt.run() |
| 169 | + |
| 170 | +Runs the query (or queries) and returns results. |
| 171 | + |
| 172 | +```js |
| 173 | +const { results } = await stmt.run(); |
| 174 | +``` |
| 175 | + |
| 176 | +#### Parameter |
| 177 | + |
| 178 | +- None. |
| 179 | + |
| 180 | +#### Return value |
| 181 | + |
| 182 | +- <code>results</code>: <Type text="Array"/> |
| 183 | + - An array of objects, where each object represents a row of the query result. |
| 184 | + - Each object is created on the `results` property of the `D1Result` type. {/*What does it return when `results` is actually empty?*/} |
| 185 | + |
| 186 | +<Details header="Example of return values" open = {false}> |
| 187 | +```js |
| 188 | +const stmt = await db.prepare("SELECT name, age FROM users LIMIT 3"); |
| 189 | +const { results } = await stmt.run(); |
| 190 | +console.log(results); |
| 191 | +``` |
| 192 | +```js output |
| 193 | +[ |
| 194 | + { |
| 195 | + name: "John", |
| 196 | + age: 42, |
| 197 | + }, |
| 198 | + { |
| 199 | + name: "Anthony", |
| 200 | + age: 37, |
| 201 | + }, |
| 202 | + { |
| 203 | + name: "Dave", |
| 204 | + age: 29, |
| 205 | + }, |
| 206 | + ] |
| 207 | +``` |
| 208 | +</Details> |
| 209 | + |
| 210 | +#### Guidance |
| 211 | + |
| 212 | +- `results` is empty for write operations such as UPDATE, DELETE, or INSERT. |
| 213 | +- Run is functionally equivalent to `stmt.all()` and can be treated as an alias. |
| 214 | +- When using TypeScript, you can pass a [type parameter](/d1/build-with-d1/d1-client-api/#typescript-support) to `run()` to return a typed result object. |
| 215 | + |
| 216 | +### await db.dump() |
| 217 | + |
| 218 | +:::caution |
| 219 | +This API only works on databases created during D1's alpha period. Check which version your database uses with `wrangler d1 info <DATABASE_NAME>`. |
| 220 | +::: |
| 221 | + |
| 222 | +Dumps the entire D1 database to an SQLite compatible file inside an ArrayBuffer. |
| 223 | + |
| 224 | +```js |
| 225 | +const dump = await db.dump(); |
| 226 | +return new Response(dump, { |
| 227 | + status: 200, |
| 228 | + headers: { |
| 229 | + "Content-Type": "application/octet-stream", |
| 230 | + }, |
| 231 | +}); |
| 232 | +``` |
| 233 | + |
| 234 | +#### Parameters |
| 235 | + |
| 236 | +- None. |
| 237 | + |
| 238 | +#### Return values |
| 239 | + |
| 240 | +- ??? |
| 241 | + |
| 242 | +#### Guidance |
| 243 | + |
| 244 | +- ??? |
| 245 | + |
| 246 | +### await db.exec() |
| 247 | + |
| 248 | +Executes one or more queries directly without prepared statements or parameters binding. |
| 249 | + |
| 250 | +```js |
| 251 | +const out = await db.exec(); |
| 252 | +``` |
| 253 | + |
| 254 | +#### Parameters |
| 255 | + |
| 256 | +- ??? |
| 257 | + |
| 258 | +#### Return values |
| 259 | + |
| 260 | +- ??? |
| 261 | + |
| 262 | +<Details header="Example of return values" open={false}> |
| 263 | +```js |
| 264 | +const migration = await fetch("/migration.sql"); |
| 265 | +const out = await db.exec(migration.text()); |
| 266 | +console.log(out); |
| 267 | +``` |
| 268 | +```js output |
| 269 | +{ |
| 270 | + count: 80, |
| 271 | + duration: 76 |
| 272 | +} |
| 273 | +``` |
| 274 | +</Details> |
| 275 | + |
| 276 | +#### Guidance |
| 277 | + |
| 278 | +- This method can have poorer performance (prepared statements can be reused in some cases) and, more importantly, is less safe. |
| 279 | +- Only use this method for maintenance and one-shot tasks (for example, migration jobs). |
| 280 | +- The input can be one or multiple queries separated by `\n`. |
| 281 | +- 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](/d1/build-with-d1/d1-client-api/#errors) to learn more. |
| 282 | + |
0 commit comments