• Start

Languages

/

JavaScript

/

API Reference

/

Query builders

SelectPromise

SelectPromise provides chainable methods for configuring SELECT queries.

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

  • T - The result type

  • I - The input type for field selection

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

Specify which fields to select from the records.

Method Syntax
selectPromise.fields(...fields)

Parameter

Type

Description

fieldsField<I>[]

Field names to select.

`SelectPromise` - Chainable promise

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

Select only the value of a specific field, unwrapping it from the record structure.

Method Syntax
selectPromise.value(field)

Parameter

Type

Description

fieldField<I>

The field name to extract.

`SelectPromise` - Chainable promise

Get Array of Values
const names = await db.select(new Table('users'))
    .value('name');
// Returns: ['John', 'Jane', 'Bob']

// Instead of: [{ name: 'John' }, { name: 'Jane' }, ...]

Add a WHERE clause to filter results.

Method Syntax
selectPromise.where(expr)

Parameter

Type

Description

exprExprLike

The condition expression (string or

Expression

object).

`SelectPromise` - Chainable promise

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'))
        )
    ));
Parameterised condition
const users = await db.query(
    surql`SELECT * FROM users WHERE age >= ${minAge}`
).collect();

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

Method Syntax
selectPromise.fetch(...fields)

Parameter

Type

Description

fieldsstring[]

Field names representing relations to fetch.

`SelectPromise` - Chainable promise

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

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

Method Syntax
selectPromise.start(start)

Parameter

Type

Description

startnumber

Number of records to skip.

`SelectPromise` - Chainable promise

Pagination
const page = 2;
const pageSize = 10;

const users = await db.select(new Table('users'))
    .start((page - 1) * pageSize)
    .limit(pageSize);

Limit the number of results returned.

Method Syntax
selectPromise.limit(limit)

Parameter

Type

Description

limitnumber

Maximum number of records to return.

`SelectPromise` - Chainable promise

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

Set a timeout for the query operation.

Method Syntax
selectPromise.timeout(duration)

Parameter

Type

Description

duration

Duration

Maximum time to wait for query completion.

`SelectPromise` - Chainable promise

const users = await db.select(new Table('users'))
    .timeout(Duration.parse('5s'));

Select records at a specific version/timestamp (time-travel queries).

Method Syntax
selectPromise.version(timestamp)

Parameter

Type

Description

timestamp

DateTime

The timestamp to query at.

`SelectPromise` - Chainable promise

Query Historical Data
const historicalUsers = await db.select(new Table('users'))
    .version(DateTime.parse('2024-01-01T00:00:00Z'));

Return results as JSON strings instead of parsed objects.

Method Syntax
selectPromise.json()

`SelectPromise` - Promise returning JSON string

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

Compile the query into a BoundQuery without executing it.

Method Syntax
selectPromise.compile()

`BoundQuery` - The compiled query

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

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

Method Syntax
selectPromise.stream()

AsyncIterableIterator - Async iterator for streaming results

for await (const user of db.select(new Table('users')).stream()) {
    console.log('Received user:', user);
}
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'));
const activeAdults = await db.select(new Table('users'))
    .where('age >= 18 AND status = "active"')
    .fields('name', 'email', 'age');
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);
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
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');
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`);
    }
}

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

Was this page helpful?