GROUP BY clause | SQL Tutorial and Query Example

Text copied!

GROUP BY clause


  • GROUP BY clause :

    GROUP BY clause is used to group and summarize the data based on column(s) and generally combined with aggregate functions such as SUM, AVG, COUNT, MIN and MAX etcetera to calculate the summaries of the grouped data.

    The syntax of the GROUP BY clause generally looks like this :
    Here's an example of how you might use the GROUP BY clause :

    Let's assume we have a table named "[Employees]".

    Case - 1 :

    Let's assume you want to determine the number of employees by gender to know how many employees are male or female in the [Employees] table.

    SELECT column_name(s)
    FROM table_name
    GROUP BY column_name(s);
            
    Case - 2 :

    Let's assume you want to determine the total salary of employees by gender to know how much male or female employees earns in the [Employees] table.

    Case - 3 :
    GROUP BY clause
    SELECT Gender, COUNT(Gender) AS [Gender_Count]
    FROM [Employees]
    GROUP BY Gender;
            
    GROUP BY clause
    SELECT Gender, SUM(Salary) AS [Salary_By_Gender]
    FROM [Employees]
    GROUP BY Gender;
            
    GROUP BY clause
    SELECT Gender, MAX(Salary) AS [Max_Salary_By_Gender]
    FROM Employees
    GROUP BY Gender;
            
    GROUP BY clause

    Frequently Asked Questions :

    GROUP BY clause is used in SQL to group rows that have the same values into summary rows, with an example like "SELECT department, AVG(salary) FROM employees GROUP BY department;"
    GROUP BY HAVING clause filters grouped rows based on specified conditions, helpful for filtering aggregated data, such as "SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000;"
    GROUP BY 1 refers to grouping by the first column specified in the SELECT statement, such as "SELECT department, AVG(salary) FROM employees GROUP BY 1;"
    "Clause" is a general term in SQL referring to syntactical elements like SELECT or WHERE, whereas GROUP BY clause specifically organizes data into groups for aggregation.