How to Perform Complex Queries in MySQL with Node.js?
Last Updated :
14 Aug, 2024
MySQL is a colleague relational database management system that is used for complex queries to deal with intricate data manipulation works. This guide is dedicated to teaching the reader more about making elaborate queries with the help of Node. js and the mysql2 package Once you have installed js you then install the mysql2 package.
Prerequisites
Steps to Perform Complex Queries with Node.js
Step 1: Set Up the Node.js Project
Start by creating a new Node.js project and installing the necessary dependencies
mkdir geeksforgeeks
cd geeksforgeeks
npm init -y
npm install mysql2 dotenv nodemon
Project structure:
Project structureUpdated dependencies:
"dependencies": {
"dotenv": "^16.4.5",
"mysql2": "^3.11.0",
"nodemon": "^3.1.4"
}
Step 2: Create and Configure the .env File
Create a .env file in the root directory of your project to store your MySQL database credentials..
DB_HOST="localhost"
DB_USER="root"
DB_PASSWORD=""
DB_DATABASE="geeksforgeeks"
Step 3: Create a Database
- Open MySQL Workbench and connect to your MySQL server.
- Create the Database:
CREATE DATABASE geeksforgeeks;
Select the newly created database from the schema list.
Step 4: Create Tables
- Execute the following SQL script to create tables:
USE geeksforgeeks;
-- Create customers table
CREATE TABLE customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
-- Create orders table
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
total DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
-- Create products table
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
category VARCHAR(50)
);
Step 5: Insert Sample Data
- Execute the following SQL script to insert sample data:
INSERT INTO customers (name) VALUES ('Geeksfor'), ('Geeks');
INSERT INTO orders (customer_id, total) VALUES (1, 100.00), (2, 150.00);
INSERT INTO products (category) VALUES ('Education'), ('Coding');
After running the query After insertion tables will be:
customers table after insertion of data
orders table after insertion of data
products table after insertion of dataStep 6: Set Up the Database Connection
Create a db.js file to establish the connection between phpmyadmin and MySQL database.
JavaScript
// db.js
require('dotenv').config();
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database!');
});
module.exports = connection;
Step 7: Perform Complex Queries
Create a queries.js file to perform complex queries, such as joins, subqueries, and aggregations.
JavaScript
// queries.js
const db = require('./db');
// Example 1: Join Query
const joinQuery = `
SELECT orders.id, customers.name, orders.total
FROM orders
JOIN customers ON orders.customer_id = customers.id
`;
db.query(joinQuery, (err, results) => {
if (err) throw err;
console.log('Join Query Results:', results);
});
// Example 2: Subquery
const subquery = `
SELECT name, (SELECT COUNT(*) FROM orders WHERE
customer_id = customers.id) AS order_count
FROM customers
`;
db.query(subquery, (err, results) => {
if (err) throw err;
console.log('Subquery Results:', results);
});
// Example 3: Aggregation
const aggregationQuery = `
SELECT category, COUNT(*) AS product_count
FROM products
GROUP BY category
`;
db.query(aggregationQuery, (err, results) => {
if (err) throw err;
console.log('Aggregation Query Results:', results);
});
Step 8: Execute the project
For executing the project run the queries.js file:
node queries.js
Output:
OutputConclusion
In this guide, we have shown how to use Node and MySQL for the performing of the complex queries.js. Establishing a project using the mysql2 package and making several types of operations through the utilizing of API, enables you to work with and sort out data. In particular, this approach contributes to creating a solid base for a set of activities to work with large and extensive datasets in your Node.js applications.
Similar Reads
Performing complex queries in MongoDB with Node.js
MongoDB is a popular NoSQL database known for its flexibility and scalability. When working with the MongoDB in the Node.js application. We often need to perform complex queries to retrieve or manipulate the data effectively. This article will guide you through the various approaches to performing c
4 min read
How to Perform Geospatial Queries in MongoDB using Node.js?
A geospatial query involves searching for data based on geographic locations. It allows developers to identify and analyze data associated with specific coordinates or within a defined proximity of a given point. In a geospatial query, we can define a geographic shape, such as a point, line, or poly
6 min read
How to Use Connection Pooling with MySQL in Node.js?
MySQL is one of the most preferred relational databases, While Node.js is another name for JavaScript runtime environment. While assessing a large number of connections in the database in a Node. In this regard, effectiveness in managing them is also a significant determinant when developing and mai
3 min read
How to Use Prepared Statements in MySQL with Node.js
MySQL prepared a database by pre-compiling the SQL query with a set of placeholders for parameters. You could use the MySQL2 or MySQL library to be connected to your MySQL database and execute queries by passing the SQL statement with an array of values for the placeholders. It prevents SQL injectio
9 min read
How to Create and Use Stored Procedures in MySQL with Node.js?
Stored procedures in MySQL are very useful in the following ways Regarding the encapsulation of business logic within a database. They can be run multiple times and do not cause a large load on the client-server connection. In this tutorial, we will learn how to create and use stored procedures in M
3 min read
How to do pagination Node.js with MySQL ?
Node.js is a runtime environment like Chrome's V8 JavaScript engine. Node.js is an open-source, cross-platform, and backend runtime environment that executes outside a web browser.MySQL is an open-source relational database management system that is fast, reliable, flexible, and robust. Both MySQL a
8 min read
How to Perform Text Search in MongoDB using Node.js?
MongoDB is an open-source, cross-platform, No-SQL database that stores data in documents, which contain data in the form of key-value pairs. In this article, we will learn about how to perform text-based searches in MongoDB using node.js. Prerequisites Node.jsMongoDBMongoDB Atlas Connect with Applic
5 min read
How To Build Node.js Authentication System With MySQL?
Node.js is an open-source server-side JavaScript runtime environment established to develop server-side applications. The first task can be an implementation of an authentication system, this is one of the most frequently used processes in web development. In this article, we are going to learn how
4 min read
How to Optimize MongoDB Queries for Performance?
MongoDB is a popular NoSQL database known for its flexibility, scalability, and powerful capabilities in handling large datasets. However, to fully use MongoDB's potential, optimizing query performance is essential. Efficient MongoDB queries not only reduce response times but also help in lowering r
7 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications.In this article, we'll explore how to connect a Node.js application with a MySQL database, coveri
2 min read