The SQL Order By clause is used to sort the result set of a query by on more columns. By default, the results are sorted in ascending order, but you can also sort them in descendinng order.
SQL Order By Syntax
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
SQL Order By Example
SQL Order By Descending Order Example
This query retrieves all columns from the PATIENTS table and sorts the results by the dob (date of birth) coluumn in descending order.
SELECT * FROM Patients ORDER BY dob DESC;
SQL Order By Several Columns Example
This query retrieves all columns from the DOCTORS table and sorts the results by the specialty column in ascending order. Within each specialty, it further sorts the results by the last_name column, also in ascending order.
SELECT * FROM Doctors ORDER BY specialty ASC, last_name ASC;
SQL Order By Using both Ascending and Descending Order Example
This query retrieves all columns from the APPOINTMENTS table and sorts the results by the STATUS column in ascending order. Within eash status category, it further sorts the results by the appointment_date column in descending order.
SELECT * FROM Appointments ORDER BY status ASC, appointment_date DESC;