How define PRIMARY KEY on column in the table? – SQL Server 2012
Almost all tables in databases have column with primary key. This column often has int datatype.
How define column of primary key? It is very simple. You must use PRIMARY KEY
clause after datatype.
create table osoby ( id_osoby int PRIMARY KEY, nazwisko varchar(150) not null );
I sometimes meet in databases projects added NOT NULL
constraint. It isn’t needed, because in SQL Server
, PRIMARY KEY
containts constraints: UNIQUE
and NOT NULL
. If You open Design
window Management Studio
for osoby
table, You see in Properties
section, that Allow Nulls
isn’t check.
Another way to define PRIMARY KEY
is use constraint
clause. After columns definition, this clause are place with its name and PRIMARY KEY
clause and brackets with name of column for key.
create table osoby ( id_osoby int, nazwisko varchar(150) not null, constraint pk_osoba PRIMARY KEY( id_osoby ) );
Third way to define primary key is place after definitions of columns PRIMARY KEY, and after this clause brackets with name of column for key.
create table osoby ( id_osoby int, nazwisko varchar(150) not null, PRIMARY KEY( id_osoby ) );
Primary key may be define either for several columns:
create table lista ( nr int, nazwisko varchar(150), imie varchar(100) not null, PRIMARY KEY(nr, nazwisko) );
One table may have only one primary key.