How to use the avg function from knex

Find comprehensive JavaScript knex.avg code examples handpicked from public code repositorys.

knex.avg() calculates the average value of a specified column in a database table.

42
43
44
45
46
47
48
49
50
51
//   .select(knex.ref('id').as('identifier'))
//   .select(knex.ref('login').as('name'))
//   .from('users');

//const data = await knex.sum('age').from('users2');
//const data = await knex.avg('age').from('users2');
//const data = await knex.max('age').from('users2');
//const data = await knex.min('age').from('users2');

// const data = await knex.avg('sum_age').from(function () {
fork icon0
star icon0
watch icon1

+ 8 other calls in file

How does knex.avg work?

knex.avg is a method in the Knex query builder library that generates a SQL query to calculate the average value of a given column in a database table. It generates an SQL query with the AVG() function and returns a promise that resolves to the average value. The method takes a column name as its argument.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const knex = require("knex")({
  client: "mysql",
  connection: {
    host: "localhost",
    user: "your_database_user",
    password: "your_database_password",
    database: "your_database_name",
  },
});

knex("table_name")
  .avg("column_name as average")
  .then((result) => {
    console.log(result[0].average);
  })
  .catch((error) => {
    console.log(error);
  });

This code connects to a MySQL database using Knex and calculates the average value of a column in a table named table_name. The result of the query is returned as a Promise, which resolves to an array containing an object with a single property named average, representing the calculated average value. The result can be accessed using result[0].average.