'Distingish between 'GROUP BY' and ' ORDER BY'?

Hi Experts!

Can someone please clarify when to use ORDER BY and GROUP BY? I am confused about using them.

Here is a problem and answer. Like a blow query, I am confused by the operator:

Run Query: Show the number of orders placed by each customer (hint: this is found in the invoices table) and sort the result by the number of orders in descending order.

SELECT CustomerId, COUNT(InvoiceId)
AS total_items
FROM Invoices
GROUP BY CustomerId ORDER BY total_items DESC;

You use GROUP BY when you use an aggragate, like COUNT, SUM, MIN or MAX. For example, if you want to know the number or orders of a country, you will use GROUP BY Country instead of CustomerID.

You use ORDER BY to sort the results as you want. In this case they want to order by the second column total_items and the largest first (DESC).

Thank you for the response!

So, does it mean that when using ORDER BY, DESC ASC is a must to add in the query?

ORDER BY defaults to ASCending sort, you don't need to include it if that's the order you want. You must specify DESC if you want the largest/highest values to appear first.

1 Like

Thank you for the clarification!