Performance
Keep database work responsive and avoid unnecessary round trips.
Use executeAsync() for longer queries, bind values as parameters, and fetch only the rows and columns your screen needs. See queries and indexes for SQLite query plans and index tradeoffs.
Keep long work off the JavaScript thread
Use executeAsync(), executeBatchAsync(), and loadFileAsync() for work that may take longer. See sync and async for choosing a call form and multiple connections when reads need a separate connection.
const { rows } = await db.executeAsync<{ id: number; title: string }>(
'SELECT id, title FROM articles ORDER BY id DESC LIMIT ?',
[50],
)
console.log(rows._array)An async call still consumes device CPU and database I/O. Paginate large result sets instead of bringing every row into JavaScript at once.
Reuse SQL text
Pass values as parameters to execute() or executeAsync() so repeated calls keep the same SQL text. Each connection reuses its 32 most recently used query and data-change statements. This avoids compiling the same SQL again. The cache covers statements starting with SELECT, INSERT, UPDATE, DELETE, REPLACE, WITH, or VALUES; other statements, such as PRAGMA, ATTACH, and BEGIN, compile on each call.
Use prepared statements when you need to control a statement's lifetime.
for (const metric of metrics) {
db.execute('INSERT INTO metrics (key, value) VALUES (?, ?)', [
metric.key,
metric.value,
])
}Group related writes
One executeBatchAsync() call executes a fixed set of statements inside a native transaction. Use nested parameter arrays for repeated SQL. Use db.transaction() when application logic must inspect a result between writes. Both keep a transaction open while they work; keep the scope short and await each operation inside a transaction callback.
await db.executeBatchAsync([
{
query: 'INSERT INTO metrics (key, value) VALUES (?, ?)',
params: [
['a', 1],
['b', 2],
],
},
])Measure on your target devices and data sizes before choosing a batch size, prepared statement, or index strategy.
See sync and async, batch operations, and transactions for the exact ordering rules.
For SQLite build settings and their tradeoffs, see Configuration.