How to query with Knex — Basic
Build SELECT queries with knex('table').where() and return rows to the caller.
Learn: Knex builds parameterized queries—safer than string concatenation. Chain where, orderBy, and first() for one row. Await the query or return the promise to the caller.
Supplementary examples
List and read one
function list() {
return knex("pastes").select("paste_id", "name").orderBy("created_at", "desc");
}
function read(id) {
return knex("pastes").where({ paste_id: id }).first();
}Course example
function listTotalWeightByProduct() {
return knex("products")
.select(
"product_sku",
"product_title",
knex.raw(
"sum(product_weight_in_lbs * product_quantity_in_stock) as total_weight_in_lbs"
)
)
.groupBy("product_title", "product_sku");
}
Additional references & examples
- Knex.js documentation
Query builder, migrations, seeds, and connection configuration.
- PostgreSQL SELECT
SELECT, JOIN types, and filtering in PostgreSQL.