Languages
[Edit]
EN

Node.js - MySQL ORDER BY

0 points
Created by:
Dirask JS Member
3430

In this article, we would like to show you how to use SQL ORDER BY in Node.js.

Note: at the end of this article you can find database preparation SQL queries.

const mysql = require('mysql');

const connection = mysql.createConnection({              // gets connection with database
    host: 'localhost',  // '127.0.0.1'
    user: 'root',
    password: 'password',
    database: 'my_database',
});

connection.connect(error => {
    if (error) throw error;
    const query = 'SELECT * ' + 
                  'FROM `users` ' +
                  'ORDER BY ??';
    const value = ['name'];                // SELECT * FROM `users` ORDER BY `name`

    connection.query(query, value, (error, result) => {  // sends queries and receives results
        connection.end();                                // closes connection
        if (error) throw error;
        console.log(result);
    });
});

Result: 

[
    { id: 2, name: 'Chris', role: 'moderator' },
    { id: 4, name: 'Denis', role: 'moderator' },
    { id: 1, name: 'John',  role: 'admin' },
    { id: 3, name: 'Kate',  role: 'user' }
]

Descending order:

const mysql = require('mysql');

const connection = mysql.createConnection({             // gets connection with database
    host: 'localhost',  // '127.0.0.1'
    user: 'root',
    password: 'password',
    database: 'my_database',
});

connection.connect(error => {
    if (error) throw error;
    const query = 'SELECT * ' + 
                  'FROM `users` ' +
                  'ORDER BY ?? DESC';
    const value = ['id'];                      // SELECT * FROM `users` ORDER BY `id` DESC

    connection.query(query, value, (error, result) => { // sends queries and receives results
        connection.end();                               // closes connection
        if (error) throw error;
        console.log(result);
    });
});

Result: 

[
    { id: 4, name: 'Denis', role: 'moderator' },
    { id: 3, name: 'Kate',  role: 'user' },
    { id: 2, name: 'Chris', role: 'moderator' },
    { id: 1, name: 'John',  role: 'admin' }
]

Database preparation

create_tables.sql file:

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(100) NOT NULL,
	`role` VARCHAR(15) NOT NULL,
	PRIMARY KEY (`id`)
)
ENGINE=InnoDB;

insert_data.sql file:

INSERT INTO `users`
	(`name`, `role`)
VALUES
	('John', 'admin'),
	('Chris', 'moderator'),
	('Kate', 'user'),
	('Denis', 'moderator');

Node.js - MySQL

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join