How to sort results with ORDER BY
· Category: SQL & Databases
Short answer
ORDER BY sorts the result set by one or more columns in ascending (ASC) or descending (DESC) order.
Steps
- Sort ascending:
SELECT * FROM products ORDER BY price ASC; - Sort descending:
SELECT * FROM products ORDER BY price DESC; - Sort by multiple columns:
SELECT * FROM employees ORDER BY department ASC, last_name ASC; - Sort by expression:
SELECT * FROM orders ORDER BY quantity * unit_price DESC; - Sort by column position:
SELECT name, price FROM products ORDER BY 2 DESC;
Tips
- Always specify
ASCorDESCexplicitly in complex queries for clarity. - Sorting on indexed columns is faster because the database can use the index order.
Common issues
ORDER BYon calculated fields without an alias may be hard to maintain.- Sorting large result sets without a limit can cause high memory usage and slow response times.r