Cláusula Where en uniones vs Cláusula Where en Subconsulta

DDL

create table t
(
    id int Identity(1,1),
    nam varchar(100)
)


create table t1
(
    id int Identity(1,1),
    nam varchar(100)
)

DML

Insert into t( nam)values( 'a')
Insert into t( nam)values( 'b')
Insert into t( nam)values( 'c')
Insert into t( nam)values( 'd')
Insert into t( nam)values( 'e')
Insert into t( nam)values( 'f')


Insert into t1( nam)values( 'aa')
Insert into t1( nam)values( 'bb')
Insert into t1( nam)values( 'cc')
Insert into t1( nam)values( 'dd')
Insert into t1( nam)values( 'ee')
Insert into t1( nam)values( 'ff')

Query - 1

Select t.*, t1.* From t t
Inner join t1 t1 on t.id = t1.id
Where t.id = 1

Query 1 SQL profiler Result

Reads => 56, Duration => 4

Query - 2

Select T1.*, K.* from 
(
    Select id, nam from t Where id = 1
)K
Inner Join t1 T1 on T1.id = K.id

Query 2 SQL Profiler Results

Reads => 262 and Duration => 2

También puedes ver mi SQlFiddle

Query - Which query should be used and why?

preguntado el 01 de julio de 12 a las 10:07

1 Respuestas

Optimizer generates same execution plans with same total cost for both of the queries. You can view the cost metric by checking the "Include Actual Execution Plan" option in SSMS and then viewing the "Estimated Subtree Cost" of the first element for each of the queries displayed in graphical execution plan. You can also compare time metric and IO reads metric by enabling them using SET STATISTICS TIME ON and SET STATISTICS IO ON. Perform test several times and take the best average result for comparison. If tests show equal performance I would take the query which is more readable and easier to maintain.

Respondido 01 Jul 12, 10:07

+1 for so many suggestion for a single question. My last query, which query is more appropriate to you? and why? - Pankaj

If performance would prove to be the same I would take query which would be more readable and easier to maintain. - Ivan Golovic

If you want an example of an improper query that would return same results as the above queries, try SELECT t.*, (SELECT t1.id FROM t1 WHERE t1.id = t.id) id, (SELECT t1.nam FROM t1 WHERE t1.id = t.id) nam FROM t WHERE t.id = 1 which generates more complicated query plan and has a bigger cost. - Ivan Golovic

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.