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
| id | code | name | continent |
|---|---|---|---|
| 1 | KGZ | Kyrgyzstan | Asia |
| 2 | DNK | Denmark | Europe |
| 3 | LKA | Sri Lanka | Asia |
| 4 | SVN | Slovenia | Europe |
| 5 | YUG | Yugoslavia | Europe |
| 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
| continent |
|---|
| Asia |
| Europe |
| North America |
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
| ID | Name | Phone | |
|---|---|---|---|
| 1 | Bala Murugan | 9337055846 | Bala-Murugan1623@hotmail.com |
| 2 | Hari Krishnan | 9684448640 | Hari-Krishnan5531@yahoo.com |
| 3 | Hanumanthan | 9350414675 | Hanumanthan9008@yahoo.com |
| 4 | Sakunthala | 9292214983 | Sakunthala3772@hotmail.com |
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
| name | phone |
|---|---|
| Geetha | 9982436948 |
SQL Difference Between DISTINCT And GROUPBY Function
There are 5 main contrast in distinct vs groupby:-
| DISTINCT | GROUP BY |
|---|---|
| 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. |