Order By & Group By In [SQL] Tutorial Learning Path - Complete Guide
Order By and Group By in SQL Tutorial

Order By & Group By In [SQL] Tutorial Learning Path – Complete Guide

Last updated on 08th Jul 2020, Blog, Tutorials

About author

Vikas Aswal (Senior Sql Database Administrator )

Vikas Aswal is a Senior SQL Database Administrator who has more than 6 years of experience in SQL Databases. and is also an expert in DataStage, Hadoop, Microsoft Power BI, MicroStrategy, OBIEE, and Cognos.

(5.0) | 19677 Ratings 1561

SQL

  • SQL is a database computer language designed for the retrieval and management of data in a relational database. SQL stands for Structured Query Language. This tutorial will give you a quick start to SQL. It covers most of the topics required for a basic understanding of SQL and to get a feel of how it works.
  • SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a relational database.

Also, they are using different dialects, such as −

  • MS SQL Server using T-SQL,
  • Oracle using PL/SQL,
  • MS Access version of SQL is called JET SQL (native format) etc.

Why to Learn SQL?

  • SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving data stored in a relational database.
  • SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.

Also, they are using different dialects, such as −

  • MS SQL Server using T-SQL,
  • Oracle using PL/SQL,
  • MS Access version of SQL is called JET SQL (native format) etc.

Why SQL?

SQL is widely popular because it offers the following advantages −

  • Allows users to access data in the relational database management systems.
  • Allows users to describe the data.
  • Allows users to define the data in a database and manipulate that data.
  • Allows to embed within other languages using SQL modules, libraries & pre-compilers.
  • Allows users to create and drop databases and tables.
  • Allows users to create view, stored procedure, functions in a database.
  • Allows users to set permissions on tables, procedures and views.

Applications of SQL

As mentioned before, SQL is one of the most widely used query language over the databases. I’m going to list few of them here:

  • Allows users to access data in the relational database management systems.
  • Allows users to describe the data.
  • Allows users to define the data in a database and manipulate that data.
  • Allows to embed within other languages using SQL modules, libraries & pre-compilers.
  • Allows users to create and drop databases and tables.
  • Allows users to create view, stored procedure, functions in a database.
  • Allows users to set permissions on tables, procedures and views.

    Subscribe For Free Demo

    [custom_views_post_title]

    ORDER BY

    The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.

    Syntax

    • The basic syntax of the ORDER BY clause is as follows −
    • SELECT column-list 
    • FROM table_name 
    • [WHERE condition] 
    • [ORDER BY column1, column2, .. columnN] [ASC | DESC];

    You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.

    Example

    • Consider the CUSTOMERS table having the following records −
    • +—-+———-+—–+———–+———-+
    • | ID | NAME     | AGE | ADDRESS   | SALARY   |
    • +—-+———-+—–+———–+———-+
    • |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    • |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    • |  3 | kaushik  |  23 | Kota      |  2000.00 |
    • |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    • |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    • |  6 | Komal    |  22 | MP        |  4500.00 |
    • |  7 | Muffy    |  24 | Indore    | 10000.00 |
    • +—-+———-+—–+———–+———-+

    The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY −

    • SQL> SELECT * FROM CUSTOMERS
    •    ORDER BY NAME, SALARY;
    • This would produce the following result −
    • +—-+———-+—–+———–+———-+
    • | ID | NAME     | AGE | ADDRESS   | SALARY   |
    • +—-+———-+—–+———–+———-+
    • |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    • |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    • |  3 | kaushik  |  23 | Kota      |  2000.00 |
    • |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    • |  6 | Komal    |  22 | MP        |  4500.00 |
    • |  7 | Muffy    |  24 | Indore    | 10000.00 |
    • |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    • +—-+———-+—–+———–+———-+

    The following code block has an example, which would sort the result in the descending order by NAME.

    • SQL> SELECT * FROM CUSTOMERS
    •    ORDER BY NAME DESC;
    • This would produce the following result −
    • +—-+———-+—–+———–+———-+
    • | ID | NAME     | AGE | ADDRESS   | SALARY   |
    • +—-+———-+—–+———–+———-+
    • |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    • |  7 | Muffy    |  24 | Indore    | 10000.00 |
    • |  6 | Komal    |  22 | MP        |  4500.00 |
    • |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    • |  3 | kaushik  |  23 | Kota      |  2000.00 |
    • |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    • |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    • +—-+———-+—–+———–+———-+

    GROUP BY

    The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. i.e if a particular column has same values in different rows then it will arrange these rows in a group.

    Important Points:

    • GROUP BY clause is used with the SELECT statement.
    • In the query, GROUP BY clause is placed after the WHERE clause.
    • In the query, GROUP BY clause is placed before ORDER BY clause if used any.

    SQL Server GROUP BY clause and aggregate functions

    • In practice, the GROUP BY clause is often used with aggregate functions for generating summary reports.
    • An aggregate function performs a calculation on a group and returns a unique value per group. For example, COUNT() returns the number of rows in each group. Other commonly used aggregate functions are SUM(), AVG() (average), MIN() (minimum), MAX() (maximum).
    • The GROUP BY clause arranges rows into groups and an aggregate function returns the summary (count, min, max, average, sum, etc.,) for each group.

    Syntax

    The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

    • SELECT column1, column2
    • FROM table_name
    • WHERE [ conditions ]
    • GROUP BY column1, column2
    • ORDER BY column1, column2
    • An important component for Analyst to summarize the data such as sales, profit, cost, and salary. Data Summarization is very helpful for Analyst to create a visualization, conclude findings, and report writing. In SQL, GROUP BY Clause is one of the tools to summarize or aggregate the data series. For example, sum up the daily sales and combine in a single quarter and show it to the senior management. Similarly, if you want to count how many employees in each department of the company. It groups the databases on the basis of one or more column and aggregates the results.
    Course Curriculum

    Enroll in Best SQL Training and Get Hired by TOP MNCs

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum
    • After Grouping the data, you can filter the grouped record using HAVING Clause. HAVING Clause returns the grouped records which match the given condition. You can also sort the grouped records using ORDER BY. ORDER BY used after GROUP BY on aggregated column.
    • In this tutorial, you are going to learn GROUP BY Clause in detail with relevant examples. Here is the list of topics that you will learn in this tutorial:

    Group By Clause

    The GROUP BY Clause is utilized in SQL with the SELECT statement to organize similar data into groups. It combines the multiple records in single or more columns using some functions. Generally, these functions are aggregate functions such as min(),max(),avg(), count(), and sum() to combine into single or multiple columns. It uses the split-apply-combine strategy for data analysis.

    • In the split phase, It divides the groups with its values.
    • In the apply phase, It applies the aggregate function and generates a single value.
    • In the combiner phase, It combines the groups with single values into a single value.

     GROUP BY With JOIN Example

    The normalized relational database breaks down the complex table into small tables, which helps you to eliminate the data redundancy, inconsistency and ensure there is no loss of information. Normalized tables require joining data from multiple tables.

    GROUP BY With JOIN Example-Order By and Group By in SQL Tutorial

    In above example, Employee and Department are joined using the common column DeptID.

    GROUP BY With JOIN Example-Order By and Group By in SQL Tutorial

    In the above example, JOIN and GROUP BY both clauses used together in a single query. After joining both tables(Employee and Department), joined table grouped by Department name.

    GROUP BY Comparison with Other Clause

    Compare GROUP BY and DISTINCT

    DISTINCT returns the unique values present in the column while GROUP BY returns unique/distinct items with the aggregate resultant column. In the following example you can see the DISTINCT values in the dept table.

    GROUP BY Comparison with Other Clause-Order By and Group By in SQL Tutorial

    Compare GROUP BY and ORDER BY

    Course Curriculum

    Get Experts Curated SQL Course to Build Your Skills

    Weekday / Weekend BatchesSee Batch Details

    ORDER BY returns sorted items in ascending and descending order while GROUP BY returns unique items with the aggregate resultant column. In the following example, you can see the ORDER BY or sorted salary table.

    Compare GROUP BY and ORDER BY -Order By and Group By in SQL Tutorial

    Example

    • Consider the CUSTOMERS table is having the following records −
    • +—-+———-+—–+———–+———-+
    • | ID | NAME     | AGE | ADDRESS   | SALARY   |
    • +—-+———-+—–+———–+———-+
    • |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    • |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    • |  3 | kaushik  |  23 | Kota      |  2000.00 |
    • |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    • |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    • |  6 | Komal    |  22 | MP        |  4500.00 |
    • |  7 | Muffy    |  24 | Indore    | 10000.00 |
    • +—-+———-+—–+———–+———-+

    If you want to know the total amount of the salary on each customer, then the GROUP BY query would be as follows.

    SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS

       GROUP BY NAME;

    • This would produce the following result −
    • +———-+————-+
    • | NAME     | SUM(SALARY) |
    • +———-+————-+
    • | Chaitali |     6500.00 |
    • | Hardik   |     8500.00 |
    • | kaushik  |     2000.00 |
    • | Khilan   |     1500.00 |
    • | Komal    |     4500.00 |
    • | Muffy    |    10000.00 |
    • | Ramesh   |     2000.00 |
    • +———-+————-+

    Now, let us look at a table where the CUSTOMERS table has the following records with duplicate names −

    • +—-+———-+—–+———–+———-+
    • | ID | NAME     | AGE | ADDRESS   | SALARY   |
    • +—-+———-+—–+———–+———-+
    • |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    • |  2 | Ramesh   |  25 | Delhi     |  1500.00 |
    • |  3 | kaushik  |  23 | Kota      |  2000.00 |
    • |  4 | kaushik  |  25 | Mumbai    |  6500.00 |
    • |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    • |  6 | Komal    |  22 | MP        |  4500.00 |
    • |  7 | Muffy    |  24 | Indore    | 10000.00 |
    • +—-+———-+—–+———–+———-+

    Now again, if you want to know the total amount of salary on each customer, then the GROUP BY query would be as follows −

    SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS

       GROUP BY NAME;

    SQL Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    • This would produce the following result −
    • +———+————-+
    • | NAME    | SUM(SALARY) |
    • +———+————-+
    • | Hardik  |     8500.00 |
    • | kaushik |     8500.00 |
    • | Komal   |     4500.00 |
    • | Muffy   |    10000.00 |
    • | Ramesh  |     3500.00 |
    • +———+————-+

    Conclusion

    You have covered a lot of details about the GROUP BY and HAVING Clause. You have learned what the GROUP BY and HAVING Clause are with examples, Comparison between HAVING and WHERE Clause in SQL, GROUP BY with JOIN, and GROUP BY Comparison with DISTINCT and ORDER BY. In the last section, you have a Hands-on practice assignment to assess your knowledge.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free