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 - CREATE INDEX

Creating an index on a table is essential for improving the performance of query operations, especially for tables with a significant number of rows. An index provides a faster lookup path to the rows in a table based on the values of one or more columns.

In PostgreSQL, the CREATE INDEX command is used to create an index on one or more columns of a table.

Syntax:

CREATE INDEX index_name ON table_name (column_name [ASC|DESC] [NULLS {FIRST | LAST }], ...);
  • index_name: Name of the index.
  • table_name: Name of the table on which the index is to be created.
  • column_name: Name of the column(s) on which the index is to be created.
  • ASC|DESC: Specifies the sort order for the indexed column. (Optional)
  • NULLS FIRST|LAST: Determines the sort order for null values. (Optional)

Basic Example:

To create an index on the email column of a users table:

CREATE INDEX idx_users_email ON users (email);

Composite Index:

To create a composite index on multiple columns, you can list multiple columns separated by commas:

CREATE INDEX idx_users_firstname_lastname ON users (firstname, lastname);

Using Expressions:

You can also create an index on the result of an expression:

CREATE INDEX idx_users_lower_email ON users (LOWER(email));

This creates an index on the lowercase version of the email column, which might be useful if you frequently search for email addresses without case sensitivity.

Unique Index:

If you want to ensure that the values in the indexed column(s) are unique, you can create a unique index:

CREATE UNIQUE INDEX idx_users_unique_email ON users (email);

Using Different Index Types:

PostgreSQL supports several index types: B-tree, Hash, GiST, SP-GiST, GIN, and BRIN. Each type is suited for particular use cases. By default, the B-tree index type is used. However, you can specify a different type using the USING clause:

CREATE INDEX idx_users_email_gin ON users USING GIN (email);

Partial Index:

A partial index is an index built over a subset of a table; the subset is defined by a conditional expression provided in the WHERE clause:

CREATE INDEX idx_active_users_email ON users (email) WHERE status = 'active';

Note:

  1. Creating an index can be resource-intensive and can lock the table, making it unavailable for write operations for the duration of the index creation. For large tables, consider using the CONCURRENTLY option, which allows writes to the table while the index is being built:

    CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
    
  2. Indexes can significantly speed up query performance but also come with some overhead during data modification (INSERT, UPDATE, DELETE) and use disk space. Always monitor the system's performance and storage.

  3. Periodically, you should check for unused or duplicate indexes which can be dropped to reclaim space and reduce the overhead during data modifications.

  4. Remember to analyze the query patterns and the table's data distribution before creating an index. The decision to index a particular column or set of columns should be based on the queries you run most frequently.

  1. Creating indexes on single columns in PostgreSQL:

    • Description: Creates an index on a single column to improve query performance.
    • Code:
      CREATE INDEX your_index_name ON your_table (your_column);
      
  2. Composite indexes with CREATE INDEX in PostgreSQL:

    • Description: Creates an index on multiple columns to speed up queries involving those columns.
    • Code:
      CREATE INDEX your_composite_index ON your_table (column1, column2);
      
  3. Unique indexes and constraints with CREATE INDEX in PostgreSQL:

    • Description: Ensures that the indexed columns contain unique values.
    • Code:
      CREATE UNIQUE INDEX your_unique_index ON your_table (your_column);
      
  4. Partial indexes in PostgreSQL:

    • Description: Creates an index based on a subset of rows defined by a condition.
    • Code:
      CREATE INDEX your_partial_index ON your_table (your_column) WHERE condition;
      
  5. Concurrent index creation in PostgreSQL:

    • Description: Allows creating an index without blocking concurrent write operations.
    • Code:
      CREATE INDEX CONCURRENTLY your_index_name ON your_table (your_column);
      
  6. Indexing expressions and functions in PostgreSQL:

    • Description: Creates an index on an expression or function result.
    • Code:
      CREATE INDEX your_expression_index ON your_table (LOWER(your_column));
      
  7. Using DESC and ASC options with CREATE INDEX in PostgreSQL:

    • Description: Specifies the sort order of the index, ascending (ASC) or descending (DESC).
    • Code:
      CREATE INDEX your_index_name ON your_table (your_column DESC);
      
  8. B-tree vs Hash indexes in PostgreSQL:

    • Description: B-tree is the default index type; hash indexes are suitable for equality comparisons.
    • Code:
      CREATE INDEX your_btree_index ON your_table (your_column);
      CREATE INDEX your_hash_index ON your_table USING HASH (your_column);