Categories: MySQL

MySQL ORDER BY Clause

Share

Using MySQL ORDER BY Clause you can sort table columns by ascending or descending.

Suppose we have a table ‘tbl’ with column ‘name’ and a row like below values:

1
1B
10
2
10C
2A
10Z

So, when you sort by name:

SELECT name
FROM tbl
ORDER BY name;

So, when you sort by that column you will get the result:

1
10
10C
10Z
1B
2
2A

This is not like that what we expected. This ia natural sorting.
So we need to CAST this to get our desired result like below:

SELECT name
FROM tbl
ORDER BY CAST(name AS UNSIGNED);

Result:
1
1B
2
2A
10
10C
10Z

ORDER BY FIELD:

Sometimes a specific order is required in a query which cannot be done using either ASC or DESC or using a special sort field.
Using FIELD( ) function in the ORDER BY clause you can achieve this.

SELECT name
FROM tbl
ORDER BY FIELD(name, '1B', '2A') desc;

Result:
2A
1B
1
10
2
10C
10Z

Recent Posts

Unlock Growth – Guide to Online Financing and Business Loans for Entrepreneurs

If you are in a financial crisis , or need to start a new business…

1 day ago

Optimize Your Hormonal Balance: Enclomiphene Citrate for Enhanced Wellness

Hormonal balance plays a pivotal role in overall well-being, influencing various aspects of health, from…

2 days ago

Paul Kanes Explores the World of Canine Companionship through Dog Walking

Dog walking is an excellent way to maintain your furry friend's camaraderie and provides many…

2 days ago

Top 5 Must-Have Features Every Mobile App Needs to Succeed

Introduction Businesses understand the diverse requirements of mobile applications, which provide a competitive advantage. There…

2 days ago

IoT Data Analytics: Ways to Gain Value from IoT Data

The Internet of Things (IoT) has recently changed the world. It links gadgets together and…

2 days ago

The Rise of NFTs: Exploring the Impact of Non-Fungible Tokens on the Digital Economy

NFTs, or Non-Fungible Tokens, are revolutionizing the digital economy. These unique digital assets, authenticated through…

3 days ago