“Clustered index” and “Order by Clause”

前端 未结 5 1468
慢半拍i
慢半拍i 2021-02-06 00:28

Is there any difference between Clustered Index and Order by Clause?

I have to populate the Dropdown from the Master Table and followin

5条回答
  •  庸人自扰
    2021-02-06 01:05

    A index allows for quick searching filtering "WHERE CLAUSE" but also has the added bonus in that data will be sorted.

    example

    This is how data would be saved in the table.

    ID    Name
    1     Jack
    2     Bob
    3     Jill
    

    If you add a clustered index on Name(ASC) this is how it will be saved (primary keys are always stored along with each indexed for look up infomation)

    2     Bob
    1     Jack
    3     Jill
    

    So using your SQL

    Select Id, Name from Table Order by Name
    

    For a select without the clustered index, the database will check to see if an index exists that can help do its work quicker. It will not find any so it will select the data from the table, sort it, and then return.

    For select with the clustered index, the database will check to see if an index exists that can help do its work quicker. It will find the index on name that is sorted ASC. It can just select the ID and Name from the index, and then return as it knows that the data is sorted already.

    So without the index on name the database has to sort the data every time the query is run. With the index, the sort happens when data is Inserted or Updated (which slows updates a little bit) The difference is that it only needs to sort once and not every time.

提交回复
热议问题