I have table banners
with following column
column | type | index |
---|---|---|
id | BIGINT | primary |
start_date | DATETIME | key |
end_date | DATETIME NULLABLE | key |
Executing this query gives me result
EXPLAIN SELECT * FROM banners WHERE end_date IS NULL;
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | banners | (NULL) | ref | banners_end_date_index | banners_end_date_index | 6 | const | 2 | 100.00 | Using index condition |
However, this query gives me result
EXPLAIN SELECT * FROM banners WHERE end_date > '2022-04-26';
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | banners | (NULL) | ALL | banners_end_date_index | (NULL) | (NULL) | (NULL) | 9,980 | 50.00 | Using where |
So does that mean the 2nd query is ignoring the index and doing full table scan?
If the index is being ignored, what query should I use instead to use the index?
Also, I read that OR statement is also ignoring index. Is it always true, or are there exception for index and OR to work together?
Edit:
As pointed out by Bill Karwin in the comment, if most of the data match the condition, it will skip the index. So, I tried again with end_date so far in the future, and here's the EXPLAIN result. Column key and key_len are not NULL, which mean the index is indeed being used.
EXPLAIN SELECT * FROM banners WHERE end_date > DATE('2022-07-20');
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
---|---|---|---|---|---|---|---|---|---|---|---|
1 | SIMPLE | banners | (NULL) | ALL | banners_end_date_index | banners_end_date_index | 6 | (NULL) | 74 | 100.00 | Using index condition |