Home >Database >SQL >The difference between groupby and orderby in sql

The difference between groupby and orderby in sql

下次还敢
下次还敢Original
2024-04-29 14:57:15763browse

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

The difference between GroupBy and OrderBy in SQL

GroupBy

  • Combine rows with the same value into a grouping
  • Purpose: To summarize or aggregate data
  • Syntax:
<code class="sql">SELECT column_name(s)
FROM table_name
GROUP BY column_name</code>

OrderBy

  • Sort the result set by the value of the specified column
  • Purpose:Organize and display Data
  • Syntax:
<code class="sql">SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC | DESC]</code>

Difference

  • Usage: GroupBy Used to aggregate data, while OrderBy is used to sort data.
  • Result set: GroupBy returns groups, while OrderBy returns sorted rows.
  • Columns: GroupBy can contain aggregate functions, while OrderBy can contain regular columns.

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:

ProductTotalSalesApple175Banana75Orange120

OrderBy Example:

<code class="sql">SELECT * FROM Sales
ORDER BY Sales DESC;</code>
Results (sorted by sales volume in descending order):

##ProductOrangeAppleAppleBananaBanana
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Usage of group by in sqlNext article:Usage of group by in sql

Related articles

See more