Order By – Listing Query Result in a Specific Order

SELECT select_list FROM table_name ORDER BY sıralama_ifadesi1
[ASC | DESC], .., sıralama_ifadesiN [ASC | DESC];

SELECT actor_id, last_name FROM actor ORDER BY actor_id DESC;

SELECT title, fulltext FROM film ORDER BY title ASC;

SELECT first_name, last_name FROM customer ORDER BY last_name
DESC, first_name ASC;

When you query data from a table, the SELECT statement returns rows in an irregular order. The ORDER BY statement is used with the SELECT clause to sort the rows in the result set. The ORDER BY statement allows you to sort the rows returned by a SELECT clause in ascending or descending order based on a sort expression.

If you want to sort the result set by multiple columns or expressions, a comma (,) must be placed between the two columns or expressions to separate them. The ‘ASC’ option is used to sort the rows in ascending order and the ‘DESC’ option is used to sort the rows in descending order. If either ASC or DESC is not specified, ORDER BY defaults to ASC.

SELECT first_name, LENGTH(first_name) len FROM customer ORDER BY len DESC;

The query calculates the length (of characters) of the values in the first_name column in the customer table with the LENGTH() function.

Displays len as alias for the result of length columns and returns the results by sorting in descending order according to this column.