Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index on SUM function in MYSQL

Tags:

sql

mysql

I have a query in MYSQL like this (simplified) :

SELECT col1, SUM(DISTINCT col2) AS S
FROM tbl1
WHERE col1='abbc'
GROUP BY col1
ORDER BY S ASC

I know that an index on col1 would be useful for that kind of query. I would like to know if a covering index on (col1, col2) would be more usefull or if it doesnt make any difference.

like image 390
user24533435 Avatar asked May 19 '18 17:05

user24533435


People also ask

What is ADD index in MySQL?

In MySQL, an index can be created on a table when the table is created with CREATE TABLE command. Otherwise, CREATE INDEX enables to add indexes to existing tables. A multiple-column index can be created using multiple columns. The indexes are formed by concatenating the values of the given columns.

How do I index a MySQL query?

The statement to create index in MySQL is as follows: CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name USING [BTREE | HASH | RTREE] ON table_name (column_name [(length)] [ASC | DESC],…) In above statement UNIQUE specify that MySQL will create a constraint that all values in the index must be distinct.

What is functional index in MySQL?

Starting from version 8.0. 13, MySQL supports functional indexes. Instead of indexing a simple column, you can create the index on the result of any function applied to a column or multiple columns.


1 Answers

i try it , it seems different and more usefull


Index Version Execution Plan :

without distinct

SELECT col1, SUM(col2) AS S
FROM tbl1
WHERE col1='abbc'
GROUP BY col1
ORDER BY S ASC;

distinct

SELECT col1, SUM(distinct col2) AS S
FROM tbl1
WHERE col1='abbc'
GROUP BY col1
ORDER BY S ASC;

SQL Fiddle


without Index Version Execution Plan :

it's no different

SQL Fiddle

like image 91
Wei Lin Avatar answered Oct 22 '22 12:10

Wei Lin