Open In App

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:

Return Value: It returns a substring of input string between a given starting position and length. If length is out of string then the extra part is ignored.



Module Installation: Install the mysql module using the following command:

npm install mysql

Database: Our SQL publishers table preview with sample data is shown below:

Example 1:




const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Notice the ? in query
    let query = `SELECT SUBSTRING("GeeksforGeeks"
                 8, 20) AS SUBSTRING_Output`;
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

Run the index.js file using the following command:

node index.js

Output:

Example 2:




const mysql = require("mysql");
  
let db_con  = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: '',
    database: 'gfg_db'
});
  
db_con.connect((err) => {
    if (err) {
      console.log("Database Connection Failed !!!", err);
      return;
    }
  
    console.log("We are connected to gfg_db database");
  
    // Notice the ? in query
    let query = `SELECT SUBSTRING(name, 1, 4) 
            AS SUBSTRING_Name FROM publishers`;
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});

Run the index.js file using the following command:

node index.js

Output:


Article Tags :