Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL order by both Ascending and Descending sorting

Tags:

sql

sorting

mysql

I have a mysql table with products.

The products have a category ID and a name.

What I'd like to do is order by category id first descending order and then order by product name ascending order.

SELECT * FROM `products` ORDER BY `products`.`product_category_id`,`naam` DESC 

What i'd like is

SELECT * FROM `products` ORDER BY `products`.`product_category_id`,`naam` DESC,ASC 

but that unfortunately doesn't work.

Is this even possible in mysql to define the sorting order of the second sorting column?

like image 219
Tschallacka Avatar asked Nov 20 '12 07:11

Tschallacka


People also ask

Can we use two 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],..

How do you get query results in the same order as given in clause?

in php u can do it like : <? php $my_array = array (3,6,1,8,9) ; $sql = 'SELECT * FROM table WHERE id IN (3,6,1,8,9)'; $sql . = "\nORDER BY CASE id\n"; foreach($my_array as $k => $v){ $sql .

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 you sorting of data in the table in ascending and descending order using a query?

If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.


1 Answers

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC 

Have a look at ORDER BY Optimization

like image 129
Himanshu Jansari Avatar answered Sep 25 '22 17:09

Himanshu Jansari