Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Clustered index" and "Order by Clause"

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

I have to populate the Dropdown from the Master Table and following is the query.

Select Id, Name from Table Order by Name

Should I use the Order by Clause Or Clustered Index for the above task?

EDIT

Below is the schema of the table

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[lookup]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[lookup](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
 CONSTRAINT [PK_lookup_ID] PRIMARY KEY NONCLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[lookup]') AND name = N'IX_lookup_Name')
CREATE CLUSTERED INDEX [IX_lookup_Name] ON [dbo].[lookup]
(
    [Name] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

I have a clustered index on Name as well. But right now it is not showing in the schema. Sorry, I don't know why.

like image 440
Pankaj Avatar asked Jun 01 '11 05:06

Pankaj


1 Answers

Apples and Oranges. A clustered index is a storage option. An ORDER BY is a query option. If you need ordered results, the only way to get them is to add an ORDER BY clause to your query. Period.

An index may help the query optimizer generate a more efficient plan and leverage the index as a means to satisfy the ORDER BY requirement. But by no means will the presence of an index, clustered or non-clustered, guarantee any ordering of a result.

So you absolutely need ORDER BY in your queries. You also may consider an index by Name column to help this the query. Whether an index will be used or not, it depends on many more factors. you should read Designing Indexes and The Tipping Point.

like image 153
Remus Rusanu Avatar answered Sep 29 '22 11:09

Remus Rusanu