简介
函数索引就是给字段加了函数的索引,这里的函数也可以是表达式;所以也叫表达式索引。
使用场景
比如:如果某张表的数据量特别大,并且其中某个字段在当前数据库中保存大小写共存,当需要查询的时候忽略大小写,那么此时一般使用到的方法就是使用sql中的upper()
函数,但是使这时候应用upper()
函数后,sql语句是不会走索引的,建议为该字段创建一个函数索引,从而提高查询效率。
create table cust_info(
cust_no string primary key,
cust_name varchar(30) not null,
cust_card_no varchar(18),
cust_phoneno decimal(15),
cust_address varchar(30),
cust_ctime timestamp default now(),
index(cust_card_no)
);
insert
数据insert into cust_info values('SJDHADJu','王吉','12022519960321531X',15122511874,'天津武清','2021-02-02 00:00:00');
insert into cust_info values('HJSucjUN','张贺','431256197306265320',15534343555,'山西临汾','2021-03-02 00:00:00');
insert into cust_info values('AHAHuicn','刘明','371452199303034312',18967756743,'陕西延安','2021-04-02 00:00:00');
insert into cust_info values('AusdnACJ','李华','52112119860621421X',15833355455,'湖北武汉','2021-05-02 00:00:00');
insert into cust_info values('CCisuWEN','郑青','213456199102275341',13054546567,'江西南昌','2021-06-02 00:00:00');
create index on cust_info(upper(cust_no));
explain
select * from cust_info
where upper(cust_no)='CCISUWEN';
info
---------------------------------------------
distribution: local
vectorized: true
• index join
│ table: cust_info@cust_info_pkey
│
└── • scan
missing stats
table: cust_info@cust_info_expr_idx
spans: [/'CCISUWEN' - /'CCISUWEN']
(10 rows)
create table test1 (a date );
create index idx_funtochar on test1(to_char(create time));
explain select * from test1 where to_char(create_time)='2023-08-23';
info
-----------------------------------------------------------------------------------
distribution: local
vectorized: true
• index join
│ estimated row count: 0
│ table: test1@test1_pkey
│
└── • scan
estimated row count: 1 (99% of the table; stats collected 46 seconds ago)
table: test1@idx_funtochar
spans: [/'2023-08-23' - /'2023-08-23']
(11 rows)
其他场景还有不同函数,都可以按照此类此种方式去建立函数索引。