Open In App

Node.js MySQL LOCATE() Function

LOCATE() Function is a Builtin function in MySQL which is used to get position of first occurrence of a pattern in a text when searched from specific position.

Note: It is Not Case Sensitive.



Syntax:

LOCATE(pattern, text, starting_position)

Parameters: LOCATE() function accepts three parameters as mentioned above and described below.



Return Value: LOCATE() function returns position of the first occurrence of a pattern in a text when searched from specific position. If something went wrong it will return 0.

Modules:

npm install mysql

SQL publishers Table Preview:

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");
  
  // here is the query
  let query = `SELECT LOCATE('for', 'GeeksForGeeks', 3) AS Position`;
  
  db_con.query(query, (err, rows) => {
    if (err) throw err;
  
    console.log(rows);
  });
});

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");
  
  // here is the query
  let query = `SELECT name, LOCATE('n', name) AS Position FROM publishers`;
  
  db_con.query(query, (err, rows) => {
    if (err) throw err;
  
    console.log(rows);
  });
});

Output:


Article Tags :