The Wayback Machine - https://web.archive.org/web/20240919230803/https://www.geeksforgeeks.org/postgresql-create-index/
Open In App

PostgreSQL – CREATE INDEX

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Indexes in PostgreSQL are crucial for improving the performance of database searches. They function similarly to a phone book. Imagine looking up Raju Kumar’s phone number in an alphabetically ordered phone book. You quickly navigate to the ‘K’ section, find ‘Kumar,’ then ‘Raju,’ and finally get his phone number. This ordered search is efficient. However, if the phone book were unordered, you would have to scan every entry sequentially to find Raju Kumar, making the search time-consuming. This sequential scan is what happens when a database table lacks indexes.

Why Use Indexes?

Indexes in PostgreSQL organize table data in a particular order to speed up searches. They act like the alphabetized phone book, allowing for quick data retrieval. Without indexes, PostgreSQL performs a sequential scan, checking each row until it finds the matching data. This method is slow, especially for large datasets.

In PostgreSQL, the CREATE INDEX statement to define a new index for a table.

Syntax

CREATE INDEX index_name ON table_name [USING method]
(
    column_name [ASC | DESC] [NULLS {FIRST | LAST }],
    ...
);

Parameters

Let’s analyze the above syntax:

  • Index Name: Choose a meaningful and memorable name for the index.
  • Table Name: Specify the table to which the index belongs.
  • Index Method: Choose an index method such as ‘btree’, ‘hash’, ‘gist’, ‘spgist’, ‘gin’, or ‘brin’. PostgreSQL defaults to ‘btree’.
  • Columns: List one or more columns to include in the index.
  • Sort Order: Specify the sort order with ‘ASC’ (default) or ‘DESC’.
  • Nulls Order: Specify ‘NULLS FIRST’ or ‘NULLS LAST’. ‘NULLS FIRST’ is the default with ‘DESC’, and ‘NULLS LAST’ is the default with ‘ASC’.

For the purpose of demonstration, we will use the address table from the sample database for the demonstration.

Database

PostgreSQL CREATE INDEX Example

Let us look at an example of CREATE INDEX Statement in PostgreSQL to better understand the concept.

The following query finds the address whose phone number is 223664661973.

Query:

SELECT * FROM address
WHERE phone = '223664661973';

It is obvious that the database engine had to scan the whole address table to look for the address because there is no index available for the phone column.

To show the query plan, you use the EXPLAIN statement as follows.

Query:

EXPLAIN SELECT * FROM address
WHERE phone = '223664661973';

This will result in the following:

PostgreSQL CREATE INDEX Example

To create an index for the values in the phone column of the address table, you use the following statement.

Query:

CREATE INDEX idx_address_phone 
ON address(phone);

Now, if you execute the query again, you will find that the database engine uses the index for lookup.

Query:

EXPLAIN SELECT * FROM address
WHERE phone = '223664661973';

Output:

PostgreSQL CREATE INDEX Example

This time, the output will show that PostgreSQL uses the index for a more efficient lookup, significantly speeding up the query.


Previous Article
Next Article

Similar Reads

PostgreSQL - Connect To PostgreSQL Database Server in Python
The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python setup.py build sudo python setup.py installCreate a
4 min read
PostgreSQL - Export PostgreSQL Table to CSV file
In this article we will discuss the process of exporting a PostgreSQL Table to a CSV file. Here we will see how to export on the server and also on the client machine. For Server-Side Export: Use the below syntax to copy a PostgreSQL table from the server itself: Syntax: COPY Table_Name TO 'Path/filename.csv' CSV HEADER; Note: If you have permissio
2 min read
PostgreSQL - Installing PostgreSQL Without Admin Rights on Windows
If you are a part of a corporation, it is highly unlikely that you have the admin privileges to install any external software. But the curious souls that all software developers are, in this article, we will see the detailed process of installation of PostgreSQL without having administrator rights on our Windows machine. Installation: Follow the be
3 min read
PostgreSQL - DROP INDEX
The DROP INDEX statement in PostgreSQL is used to remove an existing index from the database. This operation is essential when an index is no longer needed or when it is not being utilized by the query optimizer. Let us get a better understanding of the PostgreSQL DROP INDEX statement in this article. SyntaxDROP INDEX [ CONCURRENTLY ] [ IF EXISTS ]
3 min read
PostgreSQL - Partial Index
In PostgreSQL, partial indexes are a powerful feature designed to improve query performance while minimizing index size. By allowing you to specify the rows of a table that should be indexed, partial indexes can significantly speed up queries that use common WHERE conditions with constant values. Let us better understand the Partial Index in Postgr
2 min read
PostgreSQL - UNIQUE Index
In PostgreSQL, a UNIQUE index is used to ensure that the values in one or more columns are unique across the rows in a table. This is essential for maintaining data integrity and avoiding duplicate entries. Let us better understand the UNIQUE Index in PostgreSQL from this article. SyntaxCREATE UNIQUE INDEX index_name ON table_name(column_name, [...
3 min read
PostgreSQL - Index Types
Indexes are essential tools in PostgreSQL, allowing you to speed up data retrieval and enhance the performance of the queries. This article will explore the various index types available in PostgreSQL, understand their unique characteristics, and learn how to use them effectively to optimize your database performance. PostgreSQL has 6 primary index
3 min read
PostgreSQL - Index On Expression
When working with databases, optimizing query performance is crucial, especially when dealing with large datasets. One powerful technique in PostgreSQL is leveraging indexes on expressions. This approach allows you to optimize queries that involve expressions, ensuring faster retrieval times and efficient database operations. In this article, we'll
3 min read
What is an Index in PostgreSQL?
PostgreSQL is a powerful and reliable open-source relational database management system (RDBMS) known for its extensive features, including robustness, scalability, and adherence to SQL standards. Indexing is one of the most important aspects that has a lot to do with the efficiency of the database. In this article, we focus on indexes in PostgreSQ
4 min read
How to Create a New User With Full Privileges in PostgreSQL?
PostgreSQL provides a way to give a user full privileges to do anything with the database. The database objects like schema, table, function, and so on. The 'GRANT' command is used in PostgreSQL to provide a user with any specific privileges or to override the role of the user. In this article, we are going to learn how we can create a new user ass
6 min read
PostgreSQL - CREATE PROCEDURE
The CREATE PROCEDURE statement in PostgreSQL is used to create new stored procedures. Stored procedures are beneficial for encapsulating business logic, especially when you need to execute transactions. A drawback of user-defined functions is that they cannot execute transactions. In other words, inside a user-defined function, you cannot start a t
3 min read
PostgreSQL - CREATE TABLE
In PostgreSQL, the CREATE TABLE clause as the name suggests is used to create a new table. Creating tables is a fundamental aspect of database design in PostgreSQL. Let us get a better understanding of the CREATE TABLE Clause in PostgreSQL. SyntaxCREATE TABLE table_name ( column_name TYPE column_constraint, table_constraint table_constraint) INHERI
3 min read
PostgreSQL - CREATE SEQUENCE
A sequence in PostgreSQL is a user-defined schema-bound object that generates a sequence of integers based on specified parameters. The CREATE SEQUENCE statement is used to create sequences in PostgreSQL. Let us get a better understanding of the CREATE SEQUENCE Statement in PostgreSQL from this article. SyntaxCREATE SEQUENCE [ IF NOT EXISTS ] seque
4 min read
PostgreSQL - CREATE SCHEMA
PostgreSQL provides the CREATE SCHEMA statement to create a new schema in a database. Schemas in PostgreSQL help organize database objects such as tables, views, and functions, allowing for better data management and security. Let us get a better understanding of the syntax, options, and examples of using the CREATE SCHEMA statement in PostgreSQL.
3 min read
PostgreSQL - CREATE ROLE
PostgreSQL uses roles to represent user accounts. Unlike other database systems that use the concept of users, PostgreSQL treats roles as the primary means of access control. Roles that can log in are called login roles, which are equivalent to users in other systems. Roles that contain other roles are known as group roles. When you create a role,
4 min read
PostgreSQL - CREATE FUNCTION Statement
PostgreSQL allows developers to create user-defined functions to encapsulate reusable logic. The CREATE FUNCTION statement is used for this purpose, supporting various procedural languages, with plpgsql being one of the most commonly used. Let us look at the syntax, structure, and practical use of CREATE FUNCTION Statement in PostgreSQL, using the
3 min read
PostgreSQL - CREATE DOMAIN
PostgreSQL supports the creation of user-defined data types through the CREATE DOMAIN and CREATE TYPE statements. These capabilities allow for the customization and extension of data types to fit specific application needs, providing more flexibility and control over data integrity and consistency.  Let us get a better understanding of the CREATE D
3 min read
PostgreSQL - Create Database
PostgreSQL provides multiple ways to create a database, catering to different user preferences and requirements. This article will discuss various methods to create a database in PostgreSQL, including using the psql shell and pgAdmin. Creating a Database Using psql ShellTo create a database through the psql shell, you can use the CREATE DATABASE st
3 min read
PostgreSQL - Create updatable Views
Views in PostgreSQL provide a way to represent a subset of a real table, selecting certain columns or rows from an ordinary table. They are particularly useful for restricting access to the original table, allowing users to see only a specific portion of it. The table from which a view is created is known as the base table. PostgreSQL supports both
3 min read
PostgreSQL - CREATE TABLE AS
The CREATE TABLE AS statement in PostgreSQL is a powerful tool used to create a new table and populate it with data returned by a query. This functionality allows you to generate tables on the fly based on query results, which can be very useful for reporting, analysis, and other tasks. Let us better understand the CREATE TABLE AS statement in Post
3 min read
PostgreSQL - CREATE TABLESPACE
In PostgreSQL, a tablespace is a mechanism used to map a logical name to a physical location on disk. Simply put, a tablespace is a disk location where PostgreSQL stores all its database objects, such as tables, indexes, and more. Understanding and utilizing tablespaces effectively can significantly enhance the management and performance of your Po
2 min read
PostgreSQL - CREATE TRIGGER
Triggers in PostgreSQL are powerful tools that allow you to automate actions in your database whenever certain events occur, like inserting, updating, or deleting data. From this article, we will better understand the CREATE TRIGGER Statement in PostgreSQL. Steps to Create Triggers in PostgreSQLTo create a new trigger in PostgreSQL, you follow thes
3 min read
PostgreSQL - Create table using Python
Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of creating tables in PostgreSQL using Python. Prere
3 min read
PostgreSQL - Create Auto-increment Column using SERIAL
In PostgreSQL, sequences play a vital role when it comes to generating unique identifiers, especially for primary key columns. A sequence is a special database object that generates a sequence of integers, which can be used as unique IDs across rows in a table. In this article, we’ll look into how sequences work, the usage of the SERIAL pseudo-type
3 min read
PostgreSQL - Create Tables in Python
Creating tables in PostgreSQL using Python is an essential skill for developers working with databases. This article will explore the process of creating new tables in the PostgreSQL database using Python. Why Create PostgreSQL Tables with Python?Using Python to create PostgreSQL tables is beneficial because Python offers powerful libraries like 'p
4 min read
PostgreSQL - Create Recursive Views
A view in PostgreSQL can be defined as a virtual table that is derived from underlying base tables or previously defined views. A view is nothing but a SQL statement that is stored in the database with an associated name. We have looked at what is the recursive query. To store the recursive query or to make a view out of a recursive query, PostgreS
4 min read
PostgreSQL - Creating Updatable Views Using WITH CHECK OPTION Clause
PostgreSQL is the most advanced general purpose open source database in the world. pgAdmin is the most popular management tool or development platform for PostgreSQL. It is also an open source development platform. It can be used in any Operating Systems and can be run either as a desktop application or as a web in your browser. In this article, we
4 min read
What is PostgreSQL - Introduction
This is an introductory article for the PostgreSQL database management system. In this we will look into the features of PostgreSQL and why it stands out among other relational database management systems. Brief History of PostgreSQL: PostgreSQL also known as Postgres, was developed by Michael Stonebraker of the University of California, Berkley. I
2 min read
Install PostgreSQL on Mac
This is a step-by-step guide to install PostgreSQL on a Mac OS machine. We will be installing PostgreSQL version 11.3 on Mac using the installer provided by EnterpriseDB in this article. There are three crucial steps for the installation of PostgreSQL as follows: Download PostgreSQL EnterpriseDB installer for MacInstall PostgreSQLVerify the install
2 min read
PostgreSQL - Loading a Database
In this article we will look into the process of loading a PostgreSQL database into the PostgreSQL database server. Before moving forward we just need to make sure of two things: PostgreSQL database server is installed on your system. A sample database. For the purpose of this article, we will be using a sample database which is DVD rental database
3 min read