SelectPromise<T, I, J>

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 type

  • I - The input type for field selection

  • J - Boolean indicating if result is JSON (default: false)

Configuration Methods

.fields()

Specify which fields to select from the records.

Method Syntax

selectPromise.fields(...fields)

Parameters

ParameterTypeDescription
fields Field<I>[]Field names to select.

Returns

SelectPromise<T, I, J> - Chainable promise

Examples

Select Specific Fields

const users = await db.select(new Table('users'))
.fields('name', 'email', 'age');
// Returns: [{ name, email, age }, ...]

Select Nested Fields

const users = await db.select(new Table('users'))
.fields('name', 'address.city', 'address.country');

Select with Aggregations

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.

Method Syntax

selectPromise.value(field)

Parameters

ParameterTypeDescription
field Field<I>The field name to extract.

Returns

SelectPromise<T, I, J> - Chainable promise

Example

Get Array of Values

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.

Method Syntax

selectPromise.where(condition)

Parameters

ParameterTypeDescription
condition ExprLikeThe condition expression (string or Expression object).

Returns

SelectPromise<T, I, J> - Chainable promise

Examples

String Condition

const adults = await db.select(new Table('users'))
.where('age >= 18');

With Expression Builder

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'))
)
));

Parameterized Condition

const users = await db.query(
surql`SELECT * FROM users WHERE age >= ${minAge}`
).collect();

.fetch()

Specify related fields to fetch (similar to SQL JOIN).

Method Syntax

selectPromise.fetch(...fields)

Parameters

ParameterTypeDescription
fields string[]Field names representing relations to fetch.

Returns

SelectPromise<T, I, J> - Chainable promise

Examples

Fetch Related Records

const posts = await db.select(new Table('posts'))
.fetch('author');
// Expands author RecordId to full user object

Fetch Multiple Relations

const posts = await db.select(new Table('posts'))
.fetch('author', 'comments', 'tags');

Fetch Nested Relations

const posts = await db.select(new Table('posts'))
.fetch('author', 'comments.author');

.start()

Set the pagination offset (number of records to skip).

Method Syntax

selectPromise.start(offset)

Parameters

ParameterTypeDescription
offset numberNumber of records to skip.

Returns

SelectPromise<T, I, J> - Chainable promise

Example

Pagination

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.

Method Syntax

selectPromise.limit(count)

Parameters

ParameterTypeDescription
count numberMaximum number of records to return.

Returns

SelectPromise<T, I, J> - Chainable promise

Example

Get Top 10

const topUsers = await db.select(new Table('users'))
.where('score > 0')
.limit(10);

.timeout()

Set a timeout for the query operation.

Method Syntax

selectPromise.timeout(duration)

Parameters

ParameterTypeDescription
duration DurationMaximum time to wait for query completion.

Returns

SelectPromise<T, I, J> - 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).

Method Syntax

selectPromise.version(timestamp)

Parameters

ParameterTypeDescription
timestamp DateTimeThe timestamp to query at.

Returns

SelectPromise<T, I, J> - Chainable promise

Example

Query Historical Data

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.

Method Syntax

selectPromise.json()

Returns

SelectPromise<T, I, true> - Promise returning JSON string

Example

const jsonString = await db.select(new Table('users')).json();
console.log(typeof jsonString); // 'string'

.stream()

Stream results as they arrive instead of waiting for all results.

Method Syntax

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 expanded

Aggregation

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