7
I was making some queries, and came the need to carry out the grouping of a table that was in a JOIN within the query. To illustrate.
Sales chart.
+----+---------+------------+----------+
| Id | Cliente | Data | Vendedor |
+----+---------+------------+----------+
| 1 | 123 | 2018-03-20 | 12 |
| 2 | 456 | 2018-03-20 | 34 |
+----+---------+------------+----------+
Key (Id)
Items of sales:
+-------+---------+------------+----------------+
| Venda | Produto | Quantidade | Valor_Unitario |
+-------+---------+------------+----------------+
| 1 | 123 | 3 | 5,50 |
| 1 | 456 | 9 | 5 |
| 2 | 789 | 5 | 7,0 |
| 2 | 101 | 7 | 7,0 |
+-------+---------+------------+----------------+
Key (Sale, Product)
The query I was writing was a simple JOIN.
SELECT * FROM vendas v INNER JOIN vendas_itens vi ON vi.Venda = v.Id
However, at one point, I wanted to know how much each sale is worth and the order information. Determined to possess such information, I wrote the two queries below.
SELECT V.*,
SUM(Quantidade * Valor_Unitario) AS [Total]
FROM vendas v
LEFT JOIN vendas_itens vi
ON vi.Venda = v.Id
GROUP BY V.Id,
V.Cliente,
V.Data,
V.Vendedor
And
SELECT V.*,
(SELECT SUM(Quantidade * Valor_Unitario)
FROM vendas_itens vi
WHERE vi.Venda = v.Id ) AS [Total]
FROM vendas v
I checked the implementation plan for both consultations, but there was only one difference.
I would like to know the following:
-What is the difference in performance between the two consultations? Is there an advantage between one and the other (apart from the fact that the second one writes less)? - (I’m still junior)Which one is more "professional"? Or was it just a matter of taste?
I did some tests on a table with 15k records and saw no difference in performance.
Any improvement on the question, just comment, please.
EDIT1: As well remembered by José, the first query should be LEFT, because the subquery will not limit the scope of the first table. And as he asked, there are no indexes in the tables, only the keys.
Congratulations for worrying about analyzing the execution plan of each query. // The similarity in the two execution plans is due to the action of the SQL Server query optimizer. // To compare the 2 codes, I suggest you change the first code to LEFT JOIN. This is closer to the correlated subconsultation you used, which internally is transformed into OUTER JOIN. // I could add in the topic description which are the indexes of each table?
– José Diz
@Josédiz, ready, I made the change in the question. I thank the "disclosure" of this SQL Server query optimizer, I will look more about it.
– Márcio Eric