Why do both SSMS and ASP.NET MVC dropdowns show the data I filled in a different order sorted alphabetically?
I’ve added the "Other" option as the last and when I ask SSMS to show the table content I get it sorted "Other" is not the last in the list.
The same is true for the dropdown in our ASP.NET MVC website pages:
Do I need really to add a table column with an integer value to get the items sorted in the natural order I manually filled it?
2
Answers
I’d guess that your database table has a clustered index on it, and that is causing it to store the data in a sorted order.
If you need things to be sorted in a particular way, you may need to have a separate column to store that – an auto incrementing column, or a datetime for example – and then have an
order by xxx
in the query that gets the data.A relational database table is by definition an unordered set of rows. Although SQL Server might return ordered data (depending on the execution plan and other factors), an
ORDER BY
clause in the query is required to guarantee the result set is sorted as desired.The implication is you need column(s) in the table to specify the order. You could add an incremental column (IDENTITY, datetime, etc.) and specify that in the ORDER BY clause.
Rather than rely on insertion order, consider adding a MajorDisplaySequence column or similar. That way, you can add more rows later (MajorDisplaySequence value 1) yet still retain ‘OTHER’ (MajorDisplaySequence value 2) as the last returned value.
Sorting in client code is also option if the source data contains the needed attribute(s).