0

Possible Duplicate:
When and why are database joins expensive?

My company has assigned me a job of improving DB performance. Earlier developer has written a query having 5 innerjoins.

What is the number of inner joins which can be used without hurting performance ?

Community
  • 1
  • 1
pokrate
  • 3,954
  • 7
  • 30
  • 36
  • 3
    The post I linked to has a comprehensive discussion of joins - in general though, 5 innerjoins using good indexes is not a problem. It really comes down to the old story, when concerned about performance, benchmark to see if there is actually a problem in what you are trying to tune. – David Hall Jul 04 '11 at 17:44

1 Answers1

7

JOINs can perform better than alternatives, in specific situations. And it's not unusual to see that many joins in a normalized database.

JOINs aren't always necessary -- if there aren't references outside of the JOIN for the table, EXISTS or IN will perform better. For example:

SELECT a.column
  FROM TABLE_A a 
  JOIN TABLE_B b ON b.col = a.col

...vs:

SELECT a.column
  FROM TABLE_A a 
 WHERE EXISTS(SELECT NULL 
                FROM TABLE_B b 
               WHERE b.col = a.col)

If the joins are necessary for the resultset, then assess the situation:

  • Are there indexes on the foreign keys (the columns used to for the JOIN criteria)?
  • Are any of the join criteria requiring functions for JOINs to work. IE:

    JOIN table x ON DATE(x.col) = y.column
    

    ...because such cases would render an index on x.col useless

  • Is the data type of the foreign keys as narrow as possible, because the less bytes used to store the value means faster database performance. IE: VARCHAR(4) vs INT

Conclusion

It's plausible that denormalizing data can be a performance benefit but it's the very last option to consider after lots of review & testing.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
  • It's quite easy to demonstrate then IN/EXISTS is better then JOINs if you don't need data from one of the tables. What makes you say this? – gbn Jul 04 '11 at 19:04
  • done. Your old first line let down the rest ;-) Quassnoi did a lot on it eg http://explainextended.com/2009/09/30/in-vs-join-vs-exists-oracle/ – gbn Jul 04 '11 at 19:15
  • @gbn: I need an editor =) I have all of them bookmarked - Oracle, MySQL (nullable & not), PostgreSQL, and SQL Server :) – OMG Ponies Jul 04 '11 at 19:19