EDUCBA

EDUCBA

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

PostgreSQL UNIQUE Index

By Sohel SayyadSohel Sayyad

Home » Data Science » Data Science Tutorials » PostgreSQL Tutorial » PostgreSQL UNIQUE Index

PostgreSQL UNIQUE Index

Introduction to PostgreSQL UNIQUE Index

The PostgreSQL UNIQUE INDEX is used when we want to ensure that the column stores unique values only. If we define the UNIQUE INDEX on the particular column, then that column can not have the same value in multiple rows. Also, we can define the UNIQUE INDEX on multiple columns for enforcing them to store the combined unique value. While creating a table, we can add a UNIQUE  constraint or primary key for the table, which automatically constructs a UNIQUE INDEX for a column that we have marked as a primary key of the table or the column on which we have added a UNIQUE constraint.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Consider the following syntax for creating the PostgreSQL UNIQUE INDEX:

CREATE UNIQUE INDEX index_name ON table_name(column_name, [...]);

Explanation:

  • index_name: This defines the name given to the UNIQUE INDEX.
  • table_name: This defines on which table we are adding a UNIQUE INDEX.
  • column_name: This defines the column or list of columns that will be covered under the UNIQUE INDEX to have unique values.

How Does UNIQUE Index Work in PostgreSQL?

1. We can add UNIQUE INDEX on one or more columns; if we have added UNIQUE INDEX on a single column, then that column can not have the same value in multiple rows.

2. Also, if have added a UNIQUE INDEX on more than one column, then the combined value of all these columns should be unique and can not have the same value in multiple rows

3. The NULL value is considered as the DISTINCT value, so the column with a UNIQUE INDEX applied can have multiple NULL values stored in it. Similar is applied to the multiple columns for which we have applied the UNIQUE INDEX.

4. If we have added a UNIQUE  constraint or primary key for the table while creating a table, which automatically constructs a UNIQUE INDEX for a column which we have marked as a primary key of the table or the column on which we have added a UNIQUE constraint.

Examples to Implement PostgreSQL UNIQUE Index

Below are the examples of the PostgreSQL UNIQUE Index:

We will create a table named ‘student22’ for understanding the UNIQUE INDEX in detail. Consider the following CREATE TABLE statement, which will create a ‘student22’ table.

Query:

CREATE TABLE student22 (
stud_id SERIAL PRIMARY KEY,
stud_firstname VARCHAR(255) NOT NULL,
stud_lastname VARCHAR(255) NOT NULL,
stud_email VARCHAR(255) UNIQUE
);

In the above statement, we have added the stud_id column as a primary key column. Also, the column stud_email is defined with the UNIQUE constraint applied to it, which will cause to create of two UNIQUE indexes for stud_id and stud_email columns.

We can get the indexes of the student22 table by using the following SQL statement:

Query:

SELECT  tablename, indexname, indexdef
FROM
pg_indexes
WHERE
tablename = 'student22';

Output:

PostgreSQL UNIQUE Index Example 1

Example #1 – Single Column

Now we will add a column of name ‘stud_contact’ to the ‘student22’ table by using the following statement:

Query:

ALTER TABLE student22 ADD stud_contact VARCHAR(20);

The contact number for each should be unique. So we will add a UNIQUE index for the stud_contact column to make sure that the contact numbers are distinct for all students.

Popular Course in this category
Sale
PostgreSQL Course (2 Courses, 1 Project)2 Online Courses | 1 Hands-on Project | 7+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,206 ratings)
Course Price

View Course

Related Courses

Consider the following SQL statement, which will add a UNIQUE index for the stud_contact column.

Query:

CREATE UNIQUE INDEX idx_student_stud_contact
ON student22(stud_contact);

Now we will insert some data into the student table to validate the uniqueness of the stud_contact column.

Consider the following INSERT INTO statement for inserting a new row into the student22 table:

Query:

INSERT INTO student22
(stud_firstname, stud_lastname, stud_email, stud_contact)
VALUES
('David','Lundberg','David.Lundberg@educba.com', '(1)-444-555-666');

Illustrate the result of the above statement by using the following snapshot and SQL statement.

Query:

select * from student22;

Output:

PostgreSQL UNIQUE Index Example 2

Again, consider the following INSERT INTO statement for inserting a new row into the student22 table, but this time we will add the same contact number as we have added earlier.

Query:

INSERT INTO student22
(stud_firstname, stud_lastname, stud_email, stud_contact)
VALUES
('Patrik','Brand','Patrik.Brand@educba.com', '(1)-444-555-666');

Output:

PostgreSQL UNIQUE Index Example 3

Here we got an error which is because we are trying to insert the duplicate contact number in the stud_contact column.

Example #2 – Multiple Columns

Now we will add two new columns of name ‘stud_batch’ and ‘stud_reg_no’ to the ‘student22’ table by using the following statement:

Query:

ALTER TABLE student22
ADD stud_batch VARCHAR(5),
ADD stud_reg_no VARCHAR(5);

The Batch of the multiple students can be the same, but each student’s registration can not be the same. To ensure the same criteria, we have to define the UNIQUE index on the columns.

‘stud_batch’ and ‘stud_reg_no’ of the ‘student22’ table.

Query:

CREATE UNIQUE INDEX idx_student_batch_regno
ON student22(stud_batch,stud_reg_no);

Now we will insert some data into the student table to validate the uniqueness of the stud_batch and stud_reg_no columns.

Consider the following INSERT INTO statement for inserting a new row into the student22 table:

Query:

INSERT INTO student22
(stud_firstname, stud_lastname, stud_batch, stud_reg_no)
VALUES
('Thomas','John','A-1', '444');

Illustrate the result of the above statement by using the following snapshot and SQL statement.

Query:

select * from student22;

Output:

PostgreSQL UNIQUE Index Example 4

Again, consider the following INSERT INTO statement for inserting a new row into the student22 table, but this time we will add the same batch as we have added earlier with different stud_reg_no.

Query:

INSERT INTO student22
(stud_firstname, stud_lastname, stud_batch, stud_reg_no)
VALUES
('Thomas','John','A-1', '555');

Illustrate the result of the above statement by using the following snapshot and SQL statement.

Query:

select * from student22;

Output:

select * from Example 5

The combination of values of stud_batch and stud_reg_no columns is unique because this INSERT INTO statement worked without any error.

Again, consider the following INSERT INTO statement for inserting a new row into the student22 table, but this time we will add the same batch and stud_reg_no as we have added earlier.

Query:

INSERT INTO student22
(stud_firstname, stud_lastname, stud_batch, stud_reg_no)
VALUES
('Thomas','John','A-1', '555');

Output:

Insert the duplicate Example 6

Here we got an error which is because we are trying to insert the duplicate stud_batch, stud_reg_no, which already exists in the student22 table.

Conclusion

We hope from the above article you have understood how to use the PostgreSQL UNIQUE INDEX and how the PostgreSQL UNIQUE INDEX works. Also, we have added several examples of PostgreSQL UNIQUE INDEX to understand it in detail.

Recommended Articles

This is a guide to PostgreSQL UNIQUE Index. Here we discuss the Introduction to PostgreSQL UNIQUE Index and its working along with practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. Introduction to PostgreSQL Timestamp
  2. How to Notify Works in PostgreSQL?
  3. PostgreSQL JSON (Examples)
  4. Introduction to PostgreSQL Timestamp

PostgreSQL Course (2 Courses, 1 Project)

2 Online Courses

1 Hands-on Project

7+ Hours

Verifiable Certificate of Completion

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 - PostgreSQL Course (2 Courses, 1 Project) Learn More