learnsql.com/blog/sql-group-by-vs-order-by/
1 Users
0 Comments
10 Highlights
0 Notes
Tags
Top Highlights
The default order for a SELECT statement is non-deterministic, which means the order of results can differ anytime you run your code.
The default order of ORDER BY command is ascending order. So, if you didn't use ASC or DESC, results will come in ascending order.
You can use ORDER BY in two or more columns. Check the following query:
This query first orders results in the ascending order of the state, followed by the descending order of the city.
GROUP BY is not a way to display data in groups, but it is more of a way to analyze data in groups.
In most texts, GROUP BY is defined as a way of aggregating records by the specified columns which allow you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).
So, let's see what has happened here. This query has returned one result from each style value. That means SQL first makes groups from the same style values and returns one row representing the group. And what is the exact use of GROUP BY? Of course, you can use GROUP BY to find distinct values. But SQL has a DISTINCT keyword specifically for that. The real importance of GROUP BY can be seen when you use it with aggregate functions like SUM(), COUNT(). To understand it better, execute the following SQL query:
Here, SQL first groups results based on the style column. Then, it checks how many names are there in each group and returns the style values and the count of names for each style.
In actuality, there is no guarantee that GROUP BY will display results in ascending order. If you need results in a specific order, you have to do it yourself like below:
There is no real use of GROUP BY without aggregation functions.
Glasp is a social web highlighter that people can highlight and organize quotes and thoughts from the web, and access other like-minded people’s learning.