Open In App

Node.js MySQL SUM() Function

We use the SUM() function in MySQL to get Sum of the value of some columns.

Syntax:



SUM(column_name)

Parameters: SUM() function accepts a single parameter as mentioned above and described below.

Module Installation: Install the mysql module using the following command.



npm install mysql

Database: Our SQL publishers table preview with sample data is shown below:

Example 1:




const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.on('error', (err) => {
    console.log(err.code);
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err.code);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Here is the query
    let query = "SELECT SUM(salary) AS total_salary FROM publishers";
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

Run the index.js file using the following command:

node index.js

Output:

Example 2:




const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.on('error', (err) => {
    console.log(err.code);
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err.code);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Here is the query
    let query = "SELECT SUM(salary) AS total_salary FROM 
                 publishers WHERE id BETWEEN 2 AND 7";
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

Run the index.js file using the following command:

node index.js

Output:


Article Tags :