Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 612
aaaa bbbb Avatar asked Apr 18 '12 16:04

aaaa bbbb


People also ask

Does column order matter in SQL SELECT?

Column Order Does Make A Difference Clearly and immediately, performance degrades as we SELECT a column other than the first column.

What is the order of SQL SELECT?

Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.

Does order of columns in Groupby matter?

No, the order doesn't matter for the GROUP BY clause. MySQL and SQLite are the only databases I'm aware of that allow you to select columns which are omitted from the group by (non-standard, not portable) but the order doesn't matter there either.

How does SQL ORDER BY work?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


1 Answers

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
like image 198
JNK Avatar answered Sep 18 '22 23:09

JNK