42

How to provide primary key for multiple column in a single table using PostgreSQL?

Example:

Create table "Test" 
(
   "SlNo" int not null primary key,
   "EmpID" int not null, /* Want to become primary key */
   "Empname" varchar(50) null,
   "EmpAddress" varchar(50) null
);

Note: I want to make "EmpID" also a primary key.

Erwin Brandstetter
  • 479,275
  • 111
  • 893
  • 1,042
Meem
  • 4,007
  • 12
  • 47
  • 78

2 Answers2

86

There can only be one primary key per table - as indicated by the word "primary".

You can have additional UNIQUE columns like:

CREATE TABLE test(
   sl_no int PRIMARY KEY,  -- NOT NULL automatically
   emp_id int UNIQUE NOT NULL,
   emp_name text,
   emp_addr text
);

Or use a table constraint instead of a column constraint to create a single multicolumn primary key. This is semantically different from the above: Now, only the combination of both columns must be unique, each column can hold duplicates on its own.

CREATE TABLE test(
   sl_no int,     -- NOT NULL automatically
   emp_id int ,   -- NOT NULL automatically
   emp_name text,
   emp_addr text,
   PRIMARY KEY (sl_no, emp_id)
);

(Multicolumn UNIQUE constraints are possible, too.)

Aside: Don't use CaMeL-case identifiers in Postgres. Use legal, lower-case identifiers so you never have to use double-quotes. Makes your life easier.

Erwin Brandstetter
  • 479,275
  • 111
  • 893
  • 1,042
0

I think it can be.

Create table "Test" 
(
   "SlNo" int ,
   "EmpID" int , 
   "Empname" text),
   "EmpAddress" text,
   PRIMARY KEY (SlNo, EmpID)
);
Hong Van Vit
  • 2,515
  • 1
  • 11
  • 33