From 05a5af48bed2ce3044a1769c5e197c13d1369d89 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 19 Apr 2016 22:01:24 -0500 Subject: [PATCH] Add Using Expressions In Indexes as a postgres til --- README.md | 3 ++- postgres/using-expressions-in-indexes.md | 31 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 postgres/using-expressions-in-indexes.md diff --git a/README.md b/README.md index 8a3136d..86e068b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_396 TILs and counting..._ +_397 TILs and counting..._ --- @@ -237,6 +237,7 @@ _396 TILs and counting..._ - [Types By Category](postgres/types-by-category.md) - [Use A psqlrc File For Common Settings](postgres/use-a-psqlrc-file-for-common-settings.md) - [Use Argument Indexes](postgres/use-argument-indexes.md) +- [Using Expressions In Indexes](postgres/using-expressions-in-indexes.md) - [Using Intervals To Offset Time](postgres/using-intervals-to-offset-time.md) - [Who Is The Current User](postgres/who-is-the-current-user.md) - [Word Count for a Column](postgres/word-count-for-a-column.md) diff --git a/postgres/using-expressions-in-indexes.md b/postgres/using-expressions-in-indexes.md new file mode 100644 index 0000000..3947767 --- /dev/null +++ b/postgres/using-expressions-in-indexes.md @@ -0,0 +1,31 @@ +# Using Expressions In Indexes + +Though we usually see column names by themselves when defining an index, it +is also possible to create an index with an expression. + +Let's say I have a `users` table with an `email` column. Then I may end up +creating an index like this + +```sql +create index email_idx on users (email); +``` + +If I always perform queries on the `email` column with the `lower()` +function, like this + +```sql +select * from users where lower(email) = lower('some@email.com'); +``` + +then I will want to also create an index with that full expression -- +`lower(email)` + +I can do this with a statement like the following + +```sql +create index lower_email_idx on users (lower(email)); +``` + +Without an index that uses the full `lower(email)` expression, `select` +statements like the one above will be forced to do full sequential scans +instead of indexed scans.