The ORDER BY clause in MariaDB is used to sort the result set in ascending or descending order based on one or more columns.
The basic syntax of ORDER BY clause is as follows:
SELECT column1, column2, …, columnN
FROM table\_name
[WHERE condition]
ORDER BY column1, .. columnN [ASC[ENDING]|DESC[ENDING]];
- ASC or DESC keyword is used for sorting in ascending or descending order respectively. By default, ASC is used.
Here are some examples:
Example 1 – sort by one column:
SELECT \* FROM employees
ORDER BY first\_name;
This will return all records from the employees table, sorted by the first\_name in ascending order.
Example 2 – sort by more than one column:
SELECT \* FROM employees
ORDER BY first_name, last_name;
This will return all records from the employees table, sorted by the first_name. If some rows have the same first_name, those will be sorted by last\_name.
Example 3 – sort in descending order:
SELECT \* FROM employees
ORDER BY salary DESC;
This will return all records from the employees table, sorted by the salary in descending order.
The ORDER BY clause can also be used with aggregate functions:
SELECT COUNT, country
FROM customers
GROUP BY country
ORDER BY COUNT DESC;
This will return the number of customers in each country, sorted by the number of customers in descending order.