skip to Main Content

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.

enter image description here

The same is true for the dropdown in our ASP.NET MVC website pages:

enter image description here

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    CREATE TABLE dbo.industry(
        industryId char(3) NOT NULL 
            CONSTRAINT pk_industry PRIMARY KEY
       ,industryName varchar(50) NOT NULL
       ,MajorDisplaySequence int NOT NULL
    );
    
    SELECT industryId, industryName
    FROM dbo.industry
    ORDER BY MajorDisplaySequence, industryId;
    

    Sorting in client code is also option if the source data contains the needed attribute(s).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search