ORDER

ORDER BY is used in SQL to sort the result of a query. It arranges the data in ascending or descending order based on one or more columns.

When we retrieve data from a table, the records may appear in any order. If we want the data to appear in a specific order, we use ORDER BY in the query.

Syntax

SELECT column_name
FROM table_name
ORDER BY column_name ASC or DESC

ASC means ascending order. In ascending order the data is arranged from smallest to largest. For example numbers from 1 to 100 or names from A to Z.

DESC means descending order. In descending order the data is arranged from largest to smallest. For example numbers from 100 to 1 or names from Z to A.

Example

SELECT name
FROM students
ORDER BY name ASC

This query will display the names of students in alphabetical order.

Another Example

SELECT marks
FROM students
ORDER BY marks DESC

This query will show the marks of students from highest to lowest.

Using ORDER BY with Multiple Columns

We can also sort data using more than one column.

Example

SELECT name, marks
FROM students
ORDER BY marks DESC, name ASC

In this query, the data is first sorted by marks in descending order. If two students have the same marks, then their names are sorted in ascending order.

Conclusion

ORDER BY helps organize the result of a query in a clear and meaningful way. It makes the data easier to read and analyze.

Home » SQL Foundations Program (SQL-101) > Basic Queries > ORDER BY