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

  1. Sort ascending: SELECT * FROM products ORDER BY price ASC;
  2. Sort descending: SELECT * FROM products ORDER BY price DESC;
  3. Sort by multiple columns: SELECT * FROM employees ORDER BY department ASC, last_name ASC;
  4. Sort by expression: SELECT * FROM orders ORDER BY quantity * unit_price DESC;
  5. Sort by column position: SELECT name, price FROM products ORDER BY 2 DESC;

Tips

  • Always specify ASC or DESC explicitly in complex queries for clarity.
  • Sorting on indexed columns is faster because the database can use the index order.

Common issues

  • ORDER BY on 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