aaaa bbbb
aaaa bbbb

Reputation: 3043

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

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

I know "Order By" is essential for ordering the data, but I expected the column names to be consistent.

Note: My code is not dependent on the actual order the columns are returned. I just want to know how SQL Server decides to order the column names.

Of about 20 computers my team is using, one of them behaves differently. Any difference deserves to be investigated. The column name ordering appears to be the same for all computers when we open SQL Server Management Studio. When our application makes a query is when I see the difference.

I am using SQL Server 2008, and SQL Server 2008 R2. My application uses C# System.Data.SqlClient to access the database.

EDIT: My problem turned out to be that one of the computers was configured to log in as 'sa', instead of the intended user. The query was hitting the table directly when we intended it to hit a view. Thanks for the help learning about sys.columns

Upvotes: 18

Views: 25071

Answers (2)

JNK
JNK

Reputation: 65177

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

Upvotes: 19

Robert Harvey
Robert Harvey

Reputation: 180808

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.

Upvotes: 4

Related Questions