简体   繁体   中英

MariaDB virtual generated columns - use with indexes

since I'm fairly new to the concept of generated columns, I have a question about their use. I understand that it is supposed to help speed up queries performed on the table in cases when the db optimizer is unable to use table indexes due to a function used directly on the index (eg DATE(order_date), order_date is indexed).

In an attempt to speed up a query on my mariadb 10.5.16 db table, I have added a generated column:

ALTER TABLE orders ADD COLUMN month_order_date TINYINT GENERATED ALWAYS AS (month(order_date)) VIRTUAL;

and a couple of corresponding indexes like this one:

ALTER TABLE orders ADD INDEX generated_index_all (month_order_date,class,type);

It worked great, speeding up the query almost 10-fold. My question is this tho - is it enough to create said virtual column and any needed indexes once, or is it necessary to do it every once in a while?

After reading docs from Mariadb, the answer presented itself. They key (pun intended) thing here is to add the generated column as a persistent and not a virtual one. This is required if you want to use an index on it like I do. So, this is how you need to do it:

ALTER TABLE orders ADD COLUMN month_order_date TINYINT GENERATED ALWAYS AS (month(order_date)) PERSISTENT;

Obviously, remove and recreate the indexes after this. Finally, now when you EXPLAIN the query, it actually shows in the Extra column that it is "Using index condition" which is what we want and what wasn't the case before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM