NodeJS MySQL Select Unique

NodeJS is an open-source, cross-platform runtime environment that uses JavaScript for creating fast, data-intensive, and secure server-side applications. 

These applications require some ways to store data in order to use them again. NodeJS supports all kinds of Databases, relational, and non-relational out of which MySQL can be the best choice.

MySQL is a relational database management system that stores data in one or more tables of rows and columns. It can be used in NodeJS to store large amounts of data and retrieve data quickly due to its simple structure using SQL. SQL stands for structured query languages which we can use to select the unique record from the MySQL table.

Also Read: Top 15 Best Programming Languages for Hacking

Query for Selecting Unique Records from MySQL Database

For selecting a unique record we can pass an additional parameter followed by the WHERE keyword after the query of selecting records.

SELECT * FROM tableName WHERE condition

We have already coved the entire concept of selecting the records from a MySQL table in another tutorial NodeJS MySQL Select Record.

Selecting Unique Records from MySQL using Node.js

Unique Record is selected in NodeJs from a MySQL table by passing the above SQL query as an argument to query() method of the connection object. This method also uses a callback function as an argument to check for the error and get the selected records. 

Syntax:

The code snippet for selecting unique records from a table in NodeJS is given below.

con.query("SELECT * FROM tableName WHERE condition", function (err, result) {
    if (err) throw err;
    console.log(result);
});

Here:

  • con is the connection object,
  • tableName is the name of the table from which the record is retrieved,
  •  * indicates that we are setting all columns
  • condition is used as a filter to select unique records

Example of Selecting Unique Records from MySQL using Node

Let’s see an example of selecting a unique record from a table.

Step 1: Run the MySQL server in the background.

For this, you can use XAMPP which is extremely fast, easy to install, and can run a MySQL server in one click.  

XAMPP Control Panel

Step 2: Create a folder(root directory) with a file “app.js” where we write our code and open it in a code editor.

Folder Structure

Step3: Open the terminal and type the below command to initiate NPM. 

npm init -y
Initiate NPM

Step 4: Type the below command to install the MySQL module.

npm i mysql
Install Sql

Step 5: Open the “app.js” file and import the MySQL module.

const mysql = require('mysql');

Step 6: Connect to the MySQL server using the createConnection() and connect() methods.

const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "newdatabase"
});

con.connect(function (err) {
    if (err) {
        throw err;
    }
    console.log("Connected to MySQL!");
});

We have a separate tutorial on creating MySQL connections using NodeJS if you want to read it.

We specified the database as “newdatabase” which we have created in another tutorial NodeJS MySQL Create Database.

Step 7: Create a new table. We have a separate tutorial on NodeJS MySQL Create Table if you want to read it.

con.query("CREATE TABLE temptable (id INT, name VARCHAR(255),email VARCHAR(255), age INT)", function (err, result) {
    if (err) throw err;
    console.log("Table created");
});

Step 8: Insert multiple records. We have covered the process of inserting multiple records in a separate tutorial NodeJS MySQL Insert Record.

var values = [  
    ['1', 'Aditya', '[email protected]', '22'],  
    ['2', 'Example', '[email protected]', '22'], 
    ['3', 'Rack', '[email protected]', '17'],  
    ['4', 'Jack', '[email protected]', '15'],
]; 

con.query("INSERT INTO temptable VALUES ?", [values], function (err, result) {
    if (err) throw err;
    console.log("Records inserted");
});

Step 9: Use the snippet we explain at the staring of this tutorial to run the query of selecting the unique records and pass a condition id = ‘1’ to select the record having id 1.

con.query("SELECT * FROM temptable WHERE id = '1'", function (err, result) {
    if (err) throw err;
    console.log(result);
});

Step 10: Type the below command to run the application.

node app.js

Compete Code:

const mysql = require('mysql');

const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "newdatabase"
});

con.connect(function (err) {
    if (err) {
        throw err;
    }
});

con.query("CREATE TABLE temptable (id INT, name VARCHAR(255),email VARCHAR(255), age INT)", function (err, result) {
    if (err) throw err;
});

var values = [  
    ['1', 'Aditya', '[email protected]', '22'],  
    ['2', 'Example', '[email protected]', '22'], 
    ['3', 'Rack', '[email protected]', '17'],  
    ['4', 'Jack', '[email protected]', '15'],
]; 

con.query("INSERT INTO temptable VALUES ?", [values], function (err, result) {
    if (err) throw err;
});

con.query("SELECT * FROM temptable WHERE id = '1'", function (err, result) {
    if (err) throw err;
    console.log(result);
});

Output:

Output

Check Out: PHP vs. Node.js – Which One is the Undoubted Back-end King

Frequently Asked Questions (FAQs)

Is MySQL server free?

Yes, using MySQL is absolutely free. Anyone can download MySQL software from “https://dev.mysql.com/downloads/mysql/” for free. It is also open source, which means people on the internet can contribute to it, making it even better. You can also modify its code according to your project requirement.  

Why is SQL called MySQL?

MySQL is an RDBMS that stands for relational database management system. MySQL is used to store, view, and manage relational data. On the other hand, SQL stands for Structured Query Language, by using it we can perform operations on relational databases like MySQL, PostgreSQL, SQLite, etc. Since MySQL is the most popular DBMS and SQL is the query language to perform operations on that, people usually confuse between two as both are used together and have similar names, in reality, both are different.

How to start a MySQL server?

You can use XAMPP software which is extremely fast, easy to install, and can run a MySQL server in one click. Just download the software from “https://www.apachefriends.org/“, install it, and then open it. You can find the MySQL option in the module list, to start the MySQL server just click the start button in front of it. You can see the log inside XAMPP once the server is up and running.

What is the full form of MySQL?

MySQL stands for “My Structured Query Language”, where “My” is the name of co-founder Michael Widenius’ daughter.

What is NodeJS used for?

Node.js is a runtime environment mainly used for creating servers, APIs, microservices and full stack websites. Node.js applications can easily interact with the operating system and file system. it can also create and manage all types of databases. Node.js is lightweight, cross-platform, and performs multiple operations simultaneously is the reason why it is so popular.

Is Node good with MySQL?

Yes, Node.js can interact with MySQL databases easily. It has a module “mysql” for this. But Node.js is usually good for NoSQL data like MongoDB however you can use it with MySQL as well.

How to link MySQL with NodeJS?

First, you need to install the MySQL module, for which, execute the following command “npm i mysql”, then import the MySQL module using require(), and then you can use the createConnection() and connect() methods for connecting to the MySQL database.

How to create a MySQL database with Node?

For creating a MySQL database using Node, first, install mysql module, then import it using require(), then use the createConnection() and connect() methods to connect to the database, then use the connection object and call the query() method and pass a SQL statement “CREATE DATABASE databaseName” with a callback as arguments to create a MySQL database of name databaseName.

How to write MySQL query in NodeJS?

In Node.js, you can take the advantage of connection object to call the query() method and pass a query as an argument to perform different operations on connect MySQL database.

Summary

The MySQL connection object has a method query() to run a SQL query directly in NodeJS. Records can be selected uniquely from a table by passing the SQL queries of selecting unique records as an argument to the query() method. Hope this Node.js and MySQL tutorial helps to learn the process of selecting unique records from a table.

Also Read:

Reference

https://www.npmjs.com/package/mysql

Aditya Gupta
Aditya Gupta
Articles: 161