Skip to content

Commit 6f2ae93

Browse files
committed
Add Create An Index Across Two Columns as a Postgres TIL
1 parent f03bf4c commit 6f2ae93

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1352 TILs and counting..._
13+
_1353 TILs and counting..._
1414

1515
---
1616

@@ -639,6 +639,7 @@ _1352 TILs and counting..._
639639
- [Count The Number Of Trues In An Aggregate Query](postgres/count-the-number-of-trues-in-an-aggregate-query.md)
640640
- [Create A Composite Primary Key](postgres/create-a-composite-primary-key.md)
641641
- [Create A Table From The Structure Of Another](postgres/create-a-table-from-the-structure-of-another.md)
642+
- [Create An Index Across Two Columns](postgres/create-an-index-across-two-columns.md)
642643
- [Create An Index Without Locking The Table](postgres/create-an-index-without-locking-the-table.md)
643644
- [Create Database Uses Template1](postgres/create-database-uses-template1.md)
644645
- [Create hstore From Two Arrays](postgres/create-hstore-from-two-arrays.md)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Create An Index Across Two Columns
2+
3+
Most commonly when we create an index, it is targeted at a single column of a
4+
table. Sometimes an expensive query that works with two different columns would
5+
be better off with an index that combines those two columns. This is called a
6+
_composite index_.
7+
8+
Let's consider this query:
9+
10+
```sql
11+
select * from events
12+
where user_id = 123
13+
order by created_at desc
14+
limit 1;
15+
```
16+
17+
Though this query will use the index on `created_at` to do an Index Scan, it
18+
will still have to do a bunch of expensive filtering of `user_id` values after
19+
the fact.
20+
21+
What this query needs to be efficient is a _composite index_ on `user_id` and
22+
`created_at`. We can create one like so:
23+
24+
```sql
25+
create index events_user_id_created_at_idx
26+
on events (user_id, created_at);
27+
```
28+
29+
Instead of doing a bunch of post-index filtering on `user_id` values, that
30+
expensive query will factor `user_id` into its Index Scan and complete much
31+
quicker.
32+
33+
See [the Postgres docs on multicolumn
34+
indexes](https://www.postgresql.org/docs/current/indexes-multicolumn.html) for
35+
more details.

0 commit comments

Comments
 (0)