Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • PostgreSQL - Get Started
  • Install PostgreSQL
  • Connect to PostgreSQL DB
  • Create Database
  • Create Table
  • Copy Table
  • Drop Table
  • Drop Database
  • Truncate Table
  • ALTER Table
  • Rename Table
  • Rename Columns
  • Add Columns
  • Modify Column Type
  • Set Default Value of Column
  • Remove Columns
  • Add Constraints to Table
  • Insert Data
  • Upsert Data
  • Update Data
  • Delete Data
  • SELECT Statement
  • WHERE Clause
  • GROUP BY Clause
  • HAVING Clause
  • ORDER BY Clause
  • DISTINCT Clause
  • Inner Join
  • Left Outer Join
  • Right Outer Join
  • Full Outer Join
  • Self Join
  • Natural Join
  • Cross Join
  • LIMIT OFFSET Clause
  • GROUPING SETS
  • GROUPING() Function
  • GROUP BY CUBE
  • GROUP BY ROLLUP
  • Sub Query
  • ALL Operator
  • ANY Operator
  • UNION Operator
  • INTERSECT Operator
  • EXCEPT Operator
  • IS NULL Operator
  • BETWEEN Operator
  • LIKE Operator
  • CAST Operator
  • CASE Expressions
  • NULLIF()
  • COALESCE()
  • GREATEST(), LEAST()
  • WITH Queries (CTE)
  • Constraints
  • NOT NULL Constraint
  • Unique Constraint
  • Check Constraint
  • Primary Key
  • Foreign Key
  • Sequence
  • Serial Type
  • Identity Columns
  • Generated Columns
  • Data Types
  • Boolean Type
  • Character Type
  • Integer Type
  • Numeric Type
  • Date Type
  • Time Type
  • TimeStamp Type
  • Interval Type
  • Array Type
  • Json Type
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

PostgreSQL: Primary Key Constraint

In PostgreSQL, a primary key constraint uniquely identifies rows. One or more columns can be defined as a primary key in a table.

Primary key is a combination of NOT NULL constraint and UNIQUE constraint, meaning, the column or group of columns that are defined as the primary key enforce column to have not-null and unique values.

A table can have only one primary key. It is not mandatory but a good practice to add a primary key to a table.

Define Primary Key while Creating a Table

In PostgreSQL, you can define a primary key on a single column by writing "primary key" after the column name in the CREATE TABLE statement.

For example, the following CREATE TABLE statement will create the employee table with a primary key defined on emp_id column. This is called defining a primary key at the column level.

Example: Define Primary Key
CREATE TABLE IF NOT EXISTS employee
(emp_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
gender CHAR(1),
birthdate DATE,
email VARCHAR (100),
salary INT);

PostgreSQL will create a primary key constraint as table_name_pkey that's employee_pkey for the employee table, as shown below.

Primary Key Constraint

To define the primary key on multiple columns, it needs to be defined at the table level like below.

Syntax: Multi-column Primary Key
CREATE TABLE [IF NOT EXISTS] table_name (
   Column1 data_type(length),
   Column2 data_type(length),
    ...
CONSTRAINT <constraint_name> PRIMARY KEY(Column1, Column2,...)
);

For example, the following defines a primary key on two columns:

Example: Define Multi-column Primary Key
CREATE TABLE IF NOT EXISTS employee_department 
(emp_id  INT,
dept_id INT,
CONSTRAINT empid_deptid_pkey PRIMARY KEY (emp_id, dept_id));
Primary Key Constraint

Configure PRIMARY KEY Constraint on Existing Tables

A primary key constraint can be added to existing tables too, provided the column or group of columns being added to the primary key do not have NULL values in it and have unique values across the table.

Syntax: ALTER TABLE
ALTER TABLE table_name
ADD PRIMARY KEY(column1, column2,...);

---OR

ALTER TABLE table_name
ADD CONSTRAINT constraint_name
PRIMARY KEY(column1, column2,...);

Consider we created employee table without any primary key and inserted data as bellow

Primary Key Constraint

Now let's add the primary key on emp_id column. As emp_id does not have NULL values in any of the columns and all values are unique, you can alter the table and define emp_id as a primary key, as shown below.

Example: Define Primary Key in Existing Table
ALTER TABLE employee
ADD PRIMARY KEY(emp_id);

Define Primary Keys using pgAdmin

You can create primary keys on new or existing tables using pgAdmin. The steps would remain the same if you define primary keys on new tables or existing tables.

Expand your databases node in the left pane and then expand Schemas -> public -> Tables nodes.

Now, right-click on the table where you want to add a primary key and click on 'Properties' in the menu.

Open Table Properties

In the popup, go to the 'Constraints' tab and click on the 'Primary Key' tab, as shown below.

Add Primary Key

Now, to add a primary key, click on the + button to add a row in a grid. Then, click on the edit icon to add a primary column definition. In the General tab, add primary key name and in the Definition tag, add primary key columns, as shown below.

Add Primary Key

Click on the Save button to define a primary key on the selected columns.

Thus, you can define a primary key in a new or existing tables.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.