Home Tutorials SQL Tutorial ORDER BY Clause
ORDER BY Clause

ORDER BY Clause


The ORDER BY Clause

Definition: The ORDER BY clause is used to sort the result-set of a query in either ascending or descending order. By default, most databases return records in the order they were inserted; ORDER BY allows you to control exactly how that data is presented.

Why: Organized output is a critical requirement for professional reports and applications. Sorting is a core part of beginner SQL plans because it allows users to quickly identify trends, such as the highest sales, the youngest students, or alphabetical lists of names.


Syntax

The ORDER BY clause is placed at the very end of your SQL statement. You specify the column you want to sort by, followed by the direction (ASC or DESC).

SELECT column1, column2
FROM table_name
ORDER BY column1 ASC | DESC;

Example: Descending Sort

To view all students starting with the oldest at the top of the list, you would sort the age column in descending order:

SELECT *
FROM students
ORDER BY age DESC;

Sorting Directions

Keyword Meaning Result Behavior
ASC Ascending Sorts from smallest to largest (1 to 10) or A to Z. This is the default setting.
DESC Descending Sorts from largest to smallest (10 to 1) or Z to A.

Key Notes

  • Default Sorting: If you omit the keyword (e.g., ORDER BY name), the database will automatically sort in ASC (ascending) order.
  • Multiple Columns: You can sort by more than one column. For example, ORDER BY city ASC, name ASC will sort the list by city first, and then sort students alphabetically within each city.
  • Text vs. Numbers: Sorting works on both types. Numbers are sorted by value, while text (VARCHAR) is sorted alphabetically.
  • Position in Query: The ORDER BY clause must always come after the WHERE clause if you are using both in the same query.

🏋️ Test Yourself With Exercises

Take our quiz on ORDER BY Clause to test your knowledge.

Browse Quizzes »