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
5 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
10 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 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, cover
2 min read
How to Use Transactions in MySQL with NodeJS?
Transactions in MySQL are used to execute a series of operations as a single unit of work, ensuring that all operations either succeed or fail together. This is crucial in maintaining data integrity, especially when dealing with complex operations that involve multiple database queries. In Node.js,
2 min read
How to use Sequelize in Node.js ?
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. Its features are solid transaction support, relations, eager and lazy loading, read replication and many more. Features of Sequelize: Sequelize is a third-party package to be precise its an Objec
2 min read
How To Perform a Find Operation With Sorting In MongoDB Using Node.js?
Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read
How to run Cron Jobs in Node.js ?
Cron jobs are scheduled tasks that run at specific intervals in the background, commonly used for maintenance or repetitive tasks. Users can schedule commands the OS will run these commands automatically according to the given time. It is usually used for system admin jobs such as backups, logging,
4 min read
How to Update value with put in Express/Node JS?
Express JS provides various HTTP methods to interact with data. Among these methods, the PUT method is commonly used to update existing resources. PrerequisitesNode JS Express JS In this article, we are going to setup the request endpoint on the server side using Express JS and Node JS. This endpoin
2 min read