SQL ORDER BY is a powerful command that enables developers to sort query results based on specified columns. Here, we will explore the basics of SQL ORDER BY and demonstrate its usage with practical examples.
What is SQL ORDER BY?
SQL ORDER BY is a command used to sort the results of a SELECT statement based on one or more columns. This command sorts the data in either ascending or descending order, based on the user’s preference.
Syntax of SQL ORDER BY
The basic syntax of SQL ORDER BY is as follows:
1 2 3 4 5 |
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...; |
Here, we use the SELECT command to retrieve data from a specific table. The ORDER BY clause is then used to specify one or more columns by which we want to sort the query results. We can use the ASC (Ascending) or DESC (Descending) keyword to determine the sort order of the results.
Examples of SQL ORDER BY
To better understand SQL ORDER BY, let’s take a look at some examples.
Example 1: Sorting by a Single Column
Suppose we have a table called “employees” with the following columns: “id”, “name”, “age”, and “salary”. To sort the employees by their age, we can use the following SQL statement:
1 2 3 |
SELECT * FROM employees ORDER BY age; |
This statement will retrieve all the columns of the “employees” table and sort them by the “age” column in ascending order.
Example 2: Sorting by Multiple Columns
Suppose we want to sort the “employees” table by both “age” and “salary”. To do this, we can use the following SQL statement:
1 2 3 |
SELECT * FROM employees ORDER BY age, salary DESC; |
This statement will sort the query results first by the “age” column in ascending order and then by the “salary” column in descending order.
Example 3: Sorting by a Calculated Field
Suppose we want to sort the “employees” table by a calculated field that combines the “age” and “salary” columns. To do this, we can use the following SQL statement:
1 2 3 4 5 |
SELECT *, age+salary AS total_income FROM employees ORDER BY total_income DESC; |
This statement will retrieve all columns from the “employees” table and create a new calculated field called “total_income” by adding the “age” and “salary” columns. The query results will then be sorted in descending order based on the “total_income” column.
SQL ORDER BY Summary
SQL ORDER BY is a powerful command that enables developers to sort query results based on one or more columns. With the examples provided in this tutorial, you should have a solid understanding of how to use this command to sort data in either ascending or descending order. Whether you’re working with a small or large database, SQL ORDER BY can help you quickly and easily sort your data to meet your specific needs.