MySQL ORDER BY Keyword

MySQL ORDER BY Keyword

The ORDER BY keyword in MySQL is used to sort the retrieved data from a table. By default, data can be sorted in ascending (ASC) or descending (DESC) order.


๐Ÿ“Œ Basic Syntax



 

  • ASC โ†’ Ascending order (default)

  • DESC โ†’ Descending order

If no order is specified, MySQL sorts results in ascending order.


๐Ÿงช Example Table

Assume this table named students:

id name marks
1 Aman 88
2 Riya 92
3 John 75
4 Neha 88

๐Ÿท Sort in Ascending Order



 

Result:

name marks
John 75
Aman 88
Neha 88
Riya 92

๐Ÿ”ฝ Sort in Descending Order



 

Result:

name marks
Riya 92
Aman 88
Neha 88
John 75

๐Ÿง  Sorting by Multiple Columns

If two or more values are the same, you can sort using a secondary column.



 

Here:

  • Sorted first by marks (DESC)

  • If marks are equal, then by name (ASC)


๐Ÿ” Using ORDER BY With WHERE Clause



 


โณ Using ORDER BY With LIMIT



 

Returns highest two marks.


๐Ÿ Summary

Feature Example
Sort ascending ORDER BY name ASC
Sort descending ORDER BY marks DESC
Sort multiple columns ORDER BY marks DESC, name ASC
With WHERE clause WHERE marks > 80 ORDER BY name

โœ” The ORDER BY keyword helps organize results in meaningful order, making data analysis easier.

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *