Sorting with ORDER BY
Sort query results with ORDER BY — ascending and descending
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
ORDER BY sorts the rows returned by a query.
SELECT name, salary
FROM employees
WHERE department = 'Engineering'
ORDER BY salary DESC;Direction:
ASC— ascending (smallest/earliest first) — this is the default if you don't specify oneDESC— descending (largest/latest first)
Sorting by multiple columns — ties in the first column are broken by the second: ``sql SELECT * FROM employees ORDER BY department ASC, salary DESC;
Clause order matters: WHERE always comes before ORDER BY. ``sql SELECT * FROM employees WHERE department = 'Engineering' -- filter first ORDER BY salary DESC; -- then sort
Examples
Multi-column sort
Groups rows by department alphabetically, then sorts each group by salary high to low
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;How well did you understand this?
Next in SQL & Databases
Limiting Results with LIMIT