Open In App

Node.js MySQL Limit Clause

Last Updated : 07 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

LIMIT Clause is used to set the maximum size of the number of rows in the output of SQL Query.

Syntax:

  • Select only 3 rows from 1st row of users table.
    SELECT * FROM users LIMIT 3
  • Select only 3 rows from the 2nd row of the users table.
    SELECT * FROM users LIMIT 3 OFFSET 1

Modules:

  • mysql: To handle MySql Connection and Queries
npm install mysql

SQL users table preview:

Example 1: Select 3 rows from 1st row of users table

Javascript




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 our query
    let query = 'SELECT * FROM users LIMIT 3';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});


Output:

Example 2: Select 4 rows from 4th row of users table

Javascript




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 offset is 3, this means choose from row 4
    let query = 'SELECT * FROM users LIMIT 4 OFFSET 3';
  
    db_con.query(query, (err, rows) => {
        if(err) throw err;
  
        console.log(rows);
    });
});


Output: There are only 3 rows from 4th row. so, output contains only 3 rows



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads