From 272c5d72991f1633e0c44bc379321077919c4e34 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 26 Apr 2016 21:45:50 -0500 Subject: [PATCH] Add Lower Is Faster Than ilike as a postgres til --- README.md | 3 ++- postgres/lower-is-faster-than-ilike.md | 33 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 postgres/lower-is-faster-than-ilike.md diff --git a/README.md b/README.md index b8c233b..9df0e95 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/). -_402 TILs and counting..._ +_403 TILs and counting..._ --- @@ -211,6 +211,7 @@ _402 TILs and counting..._ - [List Connections To A Database](postgres/list-connections-to-a-database.md) - [List Database Users](postgres/list-database-users.md) - [List Various Kinds Of Objects](postgres/list-various-kinds-of-objects.md) +- [Lower Is Faster Than ilike](postgres/lower-is-faster-than-ilike.md) - [Max Identifier Length Is 63 Bytes](postgres/max-identifier-length-is-63-bytes.md) - [pg Prefix Is Reserved For System Schemas](postgres/pg-prefix-is-reserved-for-system-schemas.md) - [Pretty Print Data Sizes](postgres/pretty-print-data-sizes.md) diff --git a/postgres/lower-is-faster-than-ilike.md b/postgres/lower-is-faster-than-ilike.md new file mode 100644 index 0000000..17dfdba --- /dev/null +++ b/postgres/lower-is-faster-than-ilike.md @@ -0,0 +1,33 @@ +# Lower Is Faster Than ilike + +There are a couple ways to do a case-insensitive comparison of data in +PostgreSQL. One way is to use the `ilike` operator for comparison. Another +way is to use the `lower()` function on both sides of the `=` operator for +comparison. Using `lower()` is a bit faster than using `ilike`. + +When comparing + +```sql +select * from users where email ilike 'some-email@example.com'; +``` + +to + +```sql +select * from users where lower(email) = lower('some-email@example.com'); +``` + +we find (via `explain analyze`) that using `lower()` was taking around 12ms +where as the `ilike` example was taking around 17ms. + +We earn orders of magnitude in performance when adding a functional index +that uses the `lower()` function like so: + +```sql +create unique index users_unique_lower_email_idx on users (lower(email)); +``` + +After adding this index, the example using `lower()` drops to around 0.08ms. + +For the full example and `explain analyze` outputs, [see this +document](https://github.com/jbranchaud/postgresing/blob/master/ilike_vs_lower.sql).