Oracle sql区分大小写索引

时间:2018-02-12 15:13:19

标签: sql oracle oracle11g query-hints

在我的项目数据库中显示产品表,其中一列名为' Name' 因此,此表格可以包含'产品A'和'产品a' 应该在简单的选择查询中选择这两种产品。

我创建了索引: CREATE INDEX IDX_PRODUCT_NAME ON PRODUCTS(NAME)

然后运行SQL查询: SELECT /*+ INDEX(PRODUCTS IDX_PRODUCT_NAME)*/ * FROM PRODUCTS WHERE NAME='Product_a'

我做错了什么?

P.S。我知道有关更改会话标志的变体: NLS_COMP=ANSI; NLS_SORT=BINARY_CI; 但对于我有趣的变体没有更改数据库设置,它可能吗?或者例如仅为我的查询更改此标志。

请看一下图片

更新 William Robertson 帮我评论。 CREATE INDEX IDX_PRODUCT_NAME ON PRODUCTS(UPPER(NAME))

之后运行查询: SELECT * FROM PRODUCTS WHERE **UPPER**(NAME)='PRODUCT_A' 这个变种工作正常!

1 个答案:

答案 0 :(得分:1)

一种方法是添加虚拟列:

create table demo_products
( id          integer not null
, name        varchar2(20)
, name_upper  generated always as (upper(name)) );

create index demo_prod_upper_name_ix on demo_products(name_upper);

insert all
    into demo_products (id, name) values (1, 'Prod A')
    into demo_products (id, name) values (2, 'Prod a')
    into demo_products (id, name) values (3, 'Prod B')
    into demo_products (id, name) values (4, 'Prod b')
    into demo_products (id, name) values (5, 'prod A')
    into demo_products (id, name) values (6, 'Cheese')
    into demo_products (id, name) values (7, 'Bananas')
select * from dual;

commit;

select count(*) from demo_products where name_upper = 'PROD A';

  COUNT(*)
----------
         3

Plan hash value: 4158816492

---------------------------------------------------------------------------------------------
| Id  | Operation         | Name                    | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |                         |     1 |    12 |     1   (0)| 00:00:01 |
|   1 |  SORT AGGREGATE   |                         |     1 |    12 |            |          |
|*  2 |   INDEX RANGE SCAN| DEMO_PROD_UPPER_NAME_IX |     1 |    12 |     1   (0)| 00:00:01 |
---------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   2 - access("NAME_UPPER"='PROD A')