Alex Yarotsky Profile picture
Daily best practices for scaling #PostgreSQL and making queries faster | CTO at @Hubstaff
Feb 21 β€’ 11 tweets β€’ 3 min read
9 #PostgreSQL Indexing Tips Every #rails Dev Should Know πŸš€

Indexes are your first #database optimization tactic. Get them right, and everything else gets easier.

1️⃣ BTREE – The default. Rock solid for lookups.
2️⃣ GIN – JSONB & full-text search on steroids.
3️⃣ BRIN – Huge, sequential tables? Use this.
4️⃣ Partial – Only index what actually matters.
5️⃣ Covering – Store extra columns, skip table lookups.
6️⃣ Unique – Constraints, but without the overhead.
7️⃣ Concurrent – Add indexes without downtime.
8️⃣ Expression – Index computed values, query smarter.
9️⃣ Multi-Column – Optimize multiple WHEREs.

Let’s break these down πŸ§΅πŸ‘‡ 1️⃣ BTREE Indexes – The default and most commonly used in PostgreSQL. Perfect for:

βœ… Equality queries (id = ?)
βœ… Range queries (created_at > ?)
βœ… Sorting (ORDER BY name ASC)

πŸ”Ž PostgreSQL uses BTREE for indexing primary keys by default, so no need to manually create one. But for frequently queried columns, adding an index manually can speed things up significantly.

CREATE INDEX idx_users_lastname ON users (last_name);

This will improve performance for queries like:

SELECT * FROM users WHERE last_name = 'Doe';