Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort an SQL result but keep some results as special?

Tags:

.net

sql

sorting

I have a result from an SQL query that I would like to sort alphabetical, but there are a couple of commonly used results that I would like to float to the top. Is there a simple way I can achieve this either by doing clever SQL or by sorting the (asp.net) datatable once I have it filled?

I know the database ID of the things that I want to keep at the top ahead of time if that makes a difference.

like image 870
Loofer Avatar asked Nov 27 '22 19:11

Loofer


1 Answers

The easiest way to do this is to sort by something that sets those fields aside from the others...

Under the assumption you have access to modify the structure of the table (which you may not), then add a "sticky" field which allows you to mark items as sticky and attach an order to the sticky items if you like. Sort by this field before the regular sort.

As for a trick to do this without that field defined - you would need to sort by some data that you can find in these fields or maintain the ids in a separate table - or a list in your query... not the most ideal way, but it will work.

like image 130
BenAlabaster Avatar answered Dec 10 '22 02:12

BenAlabaster