From 5bcdbbb3c79fcf2236d62edff6c33df7526f01ca Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 27 Apr 2024 22:48:32 -0500 Subject: [PATCH] Add Include Columns In A Covering Index as a Postgres TIL --- README.md | 3 +- .../include-columns-in-a-covering-index.md | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 postgres/include-columns-in-a-covering-index.md diff --git a/README.md b/README.md index 20b5a80..b5d4f1c 100644 --- a/README.md +++ b/README.md @@ -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). -_1421 TILs and counting..._ +_1422 TILs and counting..._ --- @@ -738,6 +738,7 @@ _1421 TILs and counting..._ - [Group By The Result Of A Function Call](postgres/group-by-the-result-of-a-function-call.md) - [Idempotent Inserts](postgres/idempotent-inserts.md) - [Include All Queries In The Log File](postgres/include-all-queries-in-the-log-file.md) +- [Include Columns In A Covering Index](postgres/include-columns-in-a-covering-index.md) - [Include Multiple Tables In A pg_dump](postgres/include-multiple-tables-in-a-pg-dump.md) - [Insert A Bunch Of Records With Generate Series](postgres/insert-a-bunch-of-records-with-generate-series.md) - [Insert Just The Defaults](postgres/insert-just-the-defaults.md) diff --git a/postgres/include-columns-in-a-covering-index.md b/postgres/include-columns-in-a-covering-index.md new file mode 100644 index 0000000..0d71618 --- /dev/null +++ b/postgres/include-columns-in-a-covering-index.md @@ -0,0 +1,33 @@ +# Include Columns In A Covering Index + +A _covering index_ is a special type of B-Tree index that, in addition to +indexing on a certain field, also _includes_ one or more columns as extra data +in the leaves of the tree. When created correctly, this can speed up the +queries it targets by achieving an _index-only scan_. + +Let's say we have a frequently run query on a large `events` table that looks +like this: + +```sql +select user_id, identifier, type + from events + where user_id = $1; +``` + +Here is what it looks like to create an index for this query with the `include` +keyword: + +```sql +create index user_id_on_events_idx + on (user_id) + includes (identifier, type); +``` + +An index on its own can already cause a significant speed up to the queries it +targets, but may still need to retrieve some `select` attributes from the +table. For hot-path queries with a set of specific columns always included in +the select, there can be significant additional speed ups by having the index +_cover_ those columns. + +For more details, check out [A Close Look At The Index Include +Clause](https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes).