Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Sort By 2 Columns

I have a table which holds information on television programs and I want to order it by Seasons and then by episodes. Here's a basic view of what I have:

+---+--------+---------+
|id | Season | Episode |
+---+--------+---------+
| 1 |    1   |    1    |
+---+--------+---------+
| 1 |    1   |    2    |
+---+--------+---------+
| 1 |    2   |    1    |
+---+--------+---------+
| 1 |    2   |    3    |
+---+--------+---------+

So I select what I need and order by Season. But there's going to be a lot between seasons so I need to sort episodes too, but without it affecting seasons.

like image 605
Ben Shelock Avatar asked Jun 03 '09 10:06

Ben Shelock


People also ask

Can we sort by two columns 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 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.

Can we have 2 ORDER BY in MySQL?

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 sort by two attributes in SQL?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first.


2 Answers

Do you mean:

SELECT id, Season, Episode 
FROM table 
ORDER BY Season ASC, Epsisode ASC

Sorting by multiple columns is as simple as it gets.

like image 150
Stefan Gehrig Avatar answered Sep 22 '22 18:09

Stefan Gehrig


We know what you mean :) In your order by you should have

ORDER BY Season, Episode 

It will sort by Season and then on Episode within Season

like image 35
SO User Avatar answered Sep 20 '22 18:09

SO User