Node.js MySQL Order By

🚀 Node.js MySQL – ORDER BY

The ORDER BY clause is used to sort records in ascending or descending order.

We’ll use mysql2 for all examples.


✅ 1. Install mysql2

npm install mysql2

✅ 2. Connect to Database


 


✅ 3. ORDER BY Single Column

Ascending (default)


Descending



✅ 4. ORDER BY Multiple Columns


  • First sorted by name ascending

  • Then by id descending for duplicate names


✅ 5. ORDER BY With WHERE



✅ 6. ORDER BY With LIMIT (Pagination)



✅ 7. Using Async/Await


 


✅ 8. Tips & Best Practices

  • Use indexes on columns used in ORDER BY for faster sorting.

  • Combine ORDER BY with LIMIT for pagination.

  • Always prefer prepared statements (?) for dynamic queries.

  • Multiple columns allow complex sorting (e.g., ORDER BY age DESC, name ASC).

You may also like...