Node.js MySQL ORDER BY Clause
Node.js MySQL ORDER BY: Sorting Query Results Safely
MySQL's ORDER BY clause sorts SELECT query rows in ascending (ASC, default) or descending (DESC) order across one or more columns. When Node.js APIs accept query parameters like ?sort=price&dir=asc, validating column names against an allowlist is essential because SQL prepared placeholders cannot parameterize column names or ASC/DESC.
Safe Dynamic Sorting with an Allowlist Map
Never interpolate req.query.sort directly into SQL—an attacker could inject subqueries or syntax errors. Map allowed API field names through a Map or plain object lookup, and normalize the direction strictly to 'ASC' or 'DESC'.
import { pool } from './db.js';
const SORTABLE_COLUMNS = {
newest: 'created_at',
price: 'unit_price',
title: 'title',
};
export async function listCatalogItems({ sortBy = 'newest', direction = 'DESC', limit = 20 }) {
const column = SORTABLE_COLUMNS[sortBy] || 'created_at';
const dir = String(direction).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const safeLimit = Math.min(100, Math.max(1, Number(limit) || 20));
// Add `, id ASC` as a deterministic tie-breaker for stable pagination
const sql = `
SELECT id, title, unit_price, created_at
FROM products
WHERE is_active = ?
ORDER BY ${column} ${dir}, id ${dir}
LIMIT ?
`;
const [rows] = await pool.query(sql, [1, safeLimit]);
return rows;
}
Why Tie-Breakers and Indexes Matter
If 50 products share the same created_at timestamp, sorting solely by ORDER BY created_at DESC lets MySQL return tied rows in arbitrary order across pages. Adding , id DESC guarantees consistent page ordering. Also add database indexes on columns frequently used in WHERE + ORDER BY so MySQL avoids slow Using filesort operations.
Common Mistakes to Avoid
- Passing column names as
?placeholders (ORDER BY ?): MySQL treats'price'as a constant string literal instead of a column name, leaving rows completely unsorted! - Interpolating unvalidated
req.query.sortdirectly: Writing`ORDER BY ${req.query.sort}`creates an immediate SQL injection vulnerability. - Sorting before filtering: Always put selective
WHEREconditions beforeORDER BYandLIMITso MySQL sorts only matching rows.
Frequently Asked Questions
How do I sort by multiple columns in MySQL?
Separate columns with commas, each with its own direction—for example, ORDER BY category ASC, unit_price DESC.
Where do NULL values appear when sorting with ORDER BY?
In MySQL, NULL values come first in ASC order and last in DESC order. To push NULLs to the end when sorting ascending, use ORDER BY published_at IS NULL ASC, published_at ASC.
Why did pool.execute() fail with LIMIT ? in older MySQL setups?
Some versions require integers rather than stringified parameters for LIMIT; pool.query(sql, [1, Number(limit)]) or explicit integer casting works cleanly.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.