RGO
RGO

Reputation: 4727

What's the purpose of distinct in this query?

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

Answers (2)

Sebastian Meine
Sebastian Meine

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

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171411

You can remove it. It's redundant and has no effect on the output.

Upvotes: 3

Related Questions