Nodejs Mysql Order By

to create the MySQL select query with Order By clause in Nodejs, I have defined 2 steps.
Suppose, You have users table which has 4 records.

ID
Name
Age
1
John
35
2
Rom
31
3
Mathew
32
4
Sachin
38

Now, You want to get the user details based on age in ascending order.

Step:1) firstly create the connection.js file.


const mysql = require('mysql');
const config  = {
  connectionLimit : 10,
  host     : 'localhost', // Database hostname, 
  user     : 'root', // Database Username
  password : 'jnnn23nn', // Database Password,
  database : 'dbname', //Database Name
};

const pool = mysql.createPool(config);
// Export the pool
module.exports = pool;

IN the connection.js file, You have to include mysql package and create the connection pool.

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users Order By age', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 2, name: ‘Rom’, age: 31 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 4, name: ‘Sachin’, age: 38 } ]

Now, You want to get the user details based on age in descending order so change the query in Step2

Step:2) Now, create the select.js file and include the connection.js file and write the select query in this.


const pool  = require('./connection');

pool.getConnection(function(err, connection) {
  if (err) {
    console.error('error in db connection');
    return;
  }
  console.log('db is connected');
  return ;
}); 

pool.query('select * from users Order By age DESC', function (error, results) {
if (error) throw error;
console.log('result is: ', results);
});

Now, run the select.js file.


node select.js
Output:-
[ RowDataPacket { id: 4, name: ‘Sachin’, age: 38 },
RowDataPacket { id: 1, name: ‘John’, age: 35 },
RowDataPacket { id: 3, name: ‘Mathew’, age: 32 },
RowDataPacket { id: 2, name: ‘Rom’, age: 31 } ]