views:

1789

answers:

5

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?
+2  A: 

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

Ricardo Reyes
A: 

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

SQLMenace
+5  A: 

For the fourth bullet: No you can't specify where you want to add the column. Here is the syntax for ALTER TABLE: http://doc.ddart.net/mssql/sql70/aa-az_5.htm

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.

Daniel Jennings
+3  A: 

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.

Aidan Ryan
A: 

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.

egrunin