Sorting and Pagination
ORDER BY and LIMIT clauses are used to sort query results and limit the number of rows returned. This chapter introduces how to use these clauses.
ORDER BY Sorting
Basic Syntax
Ascending Order (Default)
Descending Order
Multi-Column Sorting
Sort by Expression
NULL Value Sorting
LIMIT Results
Basic Syntax
Limit Rows
OFFSET Skip Rows
Pagination
Calculate Pagination Parameters
Pagination Formula
TOP N Queries
Query Top N Records
Practical Examples
Product List Pagination
Latest Orders
Leaderboard
Performance Optimization
1. Create Indexes for Sort Columns
2. Avoid Deep Pagination
Different Database Syntax
MySQL
SQL Server
Oracle
Best Practices
- Always use ORDER BY with pagination
- Create indexes for sort columns
- Avoid deep pagination
- Use stable sort columns (like primary key)
- Consider cursor-based pagination instead of OFFSET
Summary
- ORDER BY: Sort results
- ASC/DESC: Ascending/descending
- LIMIT: Limit number of rows
- OFFSET: Skip specified rows
- Pagination: LIMIT + OFFSET for pagination
- Performance: Create indexes, avoid deep pagination
Next Step: Learn GROUP BY