EN
Node.js - MySQL BETWEEN clause
3
points
In this article, we would like to show you how to use SQL BETWEEN clause in Node.js.
Note: at the end of this article you can find database preparation SQL queries, you will also find an example of a more parameterized query there.
Between clause example
const mysql = require('mysql');
const connection = mysql.createConnection({ // gets connection with database
host: 'localhost', // '127.0.0.1'
user: 'root',
password: 'password',
database: 'database_name',
});
connection.connect((error) => {
if (error) throw error;
const query = 'SELECT * FROM `users` ' +
'WHERE `id` BETWEEN ? AND ?';
const values = [2, 4]; // id >= 2 AND id <= 4
connection.query(query, values, (error, result) => { // sends queries
connection.end(); // closes connection
if (error) throw error;
console.log(result);
});
});
Result:
[
{ id: 2, name: 'Chris', role: 'moderator' },
{ id: 3, name: 'Kate', role: 'user' },
{ id: 4, name: 'Denis', role: 'moderator' }
]
Note:
BETWEEN clause is used very often for dates.
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');
More parameterized query
// ...
connection.connect((error) => {
if (error) throw error;
const query = `SELECT *
FROM ??
WHERE ?? BETWEEN ? AND ?`;
const values = ['users', 'id', 2, 4]; // id >= 2 AND id <= 4
connection.query(query, values, (error, result) => { // sends queries
connection.end(); // closes connection
if (error) throw error;
console.log(connection.sql); // SELECT *
}); // FROM `users`
}); // WHERE `id` BETWEEN '2' AND '4'
The names of columns and tables can be placed in the query by a double question mark ??
.