How do I retrieve records from a table in a specific order using SQL?

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


When working with databases, you may sometimes need to retrieve data in a specific order. The SQL (Structured Query Language) language has a built-in functionality for that – the ORDER BY clause. This command allows you to sort the data from your database columns either in ascending (ASC) or descending (DESC) order.

Basic Usage of ORDER BY

The ORDER BY clause is used in the SELECT statement format as follows:

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

ASC Order Example:

Assume we have the following EMPLOYEES table and we want to sort the results by the NAME column in ascending order. We would write our SQL query like this:

This will return a record-set with the employee names arranged from A-Z.

DESC Order Example:

To get the same records in descending order (i.e. Z-A), you would use the DESC keyword instead:

The DESC keyword sorts the records in descending order.

Sorting By Multiple Columns

You can also sort your result-set by more than one column. The database sorts the result-set by the first column and then sort the sorted result set by the next column and so on.

Multiple Columns Order Example:

This will return a record-set with records sorted by POSITION ascendant (A-Z) and then by SALARY in a descendant way (from high to low).

The ORDER BY keyword in SQL is a powerful tool that allows you to sort through and organize your data in ways that are meaningful and useful for your specific needs.

Leave a Comment