Example Order by in mysql with nodejs

Sort the Result

Use the ORDER BY statement to sort the result in ascending or descending order.

The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword.

Example: Sort the result alphabetically by name

 

var mysql = require('mysql');

var con = mysql.createConnection({

  host: "localhost",

  user: "root",

  password: "",

  database: "mydb"

});

con.connect(function(err) {

  if (err) throw err;

  con.query("SELECT * FROM customers ORDER BY name", function (err, result) {

    if (err) throw err;

    console.log(result);

  });

});

 

Run and result:

 

C:\Nodejs>node mysqlOrderByData.js

 [ RowDataPacket { id: 1, name: 'nam1', address: 'Highway 71' },

  RowDataPacket { id: 10, name: 'name10', address: 'Yellow Garden 2' },

  RowDataPacket { id: 2, name: 'name2', address: 'Lowstreet 4' },

  RowDataPacket { id: 3, name: 'name3', address: 'Apple st 652' },

  RowDataPacket { id: 4, name: 'name4', address: 'Mountain 21' },

  RowDataPacket { id: 5, name: 'name5', address: 'Valley 345' },

  RowDataPacket { id: 6, name: 'name6', address: 'Ocean blvd 2' },

  RowDataPacket { id: 7, name: 'name7', address: 'Green Grass 1' },

  RowDataPacket { id: 8, name: 'name8', address: 'Sky st 331' },

  RowDataPacket { id: 9, name: 'name9', address: 'One way 98' } ]

 

ORDER BY DESC

Use the DESC keyword to sort the result in a descending order.

Example: Sort the result reverse alphabetically by name

 

var mysql = require('mysql');

var con = mysql.createConnection({

  host: "localhost",

  user: "root",

  password: "",

  database: "mydb"

});

con.connect(function(err) {

  if (err) throw err;

  con.query("SELECT * FROM customers ORDER BY name DESC", function (err, result) {

    if (err) throw err;

    console.log(result);

  });

});

 

Run and result:

 

C:\Nodejs>node mysqlOrderByData.js

[ RowDataPacket { id: 9, name: 'name9', address: 'One way 98' },

  RowDataPacket { id: 8, name: 'name8', address: 'Sky st 331' },

  RowDataPacket { id: 7, name: 'name7', address: 'Green Grass 1' },

  RowDataPacket { id: 6, name: 'name6', address: 'Ocean blvd 2' },

  RowDataPacket { id: 5, name: 'name5', address: 'Valley 345' },

  RowDataPacket { id: 4, name: 'name4', address: 'Mountain 21' },

  RowDataPacket { id: 3, name: 'name3', address: 'Apple st 652' },

  RowDataPacket { id: 2, name: 'name2', address: 'Lowstreet 4' },

  RowDataPacket { id: 10, name: 'name10', address: 'Yellow Garden 2' },

  RowDataPacket { id: 1, name: 'nam1', address: 'Highway 71' } ]