Partial Indexes are a way to create indexing on a partial data set of a table which satisfies the given logic.
Let's get into an exmaple to understand partial indexes in Postgres.
Let us take an an exmaple of Bus tickets booking platform where we have table called
bookings which stores the bookings, to keep things simple let us assume it only contains
Most of the time users would like to check their upcoming bookings and also as part of Booking platform features, the success bookings are highly retreived.
So it is always a good idea to index the success booking records, we can have a partial index for success booking as shown below.
CREATE INDEX bookings_status_idx ON bookings (status) where status = 'SUCCESS';
Now comes the important use case where we can avoid duplicate bookings for the same seat in a bus, either from a same user of different user, In this case we cannnot use multi-column unique constraint becasue there might be multiple records in
bookings table for a same
So, Here we need to have conditional unique constraint on
status field where
status = 'SUCCESS'. we can add conditional unique constraints using unique partial indexes
Eg: Query to create unique partial indexes for the above mentioned use case.
CREATE UNIQUE INDEX bookings_status_idx ON bookings (bus_id, seat_number, date, time) where status = 'SUCCESS';
These partial indexes become handy for developers to avoid duplication of records for high concurrency tables.