SQL ORDER BY

www.‮‬theitroad.com

SQL ORDER BY is a clause used to sort the result set of a SELECT statement in ascending or descending order based on one or more columns.

The syntax for ORDER BY is as follows:

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

Here, column1, column2, and so on represent the columns you want to retrieve from the table, table_name is the name of the table you want to retrieve data from, condition is an optional clause that specifies conditions for filtering data, column_name is the column name you want to sort the result set by, and ASC or DESC is optional and indicates the sort order (ascending or descending).

For example, the following statement retrieves all the data from the "employees" table and sorts it by the "last_name" column in ascending order:

SELECT * FROM employees ORDER BY last_name ASC;

You can sort the result set by multiple columns by listing them in the ORDER BY clause separated by commas. For example:

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

This statement retrieves all the data from the "employees" table and sorts it by the "last_name" column in ascending order and then by the "first_name" column in ascending order for employees with the same last name.