The SelectPromise class provides a chainable interface for configuring SELECT queries before execution. It extends Promise, allowing you to await it directly or chain configuration methods.
Returned by: SurrealQueryable.select()
Source: query/select.ts
Type parameters
T- The result typeI- The input type for field selectionJ- Boolean indicating if result is JSON (default:false)
Configuration methods
.fields()
Specify which fields to select from the records.
selectPromise.fields(...fields)Parameters
Parameter | Type | Description |
|---|---|---|
fields | Field<I>[] | Field names to select. |
Returns
`SelectPromise` - Chainable promise
Examples
const users = await db.select(new Table('users'))
.fields('name', 'email', 'age');
// Returns: [{ name, email, age }, ...]const users = await db.select(new Table('users'))
.fields('name', 'address.city', 'address.country');const stats = await db.select(new Table('orders'))
.fields('count()', 'sum(total)', 'avg(items)'); .value()
Select only the value of a specific field, unwrapping it from the record structure.
selectPromise.value(field)Parameters
Parameter | Type | Description |
|---|---|---|
field | Field<I> | The field name to extract. |
Returns
`SelectPromise` - Chainable promise
Example
const names = await db.select(new Table('users'))
.value('name');
// Returns: ['John', 'Jane', 'Bob']
// Instead of: [{ name: 'John' }, { name: 'Jane' }, ...] .where()
Add a WHERE clause to filter results.
selectPromise.where(expr)Parameters
Parameter | Type | Description |
|---|---|---|
expr | ExprLike | The condition expression (string or Expression object). |
Returns
`SelectPromise` - Chainable promise
Examples
const adults = await db.select(new Table('users'))
.where('age >= 18');import { expr } from 'surrealdb';
const activeUsers = await db.select(new Table('users'))
.where(expr(({ and, eq, gte, field }) =>
and(
eq(field('status'), 'active'),
gte(field('last_login'), new DateTime('2024-01-01'))
)
));const users = await db.query(
surql`SELECT * FROM users WHERE age >= ${minAge}`
).collect(); .fetch()
Specify related fields to fetch (similar to SQL JOIN).
selectPromise.fetch(...fields)Parameters
Parameter | Type | Description |
|---|---|---|
fields | string[] | Field names representing relations to fetch. |
Returns
`SelectPromise` - Chainable promise
Examples
const posts = await db.select(new Table('posts'))
.fetch('author');
// Expands author RecordId to full user objectconst posts = await db.select(new Table('posts'))
.fetch('author', 'comments', 'tags');const posts = await db.select(new Table('posts'))
.fetch('author', 'comments.author'); .start()
Set the pagination offset (number of records to skip).
selectPromise.start(start)Parameters
Parameter | Type | Description |
|---|---|---|
start | number | Number of records to skip. |
Returns
`SelectPromise` - Chainable promise
Example
const page = 2;
const pageSize = 10;
const users = await db.select(new Table('users'))
.start((page - 1) * pageSize)
.limit(pageSize); .limit()
Limit the number of results returned.
selectPromise.limit(limit)Parameters
Parameter | Type | Description |
|---|---|---|
limit | number | Maximum number of records to return. |
Returns
`SelectPromise` - Chainable promise
Example
const topUsers = await db.select(new Table('users'))
.where('score > 0')
.limit(10); .timeout()
Set a timeout for the query operation.
selectPromise.timeout(duration)Parameters
Parameter | Type | Description |
|---|---|---|
duration | Duration | Maximum time to wait for query completion. |
Returns
`SelectPromise` - Chainable promise
Example
const users = await db.select(new Table('users'))
.timeout(Duration.parse('5s')); .version()
Select records at a specific version/timestamp (time-travel queries).
selectPromise.version(timestamp)Parameters
Parameter | Type | Description |
|---|---|---|
timestamp | DateTime | The timestamp to query at. |
Returns
`SelectPromise` - Chainable promise
Example
const historicalUsers = await db.select(new Table('users'))
.version(DateTime.parse('2024-01-01T00:00:00Z')); .json()
Return results as JSON strings instead of parsed objects.
selectPromise.json()Returns
`SelectPromise` - Promise returning JSON string
Example
const jsonString = await db.select(new Table('users')).json();
console.log(typeof jsonString); // 'string' .compile()
Compile the query into a BoundQuery without executing it.
selectPromise.compile()Returns
`BoundQuery` - The compiled query
Example
const query = db.select(new Table('users'))
.where('age >= 18')
.compile(); .stream()
Stream results as they arrive instead of waiting for all results.
selectPromise.stream()Returns
AsyncIterableIterator - Async iterator for streaming results
Example
for await (const user of db.select(new Table('users')).stream()) {
console.log('Received user:', user);
}Complete examples
Basic selection
import { Surreal, Table } from 'surrealdb';
const db = new Surreal();
await db.connect('ws://localhost:8000');
// Select all
const allUsers = await db.select(new Table('users'));
// Select specific record
const user = await db.select(new RecordId('users', 'john'));Filtered selection
const activeAdults = await db.select(new Table('users'))
.where('age >= 18 AND status = "active"')
.fields('name', 'email', 'age');Paginated selection
function getPage(page: number, pageSize: number) {
return db.select(new Table('users'))
.start((page - 1) * pageSize)
.limit(pageSize);
}
const page1 = await getPage(1, 20);
const page2 = await getPage(2, 20);Complex query with relations
const posts = await db.select(new Table('posts'))
.where('published = true')
.fields('title', 'content', 'author', 'created_at')
.fetch('author', 'comments.author')
.limit(10);
// posts[0].author is now a full User object
// posts[0].comments[0].author is also expandedAggregation
import { expr, gte } from 'surrealdb';
const stats = await db.select(new Table('orders'))
.where(expr(gte('created_at', DateTime.parse('2024-01-01'))))
.fields('count() as total_orders', 'sum(amount) as total_revenue', 'avg(amount) as avg_order');Streaming large results
let count = 0;
for await (const user of db.select(new Table('users')).stream()) {
await processUser(user);
count++;
if (count % 100 === 0) {
console.log(`Processed ${count} users`);
}
}Chaining pattern
All configuration methods return a new SelectPromise, allowing you to chain them in any order:
const result = await db.select(new Table('users'))
.where('status = "active"')
.fields('name', 'email')
.fetch('profile')
.start(0)
.limit(10)
.timeout(Duration.parse('5s'));See also
SurrealQueryable.select() - Method that returns SelectPromise
Query overview - All query builder classes
Expression builders - Building complex conditions