1
 >> table1
 -------------------------------------------------------------
 | column1 | column2 | column3 | column4 | column5 | column6 |
 +---------+---------+---------+---------+---------+---------+
 |  data1  |  data2  |  data3  |  data4  |  data5  |  data6  |
 +---------+---------+---------+---------+---------+---------+
 |  data7  |  data8  |  data9  |  data10 |  data11 |  data12 | 
 +---------+---------+---------+---------+---------+---------+
                               .
                               .
                               .
 +---------+---------+---------+---------+---------+---------+
 |  data   |  data   |  data   |  data   |  data   |  data   | 
 -------------------------------------------------------------

 >> query
 SELECT * FROM table1
     WHERE (column5 + column6) >= 6;


How do I create an index for this query in MySQL?

5
  • An index might not help this particular query because you are adding together the two columns. Commented Nov 16, 2017 at 4:10
  • in Postgresql it would be CREATE INDEX sumthing ON table1 (( column5 + column6 )); for mysql i don't know. Commented Nov 16, 2017 at 5:36
  • Oh, I forgot, the data types of columns 5 and 6 are int. Commented Nov 16, 2017 at 5:42
  • @Jasen thx, but your query is not work in mysql. Commented Nov 16, 2017 at 5:50
  • I don’t understand the relevance of the other columns Commented Nov 16, 2017 at 8:07

2 Answers 2

2

Newer versions of MySQL (5.7.6) (and MariaDB in 5.2 with VIRTUAL columns) have "Generated" columns. You would create such as (col5+col6), then index this fake column. Such a column can be STORED in the table our could be VIRTUAL. Read the docs to get the details.

col56 GENERATED ALWAYS AS (col5 + col6) VIRTUAL  -- or STORED
Sign up to request clarification or add additional context in comments.

1 Comment

I do not want to create a new column. But thanks for telling me the new way.
0

I don't believe you can create an index on the sum of two columns.

You could add an additional field that contains column5 + column6 and index on that.

You could create a view with an additional column equal to column5 + column6 and index on that.

4 Comments

Hi John, I agree with creating a computed column, but I'm not sure if it is possible to index a view in MySQL.
Yeah, you're right, no indexes on views, sorry for the bad advice.
@TimBiegeleisen Thanks for the advice. I think I should study harder.
@JohnBiddle I don't know why I can comment on only one person at once. Thank you for your kind answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.