SQL Server - Does column order matter?

我的未来我决定 提交于 2019-12-28 04:22:07

问题


In terms of performance and optimizations:

  • When constructing a table in SQL Server, does it matter what order I put the columns in?
  • Does it matter if my primary key is the first column?
  • When constructing a multi-field index, does it matter if the columns are adjacent?
  • Using ALTER TABLE syntax, is it possible to specify in what position I want to add a column?
    • If not, how can I move a column to a difference position?

回答1:


In SQL Server 2005, placement of nullable variable length columns has a space impact - placing nullable variable size columns at the end of the definition can result in less space consumption.

SQL Server 2008 adds the "SPARSE" column feature which negates this difference.

See here.




回答2:


I would say the answer to all those questions is NO, altough my experience with MS-SQL goes as far as SQL2000. Might be a different story in SQL2005




回答3:


For the fourth bullet: No you can't specify where you want to add the column. Here is the syntax for ALTER TABLE: https://msdn.microsoft.com/en-us/library/ms190273.aspx

In MySQL they offer an ALTER TABLE ADD ... AFTER ... but this doesn't appear in T-SQL.

If you want to reorder the columns you'll have to rebuild the table.

Edit: For your last last bullet point, you'll have to DROP the table and recreate it to reorder the columns. Some graphical tools that manipulate SQL databases will do this for you and make it look like you're reordering columns, so you might want to look into that.




回答4:


No to the first 3 because the index will hold the data and no the last once also




回答5:


Column order does not matter while creating a table. We can arrange the columns while retrieving the data from the database. Primary key can be set to any column or combination of columns.




回答6:


For the first bullet:

Yes, column order does matter, at least if you are using the deprecated BLOBs image, text, or ntext, and using SQL Server <= 2005.

In those cases, you should have those columns at the 'end' of the table, and there is a performance hit every time you retrieve one.

If you're retrieving the data from such a table using a DAL, this is the perfect place for the Lazy Load pattern.



来源:https://stackoverflow.com/questions/34818/sql-server-does-column-order-matter

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