Group By in MySQL Queries - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Group By in MySQL Queries

Share This



In the previous books table, we have added one more attribute category to differentiate between Programming Languages and Theory Papers. The details of the books table are shown below:
table_book_modified



The values of the category attribute are Language and Theory. You may have many more categories according to the requirements.

Here, we want to find the number of books available in the library in each category. Based on our previous knowledge, it's difficult to find.

In this context, the solution is to count the books after grouping them according to the categories. Thus group by will be useful to do so.

Let us check the information available in the books table.
table_books_category_data



To count the number of books in each category, we can execute the following query:
table_books_category_count_group_by_category



Similarly, if you want to count the number of books according to the publishers, you may try the following SQL query.
table_books_category_count_group_by_publisher



You can also use order by along with group by as shown below.
table_books_category_count_group_by_publisher_order_by



Group By with Having

If you want to modify the above-mentioned query to fetch only those groups where the count is greater than 1, you can't use the where clause. In this case, you have to use having with the group by. The following example shows the result:
table_books_category_count_group_by_with_having



Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.