Skip to content

Selection Methods

Christoph Herrmann edited this page Oct 17, 2019 · 4 revisions

The return value is result.rows of the pg result object.

All columns

const users = await sql.any(
  'users',
  { name: 'name' }
)

// text: SELECT "*" FROM "users" WHERE "name" = $1
// values: ['name']

Only the list of the given columns

const users = await sql.any(
  'users',
  ['id', 'email', 'active'],
  { name: 'name' }
)

// text: SELECT "id", "email", "active" FROM "users" WHERE "name" = $1
// values: ['name']

any/manyOrNone, many

If several rows needs to be selected, e.g. some validated users:

const users = await sql.any(
  sql`SELECT "*" FROM "users" WHERE validated = true`
)

// text: SELECT "*" FROM "users" WHERE validated = true
// values: []

manyOrNone is an alias for any.

many will throw an error if there is not at least one row in the result.

oneOrNone, one

If one row needs to be selected, e.g. a specific user:

const user = await sql.one(
  sql`SELECT "*" FROM "users" WHERE "id" = 1`
)

// text: SELECT "*" FROM "users" WHERE "id" = 1
// values: []

oneOrNone returns undefined instead of throwing an error if there is none row in the result.

table can also be given as an array with the schema. Otherwise if it's defined the defaultSchema option will be used.

Clone this wiki locally