๐Ÿ” Node.js โ€“ MySQL Select From โ€“ Fetch Data from MySQL Tables Using Node.js


๐Ÿงฒ Introduction โ€“ Why Fetch Data from MySQL with Node.js?

In any dynamic application, retrieving data from a database is as essential as inserting it. With Node.js and the mysql module, you can use SQL SELECT queries to read records, apply filters, and display results in APIs, dashboards, or web pages.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to run basic SELECT queries using Node.js
  • Retrieve all records or filter by specific columns
  • Handle and format SQL query results
  • Use safe parameterized queries with placeholders

โš™๏ธ Setup โ€“ Import and Connect to MySQL

Ensure your MySQL connection is set up in db.js:

const mysql = require('mysql');

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'testdb'
});

db.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL');
});

module.exports = db;

๐Ÿ“ฅ Select All Records from a Table

const db = require('./db');

db.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log('All Users:', results);
});

๐Ÿงช Output:

[
  { id: 1, name: "Alice", email: "alice@example.com" },
  { id: 2, name: "Bob", email: "bob@example.com" }
]

๐Ÿ” Select Specific Columns

db.query('SELECT name, email FROM users', (err, results) => {
  if (err) throw err;
  console.log('User Names & Emails:', results);
});

๐Ÿงช Output:

[
  { name: "Alice", email: "alice@example.com" },
  { name: "Bob", email: "bob@example.com" }
]

๐ŸŽฏ Select with WHERE Clause (Filter Records)

const userId = 2;

db.query('SELECT * FROM users WHERE id = ?', [userId], (err, result) => {
  if (err) throw err;
  console.log('User Found:', result);
});

๐Ÿงช Output:

[{ id: 2, name: "Bob", email: "bob@example.com" }]

โœ… The ? placeholder safely escapes the inputโ€”protecting against SQL injection.


๐Ÿ”„ Using LIKE, ORDER BY, and LIMIT

db.query(
  "SELECT * FROM users WHERE name LIKE 'A%' ORDER BY name ASC LIMIT 5",
  (err, result) => {
    if (err) throw err;
    console.log('Filtered Users:', result);
  }
);

๐Ÿง  Use LIKE, ORDER BY, LIMIT for refined results and pagination.


๐Ÿงฑ Best Practices for SELECT Queries

โœ… Practice๐Ÿ’ก Why Itโ€™s Important
Use ? placeholdersPrevents SQL injection attacks
Select only required columnsReduces bandwidth and improves performance
Use LIMIT with large datasetsAvoids huge memory loads in production
Always check for empty resultsPrevents null errors in frontend/backend logic
Log or handle err in all queriesEnsures safe and debuggable operations

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

You now know how to read data from a MySQL database using SELECT queries in Node.js. Youโ€™ve learned how to apply filters, sort data, and safely handle user input using placeholders.

๐Ÿ” Key Takeaways:

  • Use SELECT * FROM table to get all rows
  • Filter using WHERE, LIKE, and LIMIT
  • Always use placeholders (?) for dynamic values
  • Retrieve only the columns you actually need

โš™๏ธ Real-world relevance:
Used in login validations, dashboard rendering, search filters, pagination, reports, and API endpoints.


โ“FAQs โ€“ Selecting Data from MySQL in Node.js


โ“ How do I fetch just one record using Node.js?
โœ… Use WHERE id = ? and access results[0] in the callback:

db.query('SELECT * FROM users WHERE id = ?', [1], (err, results) => {
  console.log(results[0]);
});

โ“ Can I perform JOINs with Node.js MySQL?
โœ… Yes! Use full SQL syntax like:

SELECT users.name, orders.amount 
FROM users 
JOIN orders ON users.id = orders.user_id;

โ“ What if the SELECT query returns no data?
โœ… You get an empty array ([]). Always check with:

if (results.length === 0) console.log('No results found');

โ“ Can I use async/await with SELECT in Node.js?
โœ… Yes. Use the mysql2/promise module and write:

const [rows] = await db.execute('SELECT * FROM users');

โ“ Is SELECT faster than INSERT in MySQL?
โœ… Generally yes, SELECT is faster unless scanning large tables or using complex joins.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ” Node.js โ€“ MySQL Select From

Or Copy Link

CONTENTS
Scroll to Top