Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL double sort

I would like to double sort my user list. Is this possible within one MySQL query?

  1. Sort by activity
  2. Sort by ID

For example:

1  Jack   Active 
2  Jill   Active 
5  Jens   Active  
3  Harry  Inactive 
4  Larry  Inactive 
6  Luke   Inactive
like image 602
John Avatar asked Apr 18 '12 15:04

John


People also ask

Can we have 2 ORDER BY in MySQL?

This sorts your MySQL table result in Ascending or Descending order according to the specified column. The default sorting order is Ascending which you can change using ASC or DESC . SELECT * FROM [table-name] ORDER BY [column-name1 ] [ASC|DESC] , [column-name2] [ASC|DESC],..

Can you ORDER BY 2 things in SQL?

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.

How do I create a secondary sort in MySQL?

When sorting your result set using the SQL ORDER BY clause, you can use the ASC and DESC attributes in a single SELECT statement. This example would return the records sorted by the category_id field in descending order, with a secondary sort by product_name in ascending order.

How do I sort multiple columns in MySQL?

Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.


2 Answers

You can use the ORDER BY clause to sort as many columns as needed.

SELECT id, name, activity
FROM userList
ORDER BY Activity, ID

I would suggest reading the MySQL ORDER BY docs. You can sort the data either in ASC or DESC order: MySQL: ORDER BY Optimization

like image 110
Taryn Avatar answered Oct 16 '22 19:10

Taryn


SELECT id, name, activity
FROM your_table
ORDER BY activity ASC, id ASC
like image 26
Ike Walker Avatar answered Oct 16 '22 18:10

Ike Walker