创建索引
可以创建一个 SQL 索引(其对应于底层的 SmartEDB 索引)来提高特定查询的查找性能。(有关使用索引进行性能优化的详细信息,请参阅 SQL 优化器。)使用 SQL 的 create index 语句创建索引,指定表和键字段。例如:
create table t (x integer);
create index tx on t(x);
这里在表 t 的列 x 上创建了一个 B 树(树)索引(默认类型)。 语法如下:
CREATE [UNIQUE] INDEX name ON table "(" key { "," key } ")"
[USING (HASH | RTREE | PTREE | TRIGRAM | INCLUSIVE)]
[IF NOT EXISTS]
key : column_name [ asc | desc ]
请注意,在 SmartESQL 中,所有 SQL 关键字均不区分大小写,即 CREATE INDEX 和 create index 是等效的。
关键字 HASH、RTREE、PTREE 和 TRIGRAM 分别指代 SmartEDB 中类型为哈希(哈希表)、R 树(空间搜索)、字典树(帕特里夏字典树)、三元组(三元组搜索)的索引。关键字 INCLUSIVE 表示该索引为键值包含索引。
一个关键的规范可以包含关键字 ASC 或 DESC,以表明索引是按升序还是降序排列。并且要注意,可以通过指定以逗号分隔的键列表来创建复合索引。
If Not Exists
If Not Exists子句可用于在索引已存在时覆盖错误。例如,请注意以下创建索引语句如何失败,而添加If Not Exists子句则可使执行成功:
XSQL>create table foo(x integer);
XSQL>insert into foo values (1);
XSQL>create index idx on foo(x);
XSQL>create index idx on foo(x);
ERROR: Compiler error at position 24: Index idx already defined for table foo
create index idx on foo(x)
^
XSQL>create index if not exists idx on foo(x);
XSQL>select * from foo;
x
------------------------------------------------------------------------------
1
Selected records: 1