EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial Indexes in PostgreSQL
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

Indexes in PostgreSQL

By Priya PedamkarPriya Pedamkar

Indexes-in-PostgreSQL

Introduction to Indexes in PostgreSQL

Indexes are handy in PostgreSQL to fast retrieval of data; we can create an index on a column of the table which used in select operation for retrieving fast data; PostgreSQL index is the same as a pointer on a table; for example, If one book and we want a reference of all pages for discussion of topic later, then we have first referred index page, which has all points or topics list serially or alphabetically. Then we refer to specific page number and topics that we want to search; the same thing happens in the PostgreSQL index.

Syntax:

The index is used to increase database performance.

Create [UNIQUE] INDEX [CONCURRENTLY] [index_name] ON table_name [Using
Method (Type of index)] ( { column_name | ( expression ) } [ COLLATE collation ] [ opclass (name of operator class) ] [ ASC | DESC ] [ NULLS { FIRST | LAST (Specify the sort order of index)}] [, ...] )
[WITH (name of storage parameter)] [TABLESPACE tablespace_name] [WHERE predicate]

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Below is the description of the above syntax:

  • Unique: It causes the system to check the duplicate value in tables.
  • Concurrently: After using this parameter, PostgreSQL will create an index without locking other sessions like (Insert, Update or Delete) on tables. Without using this parameter, PostgreSQL locks the table on write operation.
  • Index name: Any name given to the index.
  • Table name: Table name, which is indexed.
  • Method: Method or type of index like Btree, Hash, etc.
  • Column: Name of the column on which we are creating the index.
  • Expression: Expression will be written in parenthesis.
  • Collation: The name of collation which is used in the index; if we have not declared, then the index will automatically take as default.
  • Opclass: This is the name of the operator class.
  • ASC: It will specify ascending sort order.
  • DESC: It will specify descending sort order.
  • Nulls first: This specifies that nulls sort before non-nulls.
  • Nulls last: This specifies that nulls sort after non-nulls.
  • Storage parameter: This is the name of the storage parameter.
  • Tablespace: Tablespace name in which we have created an index.
  • Predicate: This is a constraint expression.

How to Create Indexes in PostgreSQL?

  • PostgreSQL index is used to increase database performance. Using the index, we improve our database performance.
  • We have used the customer table for describing the index in PostgreSQL.
  • Please find below details of the creation of a new index in PostgreSQL.

1. Create a customer table and insert data into it.

testing=#CREATE TABLE customer ( cust_id INT NOT NULL, cust_name character(10) NOT NULL, cust_address character(20) NOT NULL, cust_phone character(14), PRIMARY KEY (cust_id));

testing=#INSERT INTO customer (cust_id, cust_name, cust_address, cust_phone) VALUES (1, 'ABC', 'Pune', '1234567890');

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,294 ratings)

testing=#INSERT INTO customer (cust_id, cust_name, cust_address, cust_phone) VALUES (2, 'PQR', 'Pune', '1234567890');

Output:

indexes in PostgreSQL 1

2. Create an index on the cust_id column in the customer table.

testing=#CREATE INDEX CONCURRENTLY cust_id_index ON customer (cust_id);

Output:

create index on customer id

Types of Indexes in PostgreSQL

PostgreSQL supports different types of indexes. Please find below PostgreSQL index types:

  • B-Tree
  • Hash
  • GIN (Generalized Inverted Index )
  • GiST (Generalized Inverted Search Tree)
  • SP-GiST(Space partitioned Generalized Inverted Search Tree)
  • BRIN (Block Range Indexes)

Let us discuss each of them in detail.

1. B-Tree

Btree index is most popular and fairly used in PostgreSQL while creating an index. Btree index will create a tree and stores data in a node; the node can be a variable number. The below example shows the Btree index are as follows:

Example:

testing=#CREATE INDEX CONCURRENTLY cust_id_index ON customer USING BTREE(cust_id);

Output:

indexes in PostgreSQL 4JPG

2. Hash Index

The Hash index is faster than the Btree index, but the hash index was limited to equality operations. The below example shows the HASH index is as follows:

Example:

testing=#CREATE INDEX CONCURRENTLY cust_id_index ON customer USING HASH (cust_id);

Output:

indexes in PostgreSQL 5JPG

3. GIN (Generalized Inverted Index )

Gin index is most useful when we have data types that contain multiple values in a single column. GIN index was also referred to as a generalized inverted index. The below example shows the GIN index are as follows.

Example:

testing=#CREATE INDEX gin_custname_index ON customer USING GIN (to_tsvector('English', cust_name));

Output:

GIN

4. GiST (Generalized Inverted Search Tree)

GiST index is useful when our data is in geometrical format. It is also known as the generalized search tree. The below example shows the GiST index is as follows.

Example:

testing=#CREATE INDEX gin_custname_index ON customer USING GiST (to_tsvector('English', cust_name));

Output:

GIST

5. SP-GiST(Space partitioned Generalized Inverted Search Tree)

SP-GiST index referred to as space partitioned generalized inverted search tree. An SP-Gist index is most useful when our data is a clustering element or in clustered format. The best example is the phone number. The below example shows the SP-GiST index as follows.

Example:

Create a table for the creation of the SP-GiST index.

testing=#create table order_spgist (order_id int, phone int4range);

testing=#insert into order_spgist select order_id, int4range(order_id, order_id+(random()*10)::int) from generate_series(1,10) t(order_id);

Create an SP-GiST index.

testing=#CREATE INDEX gin_custphone_index ON customer USING SPGiST (to_tsvector('English', cust_phone));

Output:

SP-GiST 8JPG

6. BRIN (Block Range Indexes)

BRIN index is useful when a large number of natural clustered format data. BRIN index also called block range indexes. The below example shows the BRIN index as follows.

Example:

testing=#create index brin_cust_id on customer using brin (cust_id) with (pages_per_range=1);

Output:

BRIN

How to Drop Indexes in PostgreSQL?

The index is dropped in PostgreSQL using the drop command below is the syntax and example for the same.

Syntax:

DROP INDEX index_name;

Example: 

testing=#drop index cust_id_index;

Output:

indexes in PostgreSQL 10JPG

Examples:

Below is an example of creating an index in PostgreSQL.

testing=#CREATE UNIQUE INDEX custid_idx ON customer (cust_id);

testing=#CREATE INDEX custname_idx ON customer ((lower(cust_name)));

testing=#CREATE INDEX custaddress_idx ON customer (cust_address COLLATE "de_DE");

testing=#CREATE INDEX custname_idx1 ON customer (cust_name NULLS FIRST);

testing=#CREATE INDEX custid_idx1 ON customer (cust_id) TABLESPACE pg_default;

Output:

indexes in PostgreSQL 11JPG

indexes in PostgreSQL 12JPG

Conclusion

It is used to fast the retrieval of data. PostgreSQL index has its specific structure to look at data and fastest the operation of data retrieval.PostgreSQL is basically used the Btree index by default if we have not mentioned the index type at the time of index creation.

Recommended Articles

This has been a guide to Indexes in PostgreSQL. Here we discuss the introduction, types and how to create Indexes in PostgreSQL? You may also have a look at the following articles to learn more –

  1. ORDER BY in Oracle
  2. Database in SQL​ 
  3. Django Framework
  4. Relational Database
  5. Primary Key in SQL | How to Use?
  6. Different Operations of Indexes in Hive
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more