Explain Codes LogoExplain Codes Logo

How do I ALTER a PostgreSQL table and make a column unique?

sql
unique-constraint
postgresql
database-design
Anton ShumikhinbyAnton Shumikhin·Aug 22, 2024
TLDR

To ensure a column's values are unique in a PostgreSQL table, use:

ALTER TABLE tableName ADD UNIQUE (columnName);

This snippet enforces uniqueness directly on columnName. However, don't forget to preview your table for duplicates to avoid constraint violation errors.

Pre-check for duplicates

Before running the ALTER command, it's good practice to first check your table for potential duplicates in the target column:

SELECT columnName, COUNT(*) FROM tableName GROUP BY columnName HAVING COUNT(*) > 1;

If any duplicates appear, resolve them—by either updating, deleting, or addressing as per your requirements—prior to applying the unique constraint.

Naming and enforcing the unique constraint

Apply the unique constraint and name it for future manageability:

ALTER TABLE tableName ADD CONSTRAINT uniqueConstraintName UNIQUE (columnName);

This way, by providing a unique name (like uniqueConstraintName), it would prove easy to identify and manage in future operations.

Applying uniqueness over multiple columns

Unique constraints can be applied over multiple columns:

ALTER TABLE tableName ADD CONSTRAINT uniqueConstraintName UNIQUE (column1, column2);

Here, the combined values in column1 and column2 across all rows should be unique.

Transactional security with rollback

Engage transaction block for safe alterations:

BEGIN; -- Let's add some flair - unique ones only! ALTER TABLE tableName ADD UNIQUE (columnName); /* Run additional checks / operations here, such as: - spot check some data - trigger dependent processes - grab a coffee */ COMMIT; -- All good? Commit transaction.

In case of setbacks, just rollback your transaction—keeping your table in a safe, pre-change condition.

Considering performance

Remember, applying a unique constraint creates an index — great for lookups, but factors in during writing operations. It's like a librarian keeping your books sorted—faster to locate but takes some time to organise new arrivals.

Moniter ongoing uniqueness

Remember, PostgreSQL isn't just a storage bin—it's an organised, high-performing database. After setting your unique constraints, keep an eye on your data to prevent unexpected redundancies.