SQL SQL Tutorial SQL Database



SQL Order By

SQL (Structured Query Language) is a programming language used to manage and manipulate relational databases. One of the most important features of SQL is the ability to sort data using the ORDER BY clause. The ORDER BY clause is used to sort the result set in ascending or descending order based on one or more columns.

Brief Explanation of SQL Order By

The ORDER BY clause is used to sort the result set in ascending or descending order based on one or more columns. The syntax for the ORDER BY clause is as follows:

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

The ORDER BY clause can be used with any SELECT statement and can sort the result set based on one or more columns. The ASC keyword is used to sort the result set in ascending order, while the DESC keyword is used to sort the result set in descending order.

For example, the following SQL statement sorts the result set of the "customers" table in ascending order based on the "customer_name" column:

SELECT * FROM customers
ORDER BY customer_name ASC;

The following SQL statement sorts the result set of the "customers" table in descending order based on the "customer_id" column:

SELECT * FROM customers
ORDER BY customer_id DESC;

Code Examples

Here are some code examples of using the ORDER BY clause in SQL:

Example 1: Sorting by a Single Column

SELECT * FROM employees
ORDER BY last_name ASC;

This SQL statement sorts the result set of the "employees" table in ascending order based on the "last_name" column.

Example 2: Sorting by Multiple Columns

SELECT * FROM employees
ORDER BY last_name ASC, first_name ASC;

This SQL statement sorts the result set of the "employees" table in ascending order based on the "last_name" column and then by the "first_name" column.

Example 3: Sorting by a Calculated Column

SELECT first_name, last_name, salary, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;

This SQL statement calculates the annual salary of each employee by multiplying their monthly salary by 12 and then sorts the result set in descending order based on the calculated "annual_salary" column.

Conclusion

The ORDER BY clause is a powerful feature of SQL that allows you to sort the result set of a SELECT statement in ascending or descending order based on one or more columns. By using the ORDER BY clause, you can easily organize and analyze large amounts of data in a meaningful way.

References

Activity