Reputation: 4727
Today, I came across a query on W3Schools here : http://www.w3schools.com/sql/sql_view.asp which was written as below:
CREATE VIEW [Category Sales For 1997] AS
SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
I am wondering what's the purpose of using DISTINCT
in this query? The query has already GROUPed BY
the result set, so there is no chances of same CategoryName
after doing GROUP BY
and before doing SELECT
. Would this query behave differently if it did not use DISTINCT
? I mean what would happen if it was written simply as this:
CREATE VIEW [Category Sales For 1997] AS
SELECT CategoryName,Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName
Thank you!
Upvotes: 2
Views: 242
Reputation: 11783
As you correctly stated, GROUP BY already returns distinct values for the group-by-columns. As that one column is included in the select column list in your example, the DISTINCT does not provide any additional functionality.
Depending on the query (probably not in this case) an unnecessary DISTINCT can however hurt performance badly, so it is always a good idea to check if the DISTINCT is really necessary in any queries.
Upvotes: 2
Reputation: 171411
You can remove it. It's redundant and has no effect on the output.
Upvotes: 3