Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a JOIN faster than a WHERE?

Suppose I have two tables that are linked (one has a foreign key to the other):

CREATE TABLE Document (   Id INT PRIMARY KEY,   Name VARCHAR 255 )  CREATE TABLE DocumentStats (   Id INT PRIMARY KEY,   DocumentId INT, -- this is a foreign key to table Document   NbViews INT ) 

I know, this is not the smartest way of doing things, but this is the best example I could come up with.

Now, I want to get all documents that have more than 500 views. The two solutions that come to my mind are:

SELECT * FROM Document, DocumentStats WHERE DocumentStats.Id = Document.Id   AND DocumentStats.NbViews > 500 

or:

SELECT * FROM Document INNER JOIN DocumentStats ON Document.Id = DocumentStats.Id WHERE DocumentStats.NbViews > 500 

Are both queries equivalent, or is there one way that is far better than the other? If so, why?

EDIT: as requested in the answers, this question was aimed at SQL Server, but I would be interested in knowing if it is different for other database engines (MySQL, etc...).

like image 940
Wookai Avatar asked Jul 15 '09 07:07

Wookai


People also ask

Is a join or WHERE clause faster?

A Subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. The subquery can be placed in the following SQL clauses they are WHERE clause, HAVING clause, FROM clause. Advantages Of Joins: The advantage of a join includes that it executes faster.

Is it better to use join or WHERE?

“Is there a performance difference between putting the JOIN conditions in the ON clause or the WHERE clause in MySQL?” No, there's no difference. The following queries are algebraically equivalent inside MySQL and will have the same execution plan.

WHERE exists faster than join?

In cases like above the Exists statement works faster than that of Joins. Exists will give you a single record and will save the time also. In case of joins the number of records will be more and all the records must be used.

Which is better inner join or WHERE clause?

If you want to use a JOIN other than an INNER JOIN stating it explicitly makes it clear what is going on. JOINing in the WHERE clause can be confusion since this is not it's typical purpose. It is most often used to filter the data.


1 Answers

Theoretically, no, it shouldn't be any faster. The query optimizer should be able to generate an identical execution plan. However, some database engines can produce better execution plans for one of them (not likely to happen for such a simple query but for complex enough ones). You should test both and see (on your database engine).

like image 83
mmx Avatar answered Sep 22 '22 08:09

mmx