ORDER BY in SQL

📊 The ORDER BY clause is used to sort the result of an SQL query in either ascending or descending order. By default, SQL returns records in an unspecified order unless an ORDER BY clause is used. Sorting data makes query results easier to read, analyze, and present.

📖 What is ORDER BY?

The ORDER BY clause arranges rows based on the values of one or more columns. You can sort numeric values, text, dates, and even calculated expressions. It is most commonly used with the SELECT statement, although it can also be used in queries involving joins, subqueries, and views.

Information

The ORDER BY clause is usually written at the end of an SQL query, after clauses such as WHERE, GROUP BY, and HAVING.

📝 Basic Syntax

General Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC | DESC];

📊 Sample Table

Assume the following Students table:

StudentIDNameDepartmentMarks
101AliceComputer Science92
102BobMathematics85
103CharliePhysics88
104DavidComputer Science95

âŦ†ī¸ Sorting in Ascending Order

Use ASC to sort data in ascending order. If neither ASC nor DESC is specified, SQL sorts the data in ascending order by default.

Sort by Name (Ascending)

SELECT *
FROM Students
ORDER BY Name ASC;

Tip

Omitting ASC produces the same result because ascending order is the default sorting order.

Default Ascending Order

SELECT *
FROM Students
ORDER BY Name;

âŦ‡ī¸ Sorting in Descending Order

Use DESC to sort data from highest to lowest, or from Z to A for text values.

Sort by Marks (Descending)

SELECT Name, Marks
FROM Students
ORDER BY Marks DESC;

📑 Sorting by Multiple Columns

You can sort results using more than one column. SQL first sorts by the first column and then uses the next column to resolve ties.

Sort by Department and Name

SELECT *
FROM Students
ORDER BY Department ASC,
         Name ASC;

🔍 Combining WHERE and ORDER BY

The WHERE clause filters rows before the ORDER BY clause sorts the resulting records.

Filter and Sort Results

SELECT Name,
       Department,
       Marks
FROM Students
WHERE Department = 'Computer Science'
ORDER BY Marks DESC;

🧮 Sorting by Calculated Values

You can sort query results based on calculated expressions or aliases created in the SELECT statement.

Sort Using a Calculated Column

SELECT Name,
       Marks,
       Marks + 5 AS BonusMarks
FROM Students
ORDER BY BonusMarks DESC;

đŸ”ĸ Sorting by Column Position

SQL also allows sorting by the position of a column in the SELECT list. Although supported by many database systems, using column names is generally more readable and maintainable.

Sort by Column Position

SELECT StudentID,
       Name,
       Marks
FROM Students
ORDER BY 3 DESC;

Caution

Sorting by column position can make queries harder to understand and maintain, especially if the column order changes. Prefer using explicit column names.

📊 ORDER BY with NULL Values

When sorting columns that contain NULL values, different database systems may place NULL values at the beginning or end of the result set by default. Some databases also support explicit NULLS FIRST and NULLS LAST options.

Sorting NULL Values (Supported by Some Databases)

SELECT Name, Marks
FROM Students
ORDER BY Marks DESC NULLS LAST;

📊 Execution Order in a Query

Although ORDER BY appears near the end of an SQL statement, it is applied after the database has selected, filtered, grouped, and processed the data.

Execution StepClause
1 FROM
2 WHERE
3 GROUP BY
4 HAVING
5 SELECT
6 ORDER BY

đŸ’ŧ Real-World Example

Consider a university portal that displays the highest-scoring students in the Computer Science department. The administrator wants the students listed from the highest marks to the lowest.

Top Students by Marks

SELECT StudentID,
       Name,
       Marks
FROM Students
WHERE Department = 'Computer Science'
ORDER BY Marks DESC;

âš ī¸ Best Practices

Best Practice

Use ORDER BY only when sorted results are required, sort by indexed columns when possible for better performance, use explicit column names instead of column positions, and specify ASC or DESC clearly to improve query readability.

🚀 Key Points to Remember

  • 📌 ORDER BY sorts query results.
  • 📌 ASC sorts in ascending order and is the default.
  • 📌 DESC sorts in descending order.
  • 📌 Multiple columns can be used for sorting.
  • 📌 WHERE filters rows before ORDER BY sorts them.
  • 📌 Sorting by column names is recommended over column positions.
>>"The ORDER BY clause transforms unordered data into meaningful, organized information."

Summary

✅ The ORDER BY clause is an essential SQL feature for arranging query results in ascending or descending order. By combining it with clauses such as WHERE, GROUP BY, and calculated expressions, you can present data in a clear, structured, and user-friendly manner.