Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subquery VS join with respect to performance

Tags:

sql

Which is better in performance [Subquery] or [join]?

I have 3 tables related to each other, and i need to select data from one table that has some fields related to the other 2 tables, which one from the following 2 SQL statements is better from the view of performance :

select Table1.City, Table1.State, Table2.Name, Table1.Code, Table3.ClassName 
from Table1 inner join Table2 on Table1.EmpId = Table2.Id inner join Table3
on Table1.ClassId = Table3.Id where Table.Active = 1

OR

select City, State, (select Name from Table2 where Id = Table1.EmpId) as Name, Code,
(select ClassName from Table3 where Id = Table1.ClassId) as ClassName from Table1
where Active = 1

I have tried the execution plan but its statistics is not expressive to me because the current data is a test data not real one, so i can't imagine the amount of data when tables are live of course they will be more than the test one.

Note : The Id field in Table2 and Table3 is primary key

Thanks in advance

like image 265
Ahmy Avatar asked Feb 18 '26 11:02

Ahmy


1 Answers

The first approach, with joins, is by far faster. In second the query will be executed for each row. Some databases optimize nested queries into joins though.

Join vs. sub-query

like image 96
Ilya Saunkin Avatar answered Feb 21 '26 15:02

Ilya Saunkin