Skip to content

Values List

Christoph Herrmann edited this page Oct 17, 2019 · 6 revisions
const valuesList = [
  ['emailA', 'nameA'],
  ['emailB', 'nameB']
]

const result = await sql.query(sql`
  INSERT INTO users (email, name) VALUES ${sql.valuesList(valuesList)}
`)

// text: INSERT INTO users (email, name) VALUES ($1, $2), ($3, $4)
// values: ['emailA', 'nameA', 'emailB', 'nameB']

If the parameter is an array of objects (e.g. list of users) the values of the objects will be used:

const users = [
  { email: 'emailA', name: 'nameA' },
  { email: 'emailB', name: 'nameB' }
]

const result = await sql.query(sql`
  INSERT INTO users (email, name) VALUES ${sql.valuesList(users)}
`)

// text: INSERT INTO users (email, name) VALUES ($1, $2), ($3, $4)
// values: ['emailA', 'nameA', 'emailB', 'nameB']

In that object case it's also possible to give a list of columns, which will be extracted:

const users = [
  { email: 'emailA', name: 'nameA', active: true },
  { email: 'emailB', name: 'nameB', active: true }
]

const result = await sql.query(sql`
  INSERT INTO users (email, name) 
    VALUES ${sql.valuesList(users, { columns: ['email', 'name'] })}
`)

// text: INSERT INTO users (email, name) VALUES ($1, $2), ($3, $4)
// values: ['emailA', 'nameA', 'emailB', 'nameB']
Clone this wiki locally