Say I'm running MySQL 8 with a table data
containing about 1M rows. And I want to filter a datetime
column on date
a range (using a date index).
CREATE TABLE `data` (
`rowId` int NOT NULL AUTO_INCREMENT,
`data` json NOT NULL,
`created` DATETIME NOT NULL, -- <-- datetime column for a date index
`created_date` DATE AS (cast(`created` as date)) NOT NULL, -- <-- generated date column
PRIMARY KEY (`rowId`),
INDEX (`created`), -- <-- datetime index w/ cardinality ~ 1M
INDEX (`created_date`) -- <-- date index w/ cardinality of 1250
INDEX `created_cast` ((cast(`created` as date))) -- <-- functional "date" index w/ cardinality of 1250
-- ^ I WANT TO USE THIS INDEX, BUT DON'T KNOW HOW
) ENGINE=InnoDB;
Then let's filter rows only from 2018, let's say:
SELECT COUNT(*) FROM data
WHERE created >= CAST('2018-01-01' AS DATE) AND created < CAST('2019-01-01' AS DATE);
-- Query time: 0.16 s
-- EXPLAIN shows: key: created, Using where; Using index
-- Uses the whole datetime index w/ cardinality of ~ 1M
SELECT COUNT(*) FROM data
WHERE created_date BETWEEN CAST('2018-01-01' AS DATE) AND CAST('2018-12-31' AS DATE);
-- Query time: 0.09 s
-- EXPLAIN shows: key: created_date, Using where; Using index
-- Uses the date index w/ cardinality of 1250
SELECT COUNT(*) FROM data
WHERE CAST(created AS DATE) BETWEEN CAST('2018-01-01' AS DATE) AND CAST('2018-12-31' AS DATE);
-- Query time: 0.35 s, that's slow!
-- EXPLAIN shows: key: NULL, Using where
-- Doesn't use any index at all!
Is there a way to use this functional index?
The queries above use either created
(datetime) or created_date
(date from generated column) indexes.
Is there a way to use functional index created_cast
directly? I've even tried with USE INDEX
or FORCE INDEX
, but no luck.
Thank you all :)
I would rewrite your queries and remove the
CAST
and use the he generated column, as you have no conversion in it, but it needs space.db<>fiddle here