SQL multiple column ordering

Viewed 1150761

How can I sort by multiple columns in SQL and in different directions. column1 would be sorted descending, and column2 ascending.

9 Answers
ORDER BY column1 DESC, column2

This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC
SELECT id,  
  first_name,
  last_name,
  salary
FROM employee
ORDER BY salary DESC, last_name; 

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query.

After the ORDER BY keyword, add the name of the column by which you’d like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column. If you want to use ascending (low to high) order, you can use the ASC keyword; this keyword is optional, though, as that is the default order when none is specified. If you want to use descending order, put the DESC keyword after the appropriate column (in the example, we used descending order for the salary column).

You can also sort or order by the Number of Characters in each Column you wish to sort by. Shown below is a sample which sorts by the first three characters of the First Name and by the last two characters in the name of the town.

SELECT *
FROM table_name
ORDER BY LEFT(FirstName, 3) ASC, LEFT(Town, 2);

Compiled through Intellij DataGrip

SELECT * FROM EMP ORDER BY DEPTNO ASC, JOB DESC;

TRY

'select * FROM users ORDER BY id DESC, name ASC, age DESC 
Related