Group by VS Distinct
Group By : The SQL GROUP BY statement is used together with the SQL aggregate functions to group the retrieved data by one or more columns.
Distinct : The DISTINCT keyword can be used to return only distinct (different) values.
Orders table :
| OrderId | PersonName | Price | Quantity |
| 101 | John | 12 | 1 |
| 102 | Sam | 4 | 1 |
| 103 | John | 14 | 2 |
| 104 | Brendon | 12 | 1 |
| 106 | Allen | 2 | 11 |
| 107 | Allen | 3 | 11 |
Query 1: Select PersonName,Price from Orders group by PersonName,Price
Query 2:Select distinct PersonName,Price from Orders
Execution plan for both queries are same and return 5 records.
But the purpose of Group by is different it is used to group the records and apply aggregate function on it.
Query 3: Select PersonName,Sum(Price) as ‘Total’ from Orders group by PersonName
Query 3 returns only for records like below
| PersonName | Total |
| Allen | 5 |
| Brendon | 12 |
| John | 26 |
| Sam | 4 |