EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

PostgreSQL Primary Key

By Sohel SayyadSohel Sayyad

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL Primary Key

PostgreSQL Primary Key

Introduction to PostgreSQL Primary Key

The row of the table can be uniquely identified using a column or group of columns termed as a primary key. We can specify the primary keys using the primary key constraints. The PRIMARY KEY constraint is the combination of a UNIQUE constraint and a NOT NULL constraint. The table can consist of only one PRIMARY KEY; adding a primary key on each table is a best practice in the database management system.

Syntax

Below are the syntax used in the Primary key:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax #1 – Define the primary key

1. Add the primary key while creating the table. We can add the primary key constraint to a table while creating the table itself using the CREATE TABLE statement.

CREATE TABLE table_name (
column_name1 data_type PRIMARY KEY,
column_name2 data_type,
.
.
.
);

2. We can create a primary key constraint containing two or more columns as follows:

CREATE TABLE table_name (
column_name1 data_type,
column_name2 data_type,
.
.
.
PRIMARY KEY (column_name1, column_name2)
);

Syntax #2 – UPDATE PRIMARY KEY

We can add a primary key constraint for an existing table, which is rare. We can achieve the same using an ALTER TABLE statement as follows:

ALTER TABLE table ADD PRIMARY KEY (column1, column);

Syntax #3 – Remove the primary key

With the help of  the ALTER TABLE statement, we can remove an existing primary key constraint of the table as follows:

ALTER TABLE table_name DROP CONSTRAINT primary_key_constraint;

How does Primary Key work in PostgreSQL?

The PostgreSQL creates a unique B-TREE index on PRIMARY KEY columns if we have added PRIMARY KEY on the table using a column or a group of columns of a table. If we don’t define the primary key constraint name explicitly then PostgreSQL assigns a default name to the primary key constraint. PostgreSQL assigns table_name_pkey as the default name for the primary key constraint. If we have a table named  CITIES, then PostgreSQL creates the primary key constraint with the name cities_pkey for the same. We can use the CONSTRAINT clause as follows to assign the name for the same:

Code:

CONSTRAINT constraint_name PRIMARY KEY(column_name1, column_name2,...);

Examples to Implement Primary Key in PostgreSQL

Let’s create a table named COUNTRIES using the CREATE TABLE statement in order to understand the examples.

Example #1  – Single Column PRIMARY KEY

Code:

CREATE table COUNTRIES
(
country_id serial PRIMARY KEY,
country_name VARCHAR (256) NOT null,
last_updated DATE NULL
);

The country_id is the COUNTRIES table’s primary key, which used to identify the country in the COUNTRIES table uniquely.

Example #2 – Multiple Columns PRIMARY KEY

The following statement will create a table named ‘CITIES’ whose primary key is a combination of city_id and country_id.

Code:

CREATE table  CITIES
(
city_id serial,
country_id INT,
city_name VARCHAR (256) NOT NULL,
last_updated DATE null,
PRIMARY KEY (CITY_id, country_id)
);

Example #3 – Adding PRIMARY KEY

Example to ALTER TABLE for adding PRIMARY KEY after table creation. The following statement creates a table named invoices which will not have any PRIMARY KEY.

Code:

CREATE TABLE invoices (
invoice_id INT,
invoice_data VARCHAR (256) NOT NULL
);

  • Now with the help of the following statement, we can add a primary key constraint to the invoices table.

Code:

ALTER TABLE invoices
ADD PRIMARY KEY (invoice_id);

Example #4 – Auto-incremented PRIMARY KEY

Example to ALTER TABLE for adding auto-incremented PRIMARY KEY after table creation. Now with the help of the following statement, we can add an auto-incremented primary key constraint to the invoices table.

Code:

CREATE TABLE invoices (invoice_data VARCHAR(255));

  • NOW insert some data in the invoices table using the INSERT statement.

Code:

INSERT INTO invoices (invoice_data)
VALUES
('Purchase of Mobile'),
('Purchase of Laptop'),
('Purchase of PC'),
('Purchase of Tablet');

  • Illustrate the result of an INSERT statement with the help of the following SQL statement and snapshot.

Code:

SELECT   * FROM   Invoices;

Output:

PostgreSQL Primary - 1

  • Here we will add an auto-incremented by one  primary key named invoice_id into the invoices table with the help of the following statement:

Code:

ALTER TABLE invoices ADD COLUMN invoice_id SERIAL PRIMARY KEY;

  • Illustrate the result of an ALTER statement with the help of the following SQL statement and snapshot.

Code:

SELECT   invoice_id,invoice_data FROM   invoices;

Output:

PostgreSQL Primary - 2

  • Now the invoices table has the primary key invoice_id.

Example #5 – Remove a PRIMARY KEY of the table

In order to remove the primary key constraint of the invoices table, we have to use the following statement:

Code:

ALTER TABLE invoices
DROP CONSTRAINT invoices_pkey;

Advantages of using Primary Key in PostgreSQL

  1. The PostgreSQL PRIMARY KEY helps us to search records quickly as the index is getting used based on the PRIMARY KEY.
  2. By using PostgreSQL PRIMARY KEY, we can uniquely identify the table records for an update or delete operation.
  3. The PostgreSQL PRIMARY KEY is used to sort the data based on it.
  4. By using PostgreSQL PRIMARY KEY, we can avoid duplicate row insertion in the table.

Conclusion

We hope from the above article you have understood how to add, update and remove primary key constraints using CREATE TABLE and ALTER TABLE statements. Also, with the help of examples and syntax explained in detail.

Recommended Articles

This is a guide to PostgreSQL Primary Key. Here we discuss an introduction to PostgreSQL Primary Key along with appropriate syntax and respective examples. You can also go through our other related articles to learn more –

  1. PostgreSQL Database
  2. PostgreSQL INTERSECT
  3. PostgreSQL Constraints
  4. PostgreSQL Cross Join
  5. PostgreSQL Tablespaces | How to Create?
  6. Guide to PostgreSQL IF Statement
  7. Learn the PostgreSQL Auto Increment

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Special Offer - All in One Data Science Bundle (360+ Courses, 50+ projects) Learn More