没有ORDER的SELECT没有在Clustered Index上排序

stu*_*ubs 1 sql-server sorting clustered-index

这个有点困惑.我的印象是,如果没有给出ORDER BY,SELECT应默认为Clustered Index进行排序.

但是如果我运行下面的代码,它会使用NON-Clustered索引.

DROP TABLE TEST_TABLE
if NOT EXISTS(select 1 from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'TEST_TABLE')
BEGIN
    CREATE TABLE TEST_TABLE (
        [ID]    int     NOT NULL IDENTITY(1,1),
        [col1]  int     NOT NULL,
        [col2]  int     NOT NULL

        CONSTRAINT [PK_TEST_TABLE] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    )WITH (FILLFACTOR = 90) ON [PRIMARY]
    ) ON [PRIMARY]
END

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TEST_TABLE]') AND name = N'TEST_TABLE_cols')
    DROP INDEX [TEST_TABLE_cols] ON [dbo].[TEST_TABLE]

CREATE UNIQUE NONCLUSTERED INDEX [TEST_TABLE_cols] ON [dbo].[TEST_TABLE] 
(       [col1] ASC,
        [col2] ASC      
)WITH (FILLFACTOR = 60) ON [PRIMARY];
GO
--GO

EXEC ('insert into test_table select 1, 0')
EXEC ('insert into test_table select 2, 0')
EXEC ('insert into test_table select 10, 0')
EXEC ('insert into test_table select 9, 0')
EXEC ('insert into test_table select 8, 0')
EXEC ('insert into test_table select 6, 0')
EXEC ('insert into test_table select 7, 0')
EXEC ('insert into test_table select 5, 0')
EXEC ('insert into test_table select 3, 0')
EXEC ('insert into test_table select 4, 0')

select * from test_table
Run Code Online (Sandbox Code Playgroud)

结果如下......

ID          col1        col2
----------- ----------- -----------
1           1           0
2           2           0
9           3           0
10          4           0
8           5           0
6           6           0
7           7           0
5           8           0
4           9           0
3           10          0
Run Code Online (Sandbox Code Playgroud)

如果有人可以解释,将非常感谢!

Ric*_*ard 5

我的印象是,如果没有给出ORDER BY,SELECT应默认为Clustered Index进行排序.

虽然在实践中可能看起来是这样的(如果行是简单的按顺序读取存储,这就是你得到的),在任何地方都没有这样的保证.查询或查询计划中的一个小变化很容易改变.

如果您未指定订单,则结果没有订单.