开发者

Case insensitive search in database with an index?

开发者 https://www.devze.com 2023-01-09 09:52 出处:网络
I\'m using Postgres. I have a table of Artices in my databas开发者_如何学Goe, with a column url for url slugs. These are so that I can display the articles in that table on a website as not \"example

I'm using Postgres.

I have a table of Artices in my databas开发者_如何学Goe, with a column url for url slugs. These are so that I can display the articles in that table on a website as not "example.com/23323" but instead as "example.com/Funny_Thing_Happened_to_Me". This was straightforward enough to implement, and then as the number of articles grew, I added an index to the table on the url slugs.

I have since realized that while I want to be able to display capitalized letters in the urls, I want them to be case insensitive in terms of what the user types in, and I want to enforce uniqueness on the urls in a case insensitive manner.

Is there a straightforward way to quickly search based on a text column in a case insensitive way, and also enforce uniqueness in a case insensitive way?

I've tried conducting the searches with something like lower(url) = but that causes Postgres to decide not to use the index at all.


Use a functional index :

CREATE UNIQUE INDEX ix_test1 on articles (lower(url));

If you're on 8.4 and can install a contrib module, then also take a look at the citext type. It abstracts away all the lower/UPPER stuff and is slightly better performing.


SELECT * FROM sometable WHERE textfield ILIKE 'value%';

Is this what you are looking for? What do you mean by "enforce uniqueness in a case insensitive way"?

Or this if you want to stick to the "lower()":

SELECT * FROM sometable WHERE UPPER(textfield) LIKE (UPPER('value') || '%');
0

精彩评论

暂无评论...
验证码 换一张
取 消