POSTGRESQL

All You Need to Know About PostgreSQL UNIQUE Constraint

intro

Learn everything about the PostgreSQL UNIQUE constraint and use it to ensure that values stored in a column or a group of columns are unique across rows in a table.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT
PostgreSQL logo POSTGRESQL
THE POSTGRESQL DATABASE

The PostgreSQL UNIQUE constraint makes sure that each record in our table is identifiable in its own unique way, preventing the creation of duplicate data and further protecting the evenness of our database.

In this guide, you will learn what this constrain is, how to use it, and when. Let’s dive in!

What Is the UNIQUE PostgreSQL Constraint?

The PostgreSQLUNIQUE constraint guarantees that all values in a column or a group of columns are distinct from one another. This means no two rows can have the same value(s) in the specified column(s).

The primary characteristics of a UNIQUE constraint are:

  • Ensuring Uniqueness: Each value in the column or a set of columns is unique.
  • Nullability: Unlike primary keys, columns with the UNIQUE constraints can contain NULL values, but NULLs are not considered equal to other NULLs.

Unique constraints can be defined on a single column or a combination of multiple columns, known as a composite unique constraint. This flexibility allows us to tailor our data model to our specific requirements, assuring that unique business rules are enforced at the database level.

How to Use the PostgreSQL UNIQUE Constraint

Defining a UNIQUE PostgreSQL constraint is pretty straightforward. When it is applied on a column constraint in a CREATE TABLE query, the syntax is:

Copy
        
1 CREATE TABLE table_name ( 2 column_name data_type UNIQUE 3 );

When written as a table constraint, it is so:

Copy
        
1 CREATE TABLE my_table ( 2 column_name data_type, 3 UNIQUE (column_name) 4 );

You can also add a unique constraint to an existing table using the ALTER TABLE statement:

Copy
        
1 ALTER TABLE my_table 2 ADD UNIQUE (column);

If you want to specify a UNIQUE constraint for more than a column or a group of columns, write your query as a table constraint and ensure that the column names are separated with commas:

Copy
        
1 CREATE TABLE my_table ( 2 column_1 data_type, 3 column_2 data_type, 4 column_3 data_type, 5 UNIQUE (column_1, column_2) 6 );

This indicates that, although any one of the columns need not be (and typically isn't) unique, the combination of values in the stated columns must be unique throughout the entire table. You may also call this style of application the composite UNIQUE constraint style.

PostgreSQL UNIQUE Violation Conditions

These are the scenarios where a UNIQUE constraint is violated in PostgreSQL:

  1. Trying to insert a new record with a value in a UNIQUE column (or set of columns) that already exists in the table will cause PostgreSQL to throw a unique constraint violation error.
  2. Updating an existing record with a value in a UNIQUE column (or set of columns) that already exists in another row.

UNIQUE Constraint in PostgreSQL: Use Cases

Now that you know the syntax behind PostgreSQL UNIQUE and how it works, you are ready to explore its use cases.

Keep it at the back of your mind that all demonstrations will be done in DbVisualizer—the database client with the highest user satisfaction in the market, and the only database client that is capable of doing this —Joking haha! Any other database client can take care of this.

Use Case #1 - Testing Validity of Unique Violation Rules

The statement below creates a person table with a UNIQUE constraint on the email column.

Screenshot 2024-06-25 at 7.17.24 PM.png
Create the person table

We know from our previous section that this same statement can be rewritten this way:

Screenshot 2024-06-25 at 7.33.06 PM.png
Create person table rewritten

Previously, we said that the UNIQUE PostgreSQL constraint is violated and will throw an error if you try to insert a new record with a value in a UNIQUE column (or set of columns) that already exists in the table, right?

Let’s test this rule to see if indeed, PostgreSQL will throw this UNIQUE constraint violation error - we got all the time in the world, and the best database client on our side!

First, populate the person table with data with this statement👇🏽

Copy
        
1 INSERT INTO person(first_name,last_name,email) 2 VALUES('Desiree','Vance','deevance@dbvis.com');
Screenshot 2024-06-26 at 1.50.27 PM.png
Populate the person table

Secondly, try to populate another row with data but ensure that the email is the same as the email in the data that was initially inserted into our table (deevance2dbvis.com).

Copy
        
1 INSERT INTO person(first_name,last_name,email) 2 VALUES('Chris','Hughton','deevance@dbvis.com');
June 26 Screenshot from Markup Hero.jpg
Populate row

And indeed, PostgreSQL issues an error.

Use Case #2 - Implementing a Unique Constraint on a Group of Columns

We’ve also learned that the unique constraints can be applied to a combination of columns and this is known as a composite unique constraint. This can be particularly useful when you need to ensure the uniqueness of a set of values, rather than a single column only.

Assuming you have a transactionstable where you are monitoring order details and want to ensure that every order is distinct using the combination of product_id and customer_id:

Copy
        
1 CREATE TABLE transactions ( 2 id SERIAL PRIMARY KEY, 3 customer_id INT NOT NULL, 4 product_id INT NOT NULL, 5 quantity INT NOT NULL, 6 UNIQUE (customer_id, product_id) 7 );

With this composite unique constraint in your database, you can prevent a customer from placing multiple orders for the same product, preventing potential issues in your application.

DbVisualizer makes visualizing data inside of your database instance, no matter what kind of DBMS you find yourself using. The image below shows one of the features of DbVisualizer: the SQL DDL query viewer:

Viewing the DDL structure of a table in DbVisualizer
Viewing the DDL structure of a table in DbVisualizer

Use Case #3 - Adding A UNIQUE Constraint To An Existing Table

Time to take a look at a scenario where you may want to add a unique constraint to an existing column or group of columns.

Assume we already have a sales_2023_sourcea table. We’re going to add a unique constraint to the sales_2023_sourcea table using this statement:

Copy
        
1 ALTER TABLE sales_2023_sourcea ADD CONSTRAINT unique_saleid UNIQUE (saleid);
Screenshot 2024-06-26 at 6.05.31 PM.png
Add constraint

And if by any chance, we want to drop our PostgreSQL UNIQUE constraint, we would do this:

Copy
        
1 ALTER TABLE sales_2023_sourcea ADD CONSTRAINT unique_saleid UNIQUE (saleid);
Newly added UNIQUE constraint to existing table
Newly added UNIQUE constraint to existing table

Best Practices and Considerations

Consider the following best practices when working with UNIQUE constraints in PostgreSQL:

  • Evaluate whether a single-column unique constraint or a composite unique constraint better suits your data model and business requirements.
  • UNIQUE constraints automatically create indexes to enforce uniqueness, but you can also manually create indexes to further optimize query performance.
  • In your application, be prepared to handle unique constraint violations and provide meaningful feedback to users when they attempt to insert duplicate data.

Extra: Nuances Between UNIQUE Constraint Vs Primary Keys

Both primary keys and UNIQUE constraints enforce the uniqueness of our database records. However, there are some subtle distinctions you must know:

UNIQUE ConstraintsPrimary Keys
Allow NULL valuesDo not allow NULL values
Creates a non-clustered index which does not affect the physical order of the table dataCreate a clustered index that affects the physical order of the table data
A table can have multiple UNIQUE constraintsA table can have only one primary key constraint.

NB: Only use the UNIQUE constraint when you need to ensure the uniqueness of your db records without the restrictions imposed by primary keys.

Conclusion

In this blog, we have looked at the UNIQUE constraint in PostgreSQL, its power syntax, how to use it and every other thing - not excluding the its violation rules. To better appreciate the power of this constraint, you need a tool that helps you manage databases and visually explore query results. This is where a full-featured database client like DbVisualizer comes in. In addition to being able to connect to several DBMSs, it offers advanced query optimization functionality and full support for all database features. Download DbVisualizer for free now! It will surprise you with many things. Take an expo of all of our features, the Pro version of DbVisualizer is free for 21 days.

FAQ

What is the UNIQUE constraint in PostgreSQL?

The UNIQUE constraint in PostgreSQL ensures that the values in a column (or a set of columns) are unique across all rows in a table, meaning you cannot have duplicate values in the column(s) with this constraint.

How do I create a UNIQUE PostgreSQL constraint?

Creating it is simple. You can create a PostgreSQL UNIQUE constraint using any of the following ways:

During the creation of a new table:

Copy
        
1 CREATE TABLE users ( 2 id SERIAL PRIMARY KEY, 3 email VARCHAR(255) UNIQUE, 4 username VARCHAR(50) 5 );

Adding it to an already existing table:

Copy
        
1 ALTER TABLE users 2 ADD UNIQUE (username);

Specifying it for a group of columns:

Copy
        
1 CREATE TABLE users ( 2 id SERIAL PRIMARY KEY, 3 email VARCHAR(255), 4 username VARCHAR(50) 5 UNIQUE (email, username) 6 );

Can a UNIQUE constraint have NULL values?

Yes, a UNIQUE constraint in PostgreSQL allows NULL values. You can have multiple rows where all columns in the constraint are NULL, and it won't cause a violation error.

Can I have multiple UNIQUE constraints on a single table?

Yes, you can have multiple UNIQUE constraints on a single table in PostgreSQL. Each UNIQUE constraint applies to a specific column or a set of columns.

Dbvis download link img
About the author
Leslie S. Gyamfi.
Leslie S. Gyamfi
Leslie Gyamfi is a mobile/web app developer with a passion for creating innovative solutions. He is dedicated to delivering high-quality products and technical articles. You can connect with him on LinkedIn
The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

How to Use a Recursive CTE in SQL

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 5 min 2025-01-22
title

How to Use MERGE in SQL Query Statements: Complete Guide

author Antonello Zanini tags ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-01-20
title

What Is a PostgreSQL Primary Key?

author Leslie S. Gyamfi tags POSTGRESQL 8 min 2024-12-18
title

SQL CHECK Constraint: Definitive Guide With Examples

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-16
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

How to Find Elements In an Array: PostgreSQL Guide

author Antonello Zanini tags POSTGRESQL 3 min 2024-12-05
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

List of SQL Reserved Words in All Major Databases

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 16 min 2024-11-20
title

SQL Variable: What It Is and How To Use It

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-11-18

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.