Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by column A and then by column B?

How to write SQL so that the result can be ordered first by column A then by column B. Something like below:

SELECT * FROM tbl WHERE predictor ORDER by col_A and ORDER by col_B 
like image 833
pierrotlefou Avatar asked Nov 09 '09 03:11

pierrotlefou


People also ask

How do you ORDER BY two columns?

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 does ORDER BY work with multiple columns?

If you specify multiple columns, the result set is sorted by the first column and then that sorted result set is sorted by the second column, and so on. The columns that appear in the ORDER BY clause must correspond to either column in the select list or columns defined in the table specified in the FROM clause.

Can we use two columns in ORDER BY clause?

By using ORDER BY clause, we can sort the result in ascending or descending order. This clause can be used with multiple columns as well.

How do I order one thing and another in SQL?

So you want to order by one column first and then another? You can specify more than one column in the ORDER BY clause of a query - separate them by commas, and the first one will be the 'major' sort, then subsequent columns in the list will be sorted within that.


Video Answer


2 Answers

ORDER BY col_A, col_B 

The SQLite website has syntax diagrams explaining the SQL grammar supported by SQLite.

like image 70
James McNellis Avatar answered Sep 29 '22 05:09

James McNellis


Just feed a comma separated list of columns to ORDER BY:

SELECT * from table WHERE table.foo=bar ORDER BY colA, colB 

The ORDER BY clause causes the output rows to be sorted. The argument to ORDER BY is a list of expressions that are used as the key for the sort. The expressions do not have to be part of the result for a simple SELECT, but in a compound SELECT each sort expression must exactly match one of the result columns. Each sort expression may be optionally followed by a COLLATE keyword and the name of a collating function used for ordering text and/or keywords ASC or DESC to specify the sort order.

like image 27
meder omuraliev Avatar answered Sep 29 '22 05:09

meder omuraliev