Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Implement Search and Filtering in a REST API with Node.js and Express.js ?
Next article icon

How to Make a search function using Node Express and MYSQL

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to create a search function using Node with Express framework to search terms inside MYSQL tables.

Prerequisites:

  • MySQL
  • Node JS
  • Express JS

We will discuss the following methods to search:

Table of Content

  • Searching term with partial match
  • Searching term with exact matching
  • Searching term in multiple columns

Approach to make search function:

We're making a web application using Express.js and connecting it to a MySQL database. When users visit the '/search' route and provide a search term as a parameter, the app looks for that term in the database. If there's an error, we log it and send a 500 error. If not, we send back the search results in JSON format. We're using Node.js with Express for all this.

Steps to Create a Express application:

Step 1: Initialize npm (node package manager) using the following command

npm init

Step 2: Install mysql2 package using the following npm install command.

 npm install mysql2

Step 3: Create a new JavaScript file with .js extension (Example: app.js ) and write the code.

Step 4: For testing, create a new database and sample records using the following SQL query. Run the query in the MySQL workspace.

sql-query-sample-data
insert sample data

Project Structure:

NodeProj
Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.6.5",
}

Step 5: Run the application using following command:

node app.js

Step 6: Navigate to 'http://localhost:3000/search' and pass search term in the query using '?term= <search term>' .

Example: http://localhost:3000/search?term=geeksforgeeks

Note:

Important Note:
Replace host, user, password and database with your actual values.
Example:
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydatabase',
});

Approach 1: Searching term with partial match:

It performs a partial match on 'name' column using LIKE and % wildcard in SQL query. Search the term with partial match in 'name' column using the following query. The LIKE operator with search term surrounded by % allows for a partial match ( const searchValue = `%${searchTerm}%`; ).

Replace it with following SQL query:

const query = `
SELECT * FROM items
WHERE name LIKE ?
`;

Example: Below is the code example of Searching term with partial match:

JavaScript
const express = require('express'); const mysql = require('mysql2');  const app = express(); const port = 3000;  // MySQL connection const db =     mysql.createConnection({         host: 'localhost',         user: 'root',         password: 'root',         database: 'mydatabase',     });  // Connect to MySQL db.connect(err => {     if (err) {         console.error('Error connecting to MySQL:', err);     } else {         console.log('Connected to MySQL');     } });  // Search endpoint app.get('/search', (req, res) => {     const searchTerm = req.query.term;     if (!searchTerm) {         return res.status(400)             .json(                 {                     error: 'Search term is required'                 }             );     }      const query = `     SELECT * FROM items     WHERE name LIKE ?   `;      // Use '%' to perform a partial match     const searchValue = `%${searchTerm}%`;      db.query(query, [searchValue, searchValue],         (err, results) => {             if (err) {                 console                     .error('Error executing search query:', err);                 return res.status(500)                     .json(                         {                             error: 'Internal server error'                         });             }              res.json(results);         }); });  // Start the server app.listen(port, () => {     console.log(`Server is running on          http://localhost:${port}`); }); 

Output:

approach-1
match partially in 'name' column

Approach 2: Searching term with exact matching

Search the term with exact match in 'name' column using the following query. The = operator finds the exact match only.

Replace it with following SQL query:

const query = `
SELECT * FROM items
WHERE name = ?
`;

Example: Below is the code example of Searching term with exact matching

JavaScript
const express = require('express'); const mysql = require('mysql2');  const app = express(); const port = 3000;  // MySQL connection const db = mysql.createConnection({     host: 'localhost',     user: 'root',     password: 'root',     database: 'mydatabase', });  // Connect to MySQL db.connect(err => {     if (err) {         console.error('Error connecting to MySQL:', err);     } else {         console.log('Connected to MySQL');     } });  // Search endpoint app.get('/search', (req, res) => {     const searchTerm = req.query.term;      if (!searchTerm) {         return res.status(400)             .json(                 {                     error: 'Search term is required'                 });     }      const query = `     SELECT * FROM items     WHERE name = ?    `;      const searchValue = searchTerm;      db.query(query,         [searchValue,             searchValue],         (err, results) => {             if (err) {                 console.error('Error executing search query:', err);                 return res.status(500)                     .json(                         {                             error: 'Internal server error'                         });             }              res.json(results);         }); });  // Start the server app.listen(port, () => {     console.log(`Server is running          on http://localhost:${port}`); }); 

Output:

approach-2
match exact term in 'name' column

Approach 3: Searching term in multiple columns

It performs a partial match on both 'name' and 'description' columns using the % wildcard. Search the term with partial match in both 'name' and 'description' column using the following query. The LIKE operator with search term surrounded by % allows for a partial match ( const searchValue = `%${searchTerm}%`; ).

Replace it with following SQL query:

const query = 
`SELECT *
FROM items
WHERE name LIKE ? OR description LIKE ? `;

Example: Below is the code example of Searching term in multiple columns

JavaScript
const express = require("express"); const mysql = require("mysql2");  const app = express(); const port = 3000;  // MySQL connection const db = mysql.createConnection({     host: "localhost",     user: "root",     password: "root",     database: "mydatabase", });  // Connect to MySQL db.connect((err) => {     if (err) {         console.error("Error connecting to MySQL:", err);     } else {         console.log("Connected to MySQL");     } });  // Search endpoint app.get("/search", (req, res) => {     const searchTerm = req.query.term;      if (!searchTerm) {         return res.status(400).json({ error: "Search term is required" });     }      const query = `   SELECT * FROM items   WHERE name LIKE ? OR description LIKE ?   `;      //Use '%' to perform a partial match     const searchValue = `%${searchTerm}%`;      //const searchValue = searchTerm;      db.query(query, [searchValue, searchValue], (err, results) => {         if (err) {             console.error("Error executing search query:", err);             return res.status(500).json({ error: "Internal server error" });         }          res.json(results);     }); });  // Start the server app.listen(port, () => {     console.log(`Server is running on http://localhost:${port}`); }); 

Output:

approach-3
search in both 'name' and 'description' with partial match



Next Article
How to Implement Search and Filtering in a REST API with Node.js and Express.js ?
author
manikandansanmugam
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Geeks Premier League
  • Express.js
  • MySQL
  • Geeks Premier League 2023

Similar Reads

  • How to Create and Use Functions in MySQL with NodeJS?
    We will learn how to create and use functions in MySQL with Node.js. MySQL functions allow encapsulating complex calculations and business logic within the database, which can then be called from Node.js applications. This method is particularly useful for reusing SQL code and maintaining a clean ap
    3 min read
  • How To Make A GET Request using Postman and Express JS
    Postman is an API(application programming interface) development tool that helps to build, test and modify APIs.  In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
    3 min read
  • How to Implement Search and Filtering in a REST API with Node.js and Express.js ?
    Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In thi
    5 min read
  • Node.js MySQL FIND_IN_SET() Function
    FIND_IN_SET() function is a built-in function in MySQL that is used to get the position of the first occurrence of value string in a list of strings separated by comma(','). Syntax: FIND_IN_SET(value, list_of_string)Parameters: It takes two parameters as follows: value: It is the value to be searche
    2 min read
  • How to use Global functions in Express JS?
    In this article, we will learn the global function of Express. Express JS is a web application framework for Node JS. This framework runs on the server-side framework. It is a trendy Express JS framework for building scalable web applications. There are many functions available in Express JS that ar
    2 min read
  • How to add Search Feature in Next.js using Algolia ?
    Adding a search feature to your Next.js application can greatly enhance user experience by providing fast and relevant search results. Algolia is a powerful search-as-a-service solution that integrates seamlessly with Next.js to offer instant, full-text search capabilities. In this article, we will
    3 min read
  • Express.js res.sendStatus() Function
    The res.sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body. Syntax: res.sendStatus( statusCode )Parameter: The statusCode parameter describes the HTTP status code. Returns: It returns an Object. Installation of the
    2 min read
  • Node.js MySQL SUBSTRING() Function
    SUBSTRING() function is a built-in function in MySQL that is used to get a substring of input string between given range inclusive. Syntax: SUBSTRING(input_string, from, length)Parameters: It takes three parameters as follows: input_string: It is the given string for which the substring will be exec
    2 min read
  • How to insert request body into a MySQL database using Express js
    If you trying to make an API with MySQL and Express JS to insert some data into the database, your search comes to an end. In this article, you are going to explore - how you can insert the request data into MySQL database with a simple Express JS app. Table of Content What is Express JS?What is MyS
    3 min read
  • How to do a Full-Text Search in MongoDB using Mongoose
    In MongoDB, performing a full-text search allows us to query and retrieve documents based on textual content matching certain criteria. When using Mongoose, an ODM (Object Data Modeling) library for MongoDB in Node.js, conducting full-text search operations can be efficiently achieved using the Mong
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences