Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Ordering mysql results by certain field value first

Olivia Rhye

I needed to order a mysql result but in a somewhat custom way.

Say there is a field "id" and rows of values of 8, 4, 2, and 19.


SELECT `id` FROM `table_name` ORDER BY `id`;

This would obviously return the order: 2,4,8,19.

But what if you needed the 4 to be first and then order by integers?


SELECT IF(`id` = '4','0','1') AS `custom_order` FROM `table_name` ORDER BY `custom_order`;

This would return 4,2,8,19.

Simple and can be really helpful.

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy