Applications and operations

Parameterize PostgreSQL queries

Pass values separately with $1 placeholders and return generated data in the same statement.

8 minute lesson

~~~

Pass untrusted values separately from SQL:

const result = await pool.query(
  `INSERT INTO app.notes (title, body)
   VALUES ($1, $2)
   RETURNING id, title`,
  ['Plan the week', 'Choose three priorities']
)

console.log(result.rows[0])

Placeholders represent values. They cannot represent table names, column names, or sort directions. Choose those from a fixed allowlist.

RETURNING gives the application the generated identifier without a second query.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →