Order By Clause in SQL
ORDER BY Clause in SQL
The ORDER BY clause is used to sort the result set of a SQL query based on one or more columns. You can sort in ascending or descending order.
Syntax:
SELECT column1, column2, ...FROM table_nameORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;ASC= Ascending order (smallest to largest, A to Z). This is the default.DESC= Descending order (largest to smallest, Z to A).
Example:
Retrieve all employees sorted by their salary from highest to lowest:
SELECT employee_name, salaryFROM employeesORDER BY salary DESC;Example with multiple columns:
Sort employees by department ascending, then by salary descending within each department:
SELECT employee_name, department_id, salaryFROM employeesORDER BY department_id ASC, salary DESC;Important Points:
The
ORDER BYclause comes after theWHEREandGROUP BYclauses (if used).If you omit
ASCorDESC,ASCis assumed by default.You can order by column name, alias, or column position (e.g.,
ORDER BY 1orders by the first selected column).Sorting on text columns is usually case-insensitive, but this depends on the database collation settings.
If you want, I can provide examples on how ORDER BY works with NULL values or how it affects query performance.