29

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?
Seibar
  • 68,705
  • 38
  • 88
  • 99
  • See http://stackoverflow.com/questions/6692021/performance-space-implications-when-ordering-sql-server-columns – gbn Oct 17 '11 at 06:07
  • Here's a similar question on DBA.SE: [Does the order of columns in a table's definition matter?](http://dba.stackexchange.com/q/18719/2660) – Nick Chammas Jun 05 '12 at 17:25
  • 1
    Use can use the bellow link for more details : https://dba.stackexchange.com/questions/18719/does-the-order-of-columns-in-a-tables-definition-matter – Keyvan Soleimani Dec 07 '22 at 09:08

5 Answers5

9

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.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Aidan Ryan
  • 11,389
  • 13
  • 54
  • 86
3

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
  • 13,256
  • 4
  • 27
  • 19
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.

Tim Abell
  • 11,186
  • 8
  • 79
  • 110
Daniel Jennings
  • 6,304
  • 3
  • 32
  • 42
1

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

SQLMenace
  • 132,095
  • 25
  • 206
  • 225
0

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.

Nithin
  • 1,376
  • 12
  • 29