Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to joins to increase performance?

Is there an alternative to joins to increase performance?

Edit (gbn): related to join-or-correlated-subquery-with-exists-clause-which-one-is-better


Why didn't anyone mention about nested loop joins?

like image 334
hrishi Avatar asked Jul 24 '10 06:07

hrishi


People also ask

What can be used instead of joins in SQL?

Subqueries allow you to use the results of another query in the outer query. In some cases, subqueries can replace complex joins and unions.

What can I use instead of an inner join?

In SQL, a join is used to compare and combine — literally join — and return specific rows of data from two or more tables in a database. An inner join finds and returns matching data from tables, while an outer join finds and returns matching data and some dissimilar data from tables.

Do joins affect performance?

Even though the join order has no impact on the final result, it still affects performance. The optimizer will therefore evaluate all possible join order permutations and select the best one. That means that just optimizing a complex statement might become a performance problem.

Does join improve performance?

Basically, join order DOES matter because if we can join two tables that will reduce the number of rows needed to be processed by subsequent steps, then our performance will improve.


2 Answers

Not an "alternate" way to JOINs, but a tip to increase JOIN performance: in SQL Server that a lot of folks don't know is that you should always put a non-clustered index on a foreign key column. Several folks believe SQL Server does this automatically - it does not.

So if you have a table Customer, it probably has a primary key something like CustomerID. SQL Server will put an index on that automatically.

However, if you have a table Order that has a foreign key relationship with Customer, there is by default no index on the column Order.CustomerID. But such an index is very useful and helpful for joins and lookups, so that's a best practice I always recommend: put an index on all your foreign key columns in a table.

like image 150
marc_s Avatar answered Oct 03 '22 22:10

marc_s


From your other question

select * 
from ContactInformation c 
where exists (select * from Department d where d.Id = c.DepartmentId )

select * 
from ContactInformation c 
inner join Department d on c.DepartmentId = d.Id  

If you want output from both tables, then you have option other then JOIN. The 2nd query here.

If it's slow, then generally:

  • you have primary key/indexes?
  • consistent datatypes (the DepartmentId/id columns)
  • don't use SELECT *
like image 30
gbn Avatar answered Oct 03 '22 21:10

gbn