Difference between order by and group by clause in SQL
1. Order By :
Order by keyword sort the result-set either in ascending or in descending order. This clause sorts the result-set in ascending order by default. In order to sort the result-set in descending order DESC keyword is used.
Order By Syntax –
SELECT column_1, column_2, column_3........... FROM Table_Name ORDER BY column_1, column_2, column_3....... ASC|DESC; Table_Name: Name of the table. ASC: keyword for ascending order DESC: keyword for descending order
2. Group By :
Group by statement is used to group the rows that have the same value. It is often used with aggregate functions for example:AVG(), MAX(), COUNT(), MIN() etc. One thing to remember about the group by clause is that the tuples are grouped based on the similarity between the attribute values of tuples.
Group By Syntax –
SELECT function_Name(column_1), column_2 FROM Table_Name WHERE condition GROUP BY column_1, column_2 ORDER BY column_1, column_2;
function_Name: Name of the aggregate function, for example:
SUM(), AVG(), COUNT() etc. Table_Name: Name of the table.
Let’s see the difference between Order by and group by clause:-
|S.NO||GROUP BY||ORDER BY|
|1.||Group by statement is used to group the rows that have the same value.||Whereas Order by statement sort the result-set either in ascending or in descending order.|
|2.||It may be allowed in CREATE VIEW statement.||While it does not use in CREATE VIEW statement.|
|3.||In select statement, it is always used before the order by keyword.||While in select statement, it is always used after the group by keyword.|
|4.||Attribute cannot be in the group by statement under aggregate function.||Whereas in order by statement, attribute can be under aggregate function.|
|5.||In group by clause, the tuples are grouped based on the similarity between the attribute values of tuples.||Whereas in order by clause, the result-set is sorted based on ascending or descending order.|
|6.||Group by controls the presentation of tuples(rows).||While order by clause controls the presentation of columns.|
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by GeeksforGeeks.