GroupBy is used to aggregate data, while OrderBy is used to sort data. GroupBy returns the group, while OrderBy returns the sorted rows. GroupBy can contain aggregate functions, while OrderBy can contain regular columns.
The difference between GroupBy and OrderBy in SQL
GroupBy
<code class="sql">SELECT column_name(s) FROM table_name GROUP BY column_name</code>
OrderBy
<code class="sql">SELECT column_name(s) FROM table_name ORDER BY column_name [ASC | DESC]</code>
Difference
Example
Suppose there is a table named "Sales" that contains the following data:
Product | Sales |
---|---|
Apple | 100 |
Banana | 50 |
Apple | 75 |
Banana | 25 |
Orange | 120 |
##GroupBy Example:
<code class="sql">SELECT Product, SUM(Sales) AS TotalSales FROM Sales GROUP BY Product;</code>Result:
TotalSales | |
---|---|
175 | |
75 | |
120 |
OrderBy Example:
<code class="sql">SELECT * FROM Sales ORDER BY Sales DESC;</code>Results (sorted by sales volume in descending order):
Sales | |
---|---|
120 | |
100 | |
75 | |
50 | |
25 |
The above is the detailed content of The difference between groupby and orderby in sql. For more information, please follow other related articles on the PHP Chinese website!