1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Create An Index Across Two Columns as a Postgres TIL

This commit is contained in:
jbranchaud
2023-11-29 16:23:24 -06:00
parent f03bf4cb70
commit 6f2ae93e45
2 changed files with 37 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1352 TILs and counting..._
_1353 TILs and counting..._
---
@@ -639,6 +639,7 @@ _1352 TILs and counting..._
- [Count The Number Of Trues In An Aggregate Query](postgres/count-the-number-of-trues-in-an-aggregate-query.md)
- [Create A Composite Primary Key](postgres/create-a-composite-primary-key.md)
- [Create A Table From The Structure Of Another](postgres/create-a-table-from-the-structure-of-another.md)
- [Create An Index Across Two Columns](postgres/create-an-index-across-two-columns.md)
- [Create An Index Without Locking The Table](postgres/create-an-index-without-locking-the-table.md)
- [Create Database Uses Template1](postgres/create-database-uses-template1.md)
- [Create hstore From Two Arrays](postgres/create-hstore-from-two-arrays.md)

View File

@@ -0,0 +1,35 @@
# Create An Index Across Two Columns
Most commonly when we create an index, it is targeted at a single column of a
table. Sometimes an expensive query that works with two different columns would
be better off with an index that combines those two columns. This is called a
_composite index_.
Let's consider this query:
```sql
select * from events
where user_id = 123
order by created_at desc
limit 1;
```
Though this query will use the index on `created_at` to do an Index Scan, it
will still have to do a bunch of expensive filtering of `user_id` values after
the fact.
What this query needs to be efficient is a _composite index_ on `user_id` and
`created_at`. We can create one like so:
```sql
create index events_user_id_created_at_idx
on events (user_id, created_at);
```
Instead of doing a bunch of post-index filtering on `user_id` values, that
expensive query will factor `user_id` into its Index Scan and complete much
quicker.
See [the Postgres docs on multicolumn
indexes](https://www.postgresql.org/docs/current/indexes-multicolumn.html) for
more details.