views:

77

answers:

4

I have a MySQL table with 3 fields:

  • Location
  • Variable
  • Value

I frequently use the following query:

SELECT * 
  FROM Table 
 WHERE Location = '$Location' 
   AND Variable = '$Variable' 
ORDER BY Location, Variable

I have over a million rows in my table and queries are somewhat slow. Would it increase query speed if I added a field VariableLocation, which is the Variable and the Location combined? I would be able to change the query to:

SELECT * 
  FROM Table 
 WHERE VariableLocation = '$Location$Variable' 
ORDER BY VariableLocation
A: 

You are right, this time around, mysql will be dealing with one field rather than two which will definitely increase performance.

You may also consider adding index to your fields.

Sarfraz
-1 - can you explain why this would happen in terms of how MySQL manages data or optimizes queries?
kdgregory
no i can't explain to you at least because i can't vote you down initially like you have done !!!
Sarfraz
If you can't explain something in terms of known behavior, then you're not giving a real answer. You have no basis on which to say "will definitely increase performance," because you don't know why it would do so. As it is, you told the OP exactly what s/he wanted to hear, which at best is spreading harmless superstition, at worst will make his/her queries perform more poorly. Compare that to the other posters, who actually gave reasoned explanations for adding an index.
kdgregory
@kdgregory my experience tell me this, when you perform a benchmark, you come up with results. thanks
Sarfraz
+2  A: 

Try adding an index which covers the two fields you should then still get a performance boost but also keep your data understandable because it wouldn't seem like the two columns should be combine but you are just doing it to get performance.

Jeff Beck
+5  A: 

I would add a covering index, for columns location and variable:

ALTER TABLE 
  ADD INDEX (variable, location);

...though if the variable & location pairs are unique, they should be the primary key.

Combining the columns will likely cause more grief than it's worth. For example, if you need to pull out records by location or variable only, you'd have to substring the values in a subquery.

OMG Ponies
+1  A: 

I would advise against combining the fields. Instead, create an index that covers both fields in the same order as your ORDER BY clause:

ALTER TABLE tablename ADD INDEX (location, variable);

Combined indices and keys are only used in queries that involve all fields of the index or a subset of these fields read from left to right. Or in other words: If you use location in a WHERE condition, this index would be used, but ordering by variable would not use the index.

When trying to optimize queries, the EXPLAIN command is quite helpful: EXPLAIN in mysql docs

kread