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.
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.
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).
There can only be one primary key per table - as indicated by the word "primary".
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) );
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With