November 23, 2023 at 7:57 pm
Hi,
I'm new to sql server and successfully created a table of columns, however after creating the table I realised I forgot to add the primary key column.
I used the ALTER command for and used a query to create a new column for the primary key. This was successful but it added the column at the right side of the table.
Can I move the primary key column to the beginning of the table if at all possible? or delete the existing one and create a new one as the first column in the table? If so how? I don't want to drop the table and start again if I don't have to.
Thanks for any help
November 24, 2023 at 4:47 am
You could use the table designer in SSMS. It will allow you to "move" it. Be advised that, behind the scenes, it will create a new table, copy the data to it (along with all the index and key stuff) and then drop the original and rename the new table to the same as the original.
My question would be, does it actually matter where the PK is?
On that note, what is the table for? I ask because it sounds to me like you might be making an IDENTITY column for the PK and, depending on what's in the table, that might be a really bad idea... especially when it comes to what the Clustered Index will be.
--Jeff Moden
Change is inevitable... Change for the better is not.
November 24, 2023 at 2:20 pm
Another way to "move" the columns is to change the SELECT order. What I mean is rather than:
SELECT NAME, ID
FROM TABLE
do:
SELECT ID, NAME
FROM TABLE
The exception is if you are using "SELECT *", but best practice is to never use SELECT *. The coding standards at my company don't allow SELECT * in any production level code due to the surprises that can happen.
The above is all just my opinion on what you should do.
As with all advice you find on a random internet forum - you shouldn't blindly follow it. Always test on a test server to see if there is negative side effects before making changes to live!
I recommend you NEVER run "random code" you found online on any system you care about UNLESS you understand and can verify the code OR you don't care if the code trashes your system.
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply