SQL Examples

SQL Sorted Query

Sorted SQL Query

Sorted query with ORDER BY supports multi-column sorting for ordered results.

Understanding ORDER BY Clause

The ORDER BY clause in SQL is used to sort the result set of a query by one or more columns. Sorting can be done in ascending (ASC) or descending (DESC) order. By default, the ORDER BY clause sorts the result set in ascending order.

Basic ORDER BY Usage

To sort the results of a query on a single column, you can simply use the ORDER BY clause followed by the column name. For example, to sort a list of employees by their last name, you can use the following query:

Sorting in Descending Order

If you need to sort the results in descending order, you can append the DESC keyword to the column name. Here's how you can sort the employees by their last name in descending order:

Multi-Column Sorting

The ORDER BY clause can also be used to sort by multiple columns. When sorting by multiple columns, the result set is sorted by the first column, and then by the second column for rows with identical values in the first column. Here’s an example that sorts employees first by department and then by last name:

Combining ASC and DESC

You can mix ascending and descending order for different columns in a multi-column sort. For example, you can sort employees by department in ascending order and by last name in descending order using the following query:

Practical Example: Sorting with Aliases

In some cases, you might want to sort by a column that is the result of an expression or an alias. You can use the alias directly in the ORDER BY clause. Consider the following query that calculates the employee's full name and sorts by the full name:

Conclusion

The ORDER BY clause is a powerful tool in SQL that allows you to organize your query results in a meaningful way. Whether sorting by a single column or multiple columns, in ascending or descending order, it provides flexibility and control over how data is presented.