File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1352 TILs and counting..._
13
+ _ 1353 TILs and counting..._
14
14
15
15
---
16
16
@@ -639,6 +639,7 @@ _1352 TILs and counting..._
639
639
- [ Count The Number Of Trues In An Aggregate Query] ( postgres/count-the-number-of-trues-in-an-aggregate-query.md )
640
640
- [ Create A Composite Primary Key] ( postgres/create-a-composite-primary-key.md )
641
641
- [ 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 )
642
643
- [ Create An Index Without Locking The Table] ( postgres/create-an-index-without-locking-the-table.md )
643
644
- [ Create Database Uses Template1] ( postgres/create-database-uses-template1.md )
644
645
- [ Create hstore From Two Arrays] ( postgres/create-hstore-from-two-arrays.md )
Original file line number Diff line number Diff line change
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.
You can’t perform that action at this time.
0 commit comments