What's the difference between GROUP BY and ORDER BY?


#1

Question

What’s the difference between GROUP BY and ORDER BY?

Answer

The GROUP BY statement is used when we want to group the results of a query by one or more columns. It’s often used in conjunction with aggregate functions like COUNT, SUM, and AVG.

The ORDER BY statement is used when we want to sort the results of a query in either ascending or descending order.

Let’s take a look at an example to help us solidify our understanding. Suppose we have the following table called people:

image

Say we wanted to find out how many people have the same age for every age listed in the table. We can use the GROUP BY statement along with the aggregate function COUNT to do this:

SELECT age, COUNT(id) FROM people GROUP BY age;

Here’s what we get when we run that query:

image

As you can see, we get all of the ages in the table, and we get a count of how many people are that age. If we then wanted to sort this table by oldest to youngest, we would use the ORDER BY statement:

SELECT age, COUNT(id) FROM people GROUP BY age ORDER BY age DESC;

Here’s the final result:

image