40

In several SO posts OP asked for an efficient way to search text columns in a case insensitive manner.

As much as I could understand the most efficient way is to have a database with a case insensitive collation. In my case I am creating the database from scratch, so I have the perfect control on the DB collation. The only problem is that I have no idea how to define it and could not find any example of it.

Please, show me how to create a database with case insensitive collation.

I am using postgresql 9.2.4.

EDIT 1

The CITEXT extension is a good solution. However, it has some limitations, as explained in the documentation. I will certainly use it, if no better way exists.

I would like to emphasize, that I wish ALL the string operations to be case insensitive. Using CITEXT for every TEXT field is one way. However, using a case insensitive collation would be the best, if at all possible.

Now https://stackoverflow.com/users/562459/mike-sherrill-catcall says that PostgreSQL uses whatever collations the underlying system exposes. I do not mind making the OS expose a case insensitive collation. The only problem I have no idea how to do it.

4

5 回答 5

28

自从这个问题以来,发生了很多变化。PostgreSQL v12 中添加了对不区分大小写排序规则的原生支持。citext如其他答案中所述,这基本上不推荐使用扩展名。

在 PostgreSQL v12 中,可以执行以下操作:

    CREATE COLLATION case_insensitive (
      provider = icu,
      locale = 'und-u-ks-level2',
      deterministic = false
    );

    CREATE TABLE names(
      first_name text,
      last_name text
    );

    insert into names values
      ('Anton','Egger'),
      ('Berta','egger'),
      ('Conrad','Egger');

    select * from names
      order by
        last_name collate case_insensitive,
        first_name collate case_insensitive;

有关更多信息,请参阅https://www.postgresql.org/docs/current/collat​​ion.html 。

于 2019-11-29T08:54:24.630 回答
10

没有不区分大小写的排序规则,但有 citext 扩展名:

http://www.postgresql.org/docs/current/static/citext.html

于 2013-09-15T21:48:21.987 回答
8

出于我的目的,ILIKE 关键字完成了这项工作。

来自postgres 文档

根据活动区域设置,可以使用关键字 ILIKE 代替 LIKE 以使匹配不区分大小写。这不在 SQL 标准中,而是 PostgreSQL 扩展。

于 2014-02-17T13:05:29.573 回答
1

这不会改变排序规则,但也许有人帮助我使用函数的这种类型的查询lower

SELECT id, full_name, email FROM nurses WHERE(lower(full_name) LIKE '%bar%' OR lower(email) LIKE '%bar%')

于 2016-08-31T04:56:54.147 回答
-2

我相信您需要initdb在创建数据库集群时将排序规则指定为命令行选项。就像是

initdb --lc-collate=en_US.UTF-8 

似乎在 Ubuntu 和 Mac OS X 上使用 PostgreSQL 9.3initdb会自动使用当前操作系统区域设置中默认的不区分大小写的排序规则创建数据库集群,在我的例子中是en_US.UTF-8.

您是否可以使用不默认为主机区域设置的旧版 PostgreSQL?或者可能是您使用的操作系统不提供任何不区分大小写的排序规则供 PostgreSQL 选择?

于 2013-11-30T19:31:47.787 回答