Skip to content

Filtered, function-based and shared indexes

View as Markdown

Besides ordinary indexes on columns, CoraDB supports three special kinds of index: filtered indexes that contain only some rows, function-based indexes on an expression, and shared indexes that cover a whole inheritance hierarchy. The general syntax of CREATE INDEX is described in CREATE INDEX.

A filtered (partial) index contains only the rows that satisfy a condition. It is smaller than a full index and suits queries that always look at the same small part of a table, such as open orders or unprocessed jobs.

CREATE INDEX index_name ON table_name (column [, column ...])
WHERE filter_condition;
ALTER INDEX index_name [ ON table_name (column [, column ...]) [ WHERE filter_condition ] ] REBUILD;
filter_condition ::= condition [ AND condition ... ]

In the e-commerce sample database, only 9 of the 2,910 orders have no shipped_date yet. An index on the unshipped orders contains just those 9 rows:

CREATE INDEX idx_orders_unshipped ON orders (order_date, customer_id) WHERE shipped_date IS NULL;

Using a filtered index. The optimizer uses a filtered index only when you name it in an index hint, and only for queries that contain the index's filter condition:

SELECT id, order_date
FROM orders USE INDEX (idx_orders_unshipped)
WHERE order_date >= DATE'2025-01-01' AND shipped_date IS NULL
ORDER BY order_date;

With the hint, SHOW TRACE shows that 9 index keys are read:

INDEX SCAN (orders.idx_orders_unshipped) (key range: (orders.order_date>= ?:0 ))
skip order by: true
...
SCAN (index: orders.idx_orders_unshipped), (btree time: 0, fetch: 11, ioread: 0, readkeys: 9, filteredkeys: 0, rows: 9) (lookup time: 0, rows: 9)

Without it, the optimizer uses the ordinary index on order_date, reads the 786 orders of 2025 and discards all but 9:

INDEX SCAN (orders.idx_orders_order_date) (key range: (orders.order_date>= ?:0 ))
...
SCAN (index: orders.idx_orders_order_date), (btree time: 0, fetch: 789, ioread: 0, readkeys: 320, filteredkeys: 0, rows: 786) (lookup time: 0, rows: 9)
  • With USE INDEX or USING INDEX idx, the filtered index is used only if the WHERE clause has a condition on its first column that can limit the index scan, as above.
  • With FORCE INDEX or USING INDEX idx(+), it is also used when another index column appears in the WHERE clause; the condition is then applied as a key filter. For example FORCE INDEX (idx_orders_unshipped) WHERE customer_id > 0 AND shipped_date IS NULL scans the 9 index entries.
  • If no column of the index appears in the WHERE clause, the filtered index is not used.
  • Only ordinary indexes can be filtered; CREATE UNIQUE INDEX … WHERE … is a syntax error.
  • At least one column of the index must be NOT NULL. CREATE INDEX … ON orders (shipped_date) WHERE … fails with Invalid filter expression (…) for index, because shipped_date is nullable.
  • Conditions can be combined only with AND: ' or ' is not allowed in a filter expression for index.
  • The condition cannot use functions whose result changes for the same input, such as SYS_DATE, SYS_DATETIME or RAND ('sys_date ' is not allowed in a filter expression for index); functions that change data, such as INCR and DECR; serial functions or pseudo-columns; aggregate functions such as MIN, MAX and STDDEV; operators and functions on SET values; or LOB functions such as CHAR_TO_CLOB and BIT_TO_BLOB.
  • IS NULL can be used only on a plain column, and not for every column of the index: WHERE a IS NULL is rejected for an index on (a, b), and WHERE (a + 1) IS NULL is rejected.
  • The filter condition can be at most 128 characters long (The maximum length of filter predicate string must be 128.).
  • A filtered index cannot be used for an index skip scan, and it cannot be function-based.
  • A filtered index on exactly the same columns as an existing index is rejected (Index "…" already defined); add a column, as in the example above.

A function-based index stores the result of a function of a column instead of the column value. It lets the optimizer use an index for conditions on that expression, for example case-insensitive searches or searches by year.

CREATE INDEX index_name ON table_name ( function_name ( arguments ) [, column ...] );
ALTER INDEX index_name [ ON table_name ( function_name ( arguments ) ) ] REBUILD;
CREATE INDEX idx_customer_lower_name ON customer (LOWER(company_name));
SELECT id, company_name FROM customer WHERE LOWER(company_name) = LOWER('JONES LLC');
INDEX SCAN (customer.idx_customer_lower_name) (key range: lower(customer.company_name)= lower('JONES LLC'))

The query returns customers 102 and 401, both named Jones LLC. Similarly, CREATE INDEX idx_orders_year ON orders (YEAR(order_date)) is used by WHERE YEAR(order_date) = 2023. SHOW INDEX shows the expression of a function-based index in its Func column.

The query must use the function exactly as in the index. The index above is not used for WHERE LOWER(CONCAT('Mr. ', company_name)) = 'mr. jones llc', which scans the whole table. Use USING INDEX to force an index when the optimizer does not choose it.

Restrictions

  • An index can contain only one function, and functions cannot be nested: (TRIM(LEFT(company_name, 3))) and (LOWER(company_name), UPPER(contact_name)) fail with Multiple or nested functions are not allowed in a function index definition. A function can be combined with plain columns, as in (LOWER(company_name), id).
  • The arguments of the function can only be columns and constants, but implicit type conversion is applied: LEFT(int_col, str_col) is accepted.
  • A function-based index cannot be filtered (Invalid index specification.).

Functions allowed in function-based indexes

ABS ACOS ADD_MONTHS ADDDATE ASIN
ATAN ATAN2 BIT_COUNT BIT_LENGTH CEIL
CHAR_LENGTH CHR COS COT DATE
DATE_ADD DATE_FORMAT DATE_SUB DATEDIFF DAY
DAYOFMONTH DAYOFWEEK DAYOFYEAR DEGREES EXP
FLOOR FORMAT FROM_DAYS FROM_UNIXTIME GREATEST
HOUR IFNULL INET_ATON INET_NTOA INSTR
LAST_DAY LEAST LEFT LN LOCATE
LOG LOG10 LOG2 LOWER LPAD
LTRIM MAKEDATE MAKETIME MD5 MID
MINUTE MOD MONTH MONTHS_BETWEEN NULLIF
NVL NVL2 OCTET_LENGTH POSITION POWER
QUARTER RADIANS REPEAT REPLACE REVERSE
RIGHT ROUND RPAD RTRIM SECOND
SECTOTIME SIN SQRT STR_TO_DATE STRCMP
SUBDATE SUBSTR SUBSTRING SUBSTRING_INDEX TAN
TIME TIME_FORMAT TIMEDIFF TIMESTAMP TIMETOSEC
TO_CHAR TO_DATE TO_DATETIME TO_DAYS TO_NUMBER
TO_TIME TO_TIMESTAMP TRANSLATE TRIM TRUNC
UNIX_TIMESTAMP UPPER WEEK WEEKDAY YEAR

A shared index is created on a table and applies to that table and all tables that inherit from it (UNDER), now and in the future. Like a unique index, and unlike an ordinary index, it uses one index structure for the whole hierarchy, so a query over the table and its subclasses (FROM ALL table) can use a single index.

CREATE SHARED INDEX index_name ON table_name (column [, column ...]);
CREATE TABLE party (party_id INT, name STRING, email STRING);
CREATE TABLE retail_customer UNDER party;
CREATE TABLE wholesale_customer UNDER party;
CREATE SHARED INDEX idx_party_email ON party (email);
INSERT INTO party VALUES (3, 'Head Office', 'office@example.com');
INSERT INTO retail_customer VALUES (1, 'Ana', 'ana@example.com');
  • The index appears on every table of the hierarchy: SHOW INDEXES FROM retail_customer lists idx_party_email with Shared = 1. Subclasses created later get it as well.

  • It works across several levels of inheritance.

  • It is used by queries on the table itself and on the whole hierarchy:

    SELECT party_id, name FROM party WHERE email = 'office@example.com'; -- 3, Head Office
    SELECT party_id, name FROM ALL party WHERE email = 'ana@example.com'; -- 1, Ana
    SELECT party_id, name FROM ALL party (EXCEPT wholesale_customer) WHERE email = 'ana@example.com';
  • It can be dropped only on the table where it was created; dropping it there removes it from all subclasses. DROP INDEX idx_party_email ON retail_customer fails with Illegal operation on "idx_party_email", inherited from class "party". Dropping the table also removes the index from its subclasses.