MorkaLork Development

Interesting stuff I've picked up over the years...

Mysql 8: ORDER BY

2009-04-16 21:16:45 | 315 views | sql mysql table order by ascending descending

Just retrieving data from a database might not always be enough. Getting it in a structured order might be just as important. Presenting ORDER BY.

ORDER BY asks for a column, or several columns, and sorts it after that. You can also set if you want ascending or descending order.
By default, the sorting order is ascending.

Ascending is low -> high.
Descending is high -> low.



This will be our table 'person'

|--------------------+--------------------+--------------------|
|Name |Age |Gender |
|____________________+____________________+____________________|
|Bob 34 Male |
|Silvia 67 Female |
|Magnus 24 Male |
|Lisa 32 Female |
+--------------------------------------------------------------+



Syntax:

SELECT column
FROM table_name
ORDER BY rule


Example:


SELECT *
FROM person
ORDERY BY Name Asc


NameAgeGender
Bob34Male
Lisa32Female
Magnus24Male
Silvia67Female


Example:


SELECT *
FROM person
ORDER BY Age ASC


|--------------------+--------------------+--------------------|
|Name |Age |Gender |
|____________________+____________________+____________________|
|Bob 34 Male |
|Lisa 32 Female |
|Magnus 24 Male |
|Silvia 67 Female |
+--------------------------------------------------------------+


You also sort by two columns. This way it will sort by the first column first, if there are several equal values, they will in turn be sorted by the second column.

Example:


SELECT *
FROM person
ORDER BY Gender, Age ASC


|--------------------+--------------------+--------------------|
|Name |Age |Gender |
|____________________+____________________+____________________|
|Lisa 32 Female |
|Silvia 67 Female |
|Magnus 24 Male |
|Bob 34 Male |
+--------------------------------------------------------------+


This sorts first by Gender, if a record has the same gender as another, they will be sorted by age.

It's also possible to have differant sorting orders:

Example:


SELECT *
FROM person
ORDER BY Gender ASC, Age DESC


|--------------------+--------------------+--------------------|
|Name |Age |Gender |
|____________________+____________________+____________________|
|Silvia 67 Female |
|Lisa 32 Female |
|Bob 34 Male |
|Magnus 24 Male |
+--------------------------------------------------------------+








Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.