SQL DISTINCT Vs GROUP BY Statement
DISTINCT is a filter that separates unique records from those that meet the query requirements.
When you need to group data, the "
GROUP BY" clause is utilised.
it should be used to apply aggregate operators to each group.
Let's look at the distinction between DISTINCT and GROUP BY.
Because a DISTINCT and a GROUP BY normally yield the same query plan, the performance of both query techniques should be comparable.
SQL DISTINCT Statement
If you have a lookup table with multiple duplicate records, you can use the DISTINCT function to get unique results.
Example: Let's look at Country table and get unique value
|6||VIR||Virgin Islands, U.S.||North America|
Let's work above table in query
SELECT Distinct continent From Country;
In this query we get unique value from continent column in Country Table.
Output: To get unique data in continent coulmn will be
SQL GROUP BY Statement
When you wish to group your data based on some criteria or perform an aggregate function on grouped data, use GROUP BY .
Example: Let's look at Customer table and write query for get name and phone no
In below query we grouped data two column Name and Phone from Customer table
SELECT Name ,Phone FROM Customer WHERE id>3 GROUP BY Name,Phone;
Output: Will get output of grouped data is
SQL Difference Between DISTINCT And GROUPBY Function
There are 5 main contrast in distinct vs groupby:-
|DISTINCT is a filter that separates unique records from those that meet the query requirements.||GROUP BY is used when you want to group your data with some criteria or any aggregate function on grouped data.|
|If you have a result set with multiple duplicate records, you can use the DISTINCT function to retrieve unique results.||When you need to group data, the GROUP BY clause is employed, and it should be used to apply aggregate operators to each group.|
|GROUP BY cannot be replaced by DISTINCT.||In some cases, GROUP BY may replace DISTINCT.|
|Distinct is used to find records that are unique or distinct.||GROUP BY groups a set of rows into summary rows based on one or more columns or a phrase.|
|If all you want to do is get rid of duplicates, use DISTINCT.||To apply aggregate operators to each group, use GROUP BY.|