MySQL GROUP BY Clause – Using Unique Index Instead of Column

group byindexMySQL

I have a table shift_wise_traffic with following columns.

toll        date            shift      car      truck      bus
 1          2016-09-01        1        10        20        30
 1          2016-09-01        2        15        25        35
 1          2016-09-01        3        20        30        40

 2          2016-09-01        1        5         10        15
 2          2016-09-01        2        20        25        30
 2          2016-09-01        3        35        40        50

 1          2016-09-02        1        10        20        30
 1          2016-09-02        2        10        20        30
 1          2016-09-02        3        10        20        30

 2          2016-09-02        1        10        20        30
 2          2016-09-02        2        10        20        30
 2          2016-09-02        3        10        20        30

Now I want to produce the output from shift_wise_traffic table group by
toll, date. And I have created a unique-index named shift_unique_index having two columns toll and date.

so instead of writing following query,

SELECT toll, date, SUM(car), SUM(truck), SUM(bus) FROM shift_wise_traffic 
GROUP BY toll, date;

Can I use this query using shift_unique_index,

SELECT toll, date, SUM(car), SUM(truck), SUM(bus) FROM shift_wise_traffic 
GROUP BY shift_unique_index;

Best Answer

SELECT toll, date, SUM(car), SUM(truck), SUM(bus)
    FROM shift_wise_traffic 
    GROUP BY toll, date;
  • The GROUP BY must have a list of columns, not an index name.
  • An INDEX is an optimization, not a requirement.
  • An INDEX may be useful for queries like this. (No index is likely to be useful for this particular query.)
  • Probably this query will simply scan the entire table, sort by toll+date, sum up the values, then deliver the output. (Or it may build an in-memory hash based on toll+date for summing.)
  • UNIQUE versus INDEX -- makes no difference in this context. UNIQUE = INDEX + a constraint. For INSERT, UNIQUE prevents duplicates.

It feels like your PRIMARY KEY is (date, shift, toll) in some order. Is it? If so, then changing the order to PRIMARY KEY(toll, date, shift) might make your GROUP BY run a little faster. (But it might slow down other operations.)