DEV Community

Ahmad khattab
Ahmad khattab

Posted on

4 2

Discoveries in Ruby(and Rails): Partial indexes with Postgres

Rails has support for partial indexes when used with Postgres. According to Postgres a partial index is defined as "A partial index is an index built over a subset of a table".

What it is used for?. Imagine you provide users of your app to delete their account. But, for some reason you want to soft delete the account, maybe for data analysis purposes, or to give the user a grace period where they can undo it. A soft-deleted email is considered to be not taken, because although there is a record with the email in the database, but it is not used(soft deleted)

Then, it does not make sense to include that record's index(which contains a pointer to the original row in the users table) in the index file. This speeds up queries by ignoring soft-deleted users records.

Adding partial indexes with Postgres could look like this in SQL

CREATE UNIQUE INDEX users_email_deleted_at_is_not_null
ON users (email) WHERE deleted_at IS NULL;
Enter fullscreen mode Exit fullscreen mode

Thankfully, you can pass a where: condition as an argument to add_index. So, the above code will look like this in rails's migration

add_index :users, :email, unique: true, where: "(deleted_at IS NULL)"
Enter fullscreen mode Exit fullscreen mode

Thanks for reading, happy coding!.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️