
Mysql Limit in NodeJs
In MySQL with Node.js, the LIMIT
clause is used to restrict the number of records returned in a query β super useful for pagination or performance optimization.
Letβs walk through how to use LIMIT
in your Node.js app π
β Step 1: Install MySQL package
npm install mysql const mysql = require('mysql');const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase'});connection.connect();const sql = 'SELECT * FROM users LIMIT 3';connection.query(sql, (err, results) => { const page = 2;const limit = 3;const offset = (page - 1) * limit;const sql = 'SELECT * FROM users LIMIT ? OFFSET ?';connection.query(sql, [limit, offset], (err, results) => { if (err) throw err; console.table(results);});
πΉ Using mysql2
(async/await)
const mysql = require('mysql2/promise');async function fetchLimitedUsers() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const [rows] = await connection.execute('SELECT * FROM users LIMIT ?', [3]); console.table(rows); await connection.end();}fetchLimitedUsers();
π§ Bonus: Sort + Limit
SELECT * FROM users ORDER BY age DESC LIMIT 2;
This returns the top 2 oldest users.