How does SQL Server determine the order of the columns when you do a `SELECT *`?

£可爱£侵袭症+ 提交于 2019-12-04 23:55:14

They are in the order of column_id from the system view sys.columns.

You can check it by:

SELECT column_id, name
FROM sys.columns
WHERE object_id = Object_id('MyTableName')
ORDER BY column_id

EDIT

This is for Dems. You should test on a larger table, but it looks like it uses the order defined in the table, not the index:

CREATE TABLE #T (cola int, colb int, colc int)

INSERT INTO #T
VALUES
(1,2,3),
(2,3,4),
(4,5,6)

SELECT * FROM #T

CREATE INDEX ix_test ON #T (colb, colc, cola)

SELECT * FROM #t
WHERE colb > 0

DROP TABLE #T

They will be the same order in which they appear in Sql Server Management Studio; essentially, the order in which they were created.

The "correct" solution for assuring a desired column order is to specify the fields explicitly in your SELECT statement. SELECT * makes no guarantees about the ordering of output columns.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!