Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Can we order by column position instead of name?

I've looked on Google but couldn't find it. Can we order in MySQL using field's position ?

Let's say I got fields ID | FirstName | LastName | Age but I want to order by field 4, could I do something like ORDER BY FieldPos4 to order on Age ? I have not manage to find something about that.

Thanks.

like image 356
David Bélanger Avatar asked Jul 06 '12 19:07

David Bélanger


People also ask

Can we use column position in ORDER BY clause?

We can also specify column position in Order by clause. In this query, column birthdate is at the 3rd position; therefore, we can use three in the Order by clause to sort results on this column data.

Can you ORDER BY column in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Can you use ORDER BY on a column that is not one of the columns in the SELECT statement?

Yes, you can order by a field(s)even if it is not your in your select statement but exists in your table.

How do I rearrange columns in MySQL?

mysql> desc reOrderColumn; The following is the output. Now re-order the column using ALTER MODIFY command. I will reorder the DeliveryDate column after the ProductName column.


1 Answers

You can refer to the columns by position (1-based):

ORDER BY 4

From the documentation (emphasis mine):

Columns selected for output can be referred to in ORDER BY and GROUP BY clauses using column names, column aliases, or column positions. Column positions are integers and begin with 1

like image 128
mellamokb Avatar answered Nov 09 '22 16:11

mellamokb