Skip to content
Advertisement

How can I generate an ID column for a column in SQL? [closed]

I have a column that I’d like to generate an ID column for. How can I do this using SQL?. Also, is it possible to specify what type of ID I’d like to have as well as length. e.g. letters+ numbers or simply numbers?.

Thank you.

I am using SQL Server and SSMS.

Advertisement

Answer

It has two ways to create primary key in SQL Server:

  1. First in the table like his:
CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    CONSTRAINT PK_Person PRIMARY KEY (ID)
);
  1. On altering table like:
ALTER TABLE Persons
ADD PRIMARY KEY (ID);

NB: Only for the number ID column, add IDENTITY(1,1) if you want the number increment automatically like:

CREATE TABLE Persons (
    Personid IDENTITY(1,1) NOT NULL ,
    PRIMARY KEY (Personid)
);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement