开发者

Optimize Select Query Based on Multiple WHERE Conditions

I'm currently a junior developer working on a web application with a Java/DB2 backend and I have some SQL queries that run quite slowly. The database right now is not optimized so there's definitely room for improvement. Only problem is that I have no experience with this and no one can help me.

SomeTableName
MyPkey
ColOne
ColTwo
ColThree
ColFour
ColFive

I was trying to figure out how to optimize the database for queries like these:

SELECT * FROM SomeTableName WHERE ColOne = 'some value'
SELECT * FROM SomeTableName WHERE ColOne = 'some value' AND ColTwo = 'another'
SELECT * FROM SomeTableName WHERE ColFive = 11 AND ColThree = 'hello world'
SELECT * FROM SomeTableName WHERE ColOne = 'hi' AND ColTwo = 'val1' AND ColThree = 'val2' AND ColFour = 'val3' AND ColFive = 'val4'

What I'm trying to portray is, the SEL开发者_运维问答ECT statements have WHERE conditions that have different column combinations and values and I'm not sure how to optimize queries like this.

Any advice?

EDIT: I'm not sure if DB2 adds its own optimizations but for sure there are NO indices setup on any of the columns.


You should definitely play with indexes on your database. They make insertion and update more expensive, but your queries will run much faster, so they're probably a big win overall. Indexes are most effective for columns that have large numbers of values (ie, not so much for a gender column). They're more effective for columns you reference a lot in your where conditions. As you try out indexes, be sure to see if your database's query optimizer is leveraging them, using the SQL EXPLAIN verb or a tool like db2expln.


From your example, it looks like you'll already gain some performance just by indexing colOne. Basically, use the columns in the same order as the index you want to use.


You would get a decent performance gain by creating an index on ( colOne, colTwo, colThree, colFour, colFive ). Queries 1, 2 and 4 will all use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜