Difference between ORDER BY and GROUP BY clause in MySQL

Learn about the ORDER BY and GROUP BY clauses, what are the differences between them?
Submitted by Apurva Mathur, on November 11, 2022

GROUP BY Clause

As the name suggests, the GROUP BY clause is used to group identical data into one set. This clause is always used with SELECT statements, and MySQL functions like (COUNT(), SUM(), etc). When we want to group some columns than in such cases, we use this clause.

Syntax:

SELECT column_1, aggregate_function (column_2)
FROM table_name
WHERE condition
GROUP BY column_1, column_2;

Example:

Suppose I have a table named "marks: and inside this table, I have the following columns:

MySQL | ORDER BY Vs. GROUP BY (1)

Let's see how we can use group by clause to group the students based on their status.

For this, we will write,

SELECT count(SID) AS Students, status
FROM marks
GROUP BY status;

The above query will display the following result,

MySQL | ORDER BY Vs. GROUP BY (2)

ORBER BY Clause

The ORDER BY clause is used when you want to sort your result in a specific order. It gives the result in ascending or descending order. To sort the result in ascending order ASC is used while to sort the result in descending order DESC is used. By default, the result is always displayed in ascending order.

Syntax:

SELECT Column_name
FROM table_name
ORDER BY column_name ASC|DESC;

Example:

Suppose I want to sort the names present in the table given above then in such I can write my query as,

SELECT * FROM marks
ORDER BY Sname ASC;

The above query will sort the names in ascending order,

MySQL | ORDER BY Vs. GROUP BY (3)

Overview Differences (ORDER BY Vs. GROUP BY)

GROUP BY ORDER BY
GROUP BY clause is used to group identical data into one set. The ORDER BY clause is used when you want to sort your result in a specific order.
GROUP BY must be used with the aggregate function. It is not important to use ORDER BY clause with aggregate functions.
In GROUP BY clause, rows are presented in a certain way. Whereas, it determines how columns are displayed.
The keyword GROUP BY is always placed before the keyword ORDER BY. Whereas here, ORDER BY keyword is always placed after the GROUP BY keyword.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.