How to use SQL order by.

“Order by is a keyword in SQL used to sort the query results. It allows for sorting of the results based on specified columns or expressions, and can specify either ascending or descending order.”

Syntax:
SELECT column1, column2, …
FROM table_name
ORDER BY column1 [ascending|descending], column2 [ascending|descending], …

“In this case, column1, column2, … are the names of the columns to be sorted, which can be one or multiple column names separated by commas. table_name is the name of the table to be queried. ASC indicates sorting in ascending order, which is the default. DESC indicates sorting in descending order.”

Example:

  1. Sort by individual column:
    SELECT * FROM customers
    ORDER BY last_name; – Sort in ascending order by the last_name column.

Sort the customers by last name in descending order.

  1. Sort by multiple columns:
    SELECT * FROM customers
    ORDER BY last_name, first_name; – Ascending order by last_name first, then first_name.

Sort customers by last name in descending order and then by first name in ascending order.

  1. Sort using the expression:
    SELECT * FROM customers
    ORDER BY YEAR(birth_date) DESC; – Sorting in descending order based on the year extracted from the birth_date column.

Notes:

  1. When using ORDER BY, the query results will be arranged in the specified sorting order. If no sorting order is specified, it defaults to ascending order.
  2. In the ORDER BY clause, you can use the position number of a column (starting from 1) instead of just the column name.
  3. Expressions such as functions, arithmetic operators, etc. can be used in the ORDER BY clause.
bannerAds