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
Column Order Does Make A Difference Clearly and immediately, performance degrades as we SELECT a column other than the first column.
Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With