- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js MySQL Select From
In Node.js, retrieving data from a MySQL database is a fundamental task for building any data-driven application. Using the mysql2 package the modern, faster successor to the original mysql driver you can execute SELECT statements to fetch records. Whether you are building a user dashboard, a product list, or a reporting tool, understanding how to query data efficiently is essential.
mysql package is still around, most modern Node.js developers prefer mysql2 because it is faster and has native support for Promises, making your code much cleaner.
Key Features of Node.js MySQL Select From
- Basic Select Query: Pulling every record from a table for simple data migrations or small datasets.
- Select with Conditions: Using the
WHEREclause to target specific records, such as finding a user by their unique ID. - Select with Multiple Columns: Improving performance and security by fetching only the data you actually need (e.g.,
usernameandemailonly). - Order Results: Sorting your data using
ORDER BYso it appears correctly in your application's UI (like sorting blog posts by date). - Asynchronous Operations: Leveraging Node's non-blocking nature using modern
async/awaitor traditional callbacks to keep your app responsive.
Step 1 Prerequisites
Before writing code, ensure you have a MySQL server running and a database ready. You also need to initialize your Node.js project and install the driver. Open your terminal in your project folder and run:
npm install mysql2
.env file and the dotenv package to keep your secrets safe.
Step 2 Select All Records from a Table
The simplest way to retrieve data is using SELECT *. This tells the database to return every column for every row in the specified table. This is great for debugging or small tables, but should be used sparingly in production.
Example Code
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // Your MySQL username
password: 'password123', // Your MySQL password
database: 'testdb' // Your database name
});
// Connect to MySQL
connection.connect((err) => {
if (err) {
console.error('Database connection failed:', err.stack);
return;
}
// Select all records from the table
const selectQuery = 'SELECT * FROM users';
connection.query(selectQuery, (err, results) => {
if (err) {
console.error('Error executing query:', err.stack);
return;
}
// results is an array of objects
console.log('Total records retrieved:', results.length);
console.log(results);
});
// Always close the connection when done
connection.end();
});
SELECT * on tables with millions of rows or very large "text" or "blob" columns can slow down your application and consume excessive memory.
Output:
Records retrieved: [
{ id: 1, name: 'John Doe', email: '[email protected]' },
{ id: 2, name: 'Jane Doe', email: '[email protected]' }
]
Step 3 Select Specific Columns
In real-world applications, you rarely need every single column. For example, if you are displaying a list of names in a sidebar, you don't need to fetch their bio, password hashes, or timestamps. Specifying columns makes your queries faster and more secure.
Example Code
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password123',
database: 'testdb'
});
connection.connect((err) => {
if (err) return console.error(err);
// We only fetch 'name' and 'email'
const selectQuery = 'SELECT name, email FROM users';
connection.query(selectQuery, (err, results) => {
if (err) throw err;
console.log('Selected columns:', results);
});
connection.end();
});
Output:
Selected columns retrieved: [
{ name: 'John Doe', email: '[email protected]' },
{ name: 'Jane Doe', email: '[email protected]' }
]
Step 4 Select with Conditions
To find specific data, we use the WHERE clause. In Node.js, it is critical to use placeholders (the ? symbol) to pass values into your query. This technique is called a Prepared Statement.
Example Code
const mysql = require('mysql2');
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'testdb' });
connection.connect((err) => {
if (err) return;
// Use '?' as a placeholder for security
const selectQuery = 'SELECT * FROM users WHERE name = ?';
const nameToSearch = 'John Doe';
connection.query(selectQuery, [nameToSearch], (err, results) => {
if (err) throw err;
console.log('Search Result:', results);
});
connection.end();
});
"WHERE name = '" + name + "'"). This makes your application vulnerable to SQL Injection attacks, where users can steal or delete your entire database.
Output:
Records retrieved: [
{ id: 1, name: 'John Doe', email: '[email protected]' }
]
Step 5 Select with Ordering
When displaying data to users, order matters. You can sort results in ascending order (ASC) or descending order (DESC). For example, you might want to show the newest users first by sorting by id or created_at in descending order.
Example Code
// Sorting users alphabetically by name
const selectQuery = 'SELECT * FROM users ORDER BY name ASC';
connection.query(selectQuery, (err, results) => {
if (err) throw err;
console.log('Users sorted by name:', results);
});
ORDER BY last_name ASC, first_name ASC will sort by last name first, then by first name for people with the same last name.
Output:
Ordered records: [
{ id: 2, name: 'Alice', email: '[email protected]' },
{ id: 1, name: 'Bob', email: '[email protected]' }
]
Step 6 Using Promises with Select Query
Modern Node.js development relies heavily on async/await. The mysql2 package provides a promise-based wrapper that eliminates "callback hell" and makes your code look like synchronous logic, which is much easier to read and maintain.
Example Code with Promises
const mysql = require('mysql2/promise');
async function selectData() {
// Use mysql.createConnection from the 'promise' export
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'testdb'
});
try {
// execute() returns an array: [rows, fields]
const [rows] = await connection.execute('SELECT * FROM users WHERE id = ?', [1]);
if (rows.length > 0) {
console.log('User found:', rows[0]);
} else {
console.log('No user found with that ID.');
}
} catch (err) {
console.error('Database Error:', err.message);
} finally {
// Ensure the connection closes even if an error occurs
await connection.end();
}
}
selectData();
try...catch...finally with Promises. The finally block is the perfect place to call connection.end(), ensuring you don't leak database connections if an error occurs during the query.
Summary
Retrieving data in Node.js with MySQL is a straightforward process once you master the mysql2 package. By using specific column selection, you keep your app efficient; by using placeholders (?), you keep it secure; and by using Promises with async/await, you keep your code clean. Always remember to handle potential connection errors and close your connections to maintain a healthy database environment.