Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary key for multiple column in PostgreSQL?

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.

like image 457
Sarfaraz Makandar Avatar asked May 08 '14 05:05

Sarfaraz Makandar


People also ask

How do I create a primary key in multiple columns in PostgreSQL?

This can be achieved using the ALTER TABLE statement. As can be seen from the above syntax, you can define PRIMARY KEY on multiple columns. When you have defined the PRIMARY KEY on multiple columns, the condition is that the column pairs should have unique and non-null values.

Can multiple columns have primary key?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).

Can Postgres have multiple primary keys?

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

How do you declare multiple columns as primary key?

For defining a PRIMARY KEY constraint on multiple columns, use the SQL syntax given below. CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID, NAME) );


1 Answers

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 due to PK    emp_id int UNIQUE NOT NULL,    emp_name text,    emp_addr text ); 

Columns that are (part of) the PRIMARY KEY are marked NOT NULL automatically.

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 due to PK below    emp_id int ,   -- NOT NULL due to PK below    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. See:

  • Are PostgreSQL column names case-sensitive?
like image 111
Erwin Brandstetter Avatar answered Sep 19 '22 15:09

Erwin Brandstetter