
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:
1 2 3 4 5 |
SELECT column1, column2, ..., columnN FROM table_name ORDER BY column1, column2, .. columnN ASC|DESC; |
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:
1 2 3 4 |
SELECT NAME, POSITION FROM EMPLOYEES ORDER BY NAME ASC; |
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:
1 2 3 4 |
SELECT NAME, POSITION FROM EMPLOYEES ORDER BY NAME DESC; |
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:
1 2 3 4 |
SELECT NAME, POSITION, SALARY FROM EMPLOYEES ORDER BY POSITION ASC, SALARY DESC; |
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.