PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - UNIQUE Index

In PostgreSQL, an index is used to speed up the retrieval of rows from a database table. A UNIQUE index, as the name suggests, ensures that the values of the indexed column(s) are unique across all rows in the table.

When you apply a UNIQUE constraint to a column or a set of columns in PostgreSQL, the system automatically creates a UNIQUE index on the same column(s). Thus, the UNIQUE constraint and the UNIQUE index are closely related, but while the primary purpose of the former is data integrity, the primary purpose of the latter is performance optimization (though it also enforces uniqueness).

Key Points:

  1. Creating a UNIQUE Index:

    You can explicitly create a UNIQUE index using the CREATE UNIQUE INDEX command:

    CREATE UNIQUE INDEX index_name ON table_name (column_name);
    

    For multiple columns:

    CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
    
  2. Dropping a UNIQUE Index:

    To drop a UNIQUE index:

    DROP INDEX index_name;
    
  3. Implied Creation:

    As mentioned earlier, when you add a UNIQUE constraint to a table, PostgreSQL will automatically create a UNIQUE index for you. This index is used to efficiently check the uniqueness constraint for new or modified data.

  4. Performance Consideration:

    • The presence of an index (including a UNIQUE index) can speed up data retrieval operations, especially for large datasets.
    • However, indices also have a cost. They can slow down write operations (like INSERT, UPDATE, and DELETE) because the index needs to be updated in addition to the table.
    • Indices also consume additional storage space.
  5. Handling Violations:

    If you attempt to insert or update a record in a way that would violate the uniqueness enforced by a UNIQUE index, PostgreSQL will raise a unique violation error, and the operation will fail.

  6. NULL Values:

    Just like the UNIQUE constraint, a UNIQUE index allows multiple NULL values. This is because, in SQL, NULL is considered unknown, and two unknown values are not considered equal to each other.

  7. Concurrent Index Creation:

    Creating an index can be a time-consuming operation, especially for large tables. PostgreSQL allows you to create indices concurrently, which reduces the lock time on the table. However, creating indexes concurrently might be slower. Here's how you can do it:

    CREATE UNIQUE INDEX CONCURRENTLY index_name ON table_name (column_name);
    

In summary, a UNIQUE index in PostgreSQL not only optimizes the performance of data retrieval operations but also ensures the uniqueness of data in the indexed column(s). It's a combination of performance and data integrity features. However, as with any index, it's crucial to weigh the benefits of faster read operations against the costs in write performance and storage.

  1. PostgreSQL UNIQUE index example: Create a unique index on a single column:

    CREATE TABLE example_table (
       id serial PRIMARY KEY,
       unique_column INTEGER,
       other_column VARCHAR(50)
    );
    
    CREATE UNIQUE INDEX unique_index ON example_table (unique_column);
    
  2. How to create UNIQUE index in PostgreSQL: Use the CREATE UNIQUE INDEX statement to create a unique index:

    CREATE UNIQUE INDEX unique_index_name ON table_name (column_name);
    
  3. PostgreSQL UNIQUE index on multiple columns: Create a unique index on multiple columns:

    CREATE TABLE example_table (
       id serial PRIMARY KEY,
       column1 INTEGER,
       column2 VARCHAR(50)
    );
    
    CREATE UNIQUE INDEX unique_index ON example_table (column1, column2);
    
  4. Remove UNIQUE index in PostgreSQL: Drop a unique index:

    DROP INDEX unique_index_name;
    
  5. Check if a column has UNIQUE index in PostgreSQL: Query the pg_indexes system catalog to check if a column has a unique index:

    SELECT indexname FROM pg_indexes WHERE tablename = 'example_table' AND indexdef LIKE '%UNIQUE%';
    
  6. PostgreSQL composite UNIQUE index: Create a composite unique index on multiple columns:

    CREATE TABLE example_table (
       id serial PRIMARY KEY,
       column1 INTEGER,
       column2 VARCHAR(50)
    );
    
    CREATE UNIQUE INDEX unique_index ON example_table (column1, column2);
    
  7. Enforce case-insensitive UNIQUE index in PostgreSQL: Use a case-insensitive collation to create a unique index that considers case-insensitivity:

    CREATE TABLE example_table (
       id serial PRIMARY KEY,
       case_insensitive_column VARCHAR(50) COLLATE "en_US",
    );
    
    CREATE UNIQUE INDEX unique_index ON example_table (case_insensitive_column);
    
  8. ALTER TABLE ADD UNIQUE index in PostgreSQL: Add a unique index using ALTER TABLE:

    ALTER TABLE example_table
    ADD CONSTRAINT unique_constraint UNIQUE (existing_column);