SQL | GROUP BY - GeeksforGeeks (2024)

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 the same values in different rows then it will arrange these rows in a group.

Features

  • GROUP BY clause is used with the SELECT statement.
  • In the query, the GROUP BY clause is placed after the WHERE clause.
  • In the query, the GROUP BY clause is placed before the ORDER BY clause if used.
  • In the query, the Group BY clause is placed before the Having clause.
  • Place condition in the having clause.

Syntax:

SELECT column1, function_name(column2)

FROM table_name

WHERE condition

GROUP BY column1, column2

ORDER BY column1, column2;

Explanation:

  1. function_name: Name of the function used for example, SUM() , AVG().
  2. table_name: Name of the table.
  3. condition: Condition used.

Let’s assume that we have two tables Employee and Student Sample Table is as follows after adding two tables we will do some specific operations to learn about GROUP BY.

Employee Table:

CREATE TABLE emp ( emp_no INT PRIMARY KEY, name VARCHAR(50), sal DECIMAL(10,2), age INT);

Insert some random data into a table and then we will perform some operations in GROUP BY.

Query:

INSERT INTO emp (emp_no, name, sal, age) VALUES(1, 'Aarav', 50000.00, 25),(2, 'Aditi', 60000.50, 30),(3, 'Amit', 75000.75, 35),(4, 'Anjali', 45000.25, 28),(5, 'Chetan', 80000.00, 32),(6, 'Divya', 65000.00, 27),(7, 'Gaurav', 55000.50, 29),(8, 'Isha', 72000.75, 31),(9, 'Kavita', 48000.25, 26),(10, 'Mohan', 83000.00, 33);

Output:

SQL | GROUP BY - GeeksforGeeks (1)

Student Table:

Query:

CREATE TABLE student ( name VARCHAR(50), year INT, subject VARCHAR(50));INSERT INTO student (name, year, subject) VALUES('Alice', 1, 'Mathematics'),('Bob', 2, 'English'),('Charlie', 3, 'Science'),('David', 1, 'History'),('Emily', 2, 'Art'),('Frank', 3, 'Computer Science');

Output:

SQL | GROUP BY - GeeksforGeeks (2)

Group By single column

Group By single column means, placing all the rows with the same value of only that particular column in one group. Consider the query as shown below:

Query:

SELECT NAME, SUM(SALARY) FROM emp GROUP BY NAME;

The above query will produce the below output:

SQL | GROUP BY - GeeksforGeeks (3)

As you can see in the above output, the rows with duplicate NAMEs are grouped under the same NAME and their corresponding SALARY is the sum of the SALARY of duplicate rows. The SUM() function of SQL is used here to calculate the sum.

Group By Multiple Columns

Group by multiple columns is say, for example, GROUP BY column1, column2. This means placing all the rows with the same values of columns column 1 and column 2 in one group. Consider the below query:

Query:

SELECT SUBJECT, YEAR, Count(*)FROM StudentGROUP BY SUBJECT, YEAR;

Output:

SQL | GROUP BY - GeeksforGeeks (4)

Output: As you can see in the above output the students with both the same SUBJECT and YEAR are placed in the same group. And those whose only SUBJECT is the same but not YEAR belong to different groups. So here we have grouped the table according to two columns or more than one column.

HAVING Clause in GROUP BY Clause

We know that the WHERE clause is used to place conditions on columns but what if we want to place conditions on groups? This is where the HAVING clause comes into use. We can use the HAVING clause to place conditions to decide which group will be part of the final result set. Also, we can not use aggregate functions like SUM(), COUNT(), etc. with the WHERE clause. So we have to use the HAVING clause if we want to use any of these functions in the conditions.

Syntax:

SELECT column1, function_name(column2)

FROM table_name

WHERE condition

GROUP BY column1, column2

HAVING condition

ORDER BY column1, column2;

Explanation:

  1. function_name: Name of the function used for example, SUM() , AVG().
  2. table_name: Name of the table.
  3. condition: Condition used.

Example:

SELECT NAME, SUM(sal) FROM EmpGROUP BY nameHAVING SUM(sal)>3000; 

Output:

SQL | GROUP BY - GeeksforGeeks (5)

As you can see in the above output only one group out of the three groups appears in the result set as it is the only group where sum of SALARY is greater than 3000. So we have used the HAVING clause here to place this condition as the condition is required to be placed on groups not columns.


Like Article

Suggest improvement

Previous

ORDER BY in SQL

Next

SQL | LIMIT Clause

Share your thoughts in the comments

Please Login to comment...

SQL | GROUP BY - GeeksforGeeks (2024)

FAQs

Can I learn SQL in 15 days? ›

Structured Query Language (SQL) is a fundamental skill for anyone working with databases, whether you're a data analyst, software developer, or business professional. While becoming a true SQL expert takes time and practice, you can acquire essential SQL skills in just 15 days.

How many days will it take to learn SQL? ›

How Long Does it Take to Learn SQL? Because SQL is a relatively simple language, learners can expect to become familiar with the basics within two to three weeks. That said, if you're planning on using SQL skills at work, you'll probably need a higher level of fluency.

What is SQL Geek for Geeks? ›

Structured Query Language (SQL) is a specialized programming language for managing relational database data. It allows users to store, manipulate, and retrieve data efficiently in databases like MySQL, SQL Server, Oracle, and more.

How to learn SQL in 10 days? ›

Day 1: Getting Started With SQL Using MySQL
  1. Introduction to DAY 1. Preview 03:20.
  2. Basics: Understanding Data and Databases. Preview 05:21.
  3. What is DBMS (Database Management System)? ...
  4. Introduction to Relational Databases Concepts. ...
  5. Overview of SQL. ...
  6. Installing MySQL on Windows. ...
  7. Installing MySQL on Mac. ...
  8. Installing MySQL on Linux.

How difficult is SQL for beginners? ›

The SQL syntax is easy to learn, and there are hundreds of tutorials online that can help you. You can test your knowledge of the basics with flashcards, online challenges, and free quizzes. There are also dozens of free resources like this SQL Query Cheatsheet.

Am I too old to learn SQL? ›

It's never too late to learn a programming language.

Is SQL easier than Python? ›

Is SQL harder than Python? SQL is a bit easier to start with. It's really easy if you're only doing basic stuff like putting data together or asking simple questions. But if you're doing complex tasks, using just SQL can be tricky.

What is the salary of a SQL developer? ›

The average salary for SQL Developer is ₹5,30,000 per year in the India. The average additional cash compensation for a SQL Developer in the India is ₹50,000, with a range from ₹27,500 - ₹56,250. Salaries estimates are based on 809 salaries submitted anonymously to Glassdoor by SQL Developer employees in India.

Do you need a powerful computer for SQL? ›

If you want to learn SQL, you're going to need a device that's portable and powerful. I recommend a laptop. Here are the features you'll need, as well as my picks for laptops to get you learning SQL in 2020!

Why do hackers use SQL? ›

SQL injection works by exploiting vulnerabilities in a website or computer application – usually through a data entry form. Hackers type SQL commands into fields such as login boxes, search boxes or 'sign up' fields. The aim is to use complex code sequences to gain access to a system and reveal the data held inside.

How to find the 2nd highest salary in SQL? ›

Using RANK() Function

The RANK() function in SQL assigns a ranking to rows based on specified criteria, like salary, in descending order. It helps identify the position of values, allowing retrieval of specific rankings, such as the second-highest salary.

What is the best way to learn SQL quickly? ›

The best way to learn SQL is through hands-on practice in a course that's designed to give you real-world SQL skills. DataCamp's online courses take you from an SQL newbie to a master of the database query, all while learning SQL at your own pace and from anywhere in the world.

How can I practice SQL on my own? ›

Best Platforms to Practice SQL Online
  1. HackerRank. HackerRank offers a wide range of coding challenges, including SQL. ...
  2. SQLPad. ...
  3. StrataScratch. ...
  4. LeetCode. ...
  5. Mode. ...
  6. SQLZoo. ...
  7. W3Schools. ...
  8. DataCamp.
Jan 18, 2024

What is the easiest SQL language to learn? ›

If you are just starting to learn SQL and want to get some hands-on experience, MySQL or PostgreSQL might be good choices since they are free and easy to set up. If you are interested in pursuing a career in a specific industry, it might be worth researching which RDBMS are commonly used in that field.

Is it possible to learn SQL in one week? ›

If you know how to code in other programming languages, it is possible to learn the basics of SQL within a week by studying 3 to 4 hours a day. If you are new to programming, you might need more time to learn the basics of SQL. In this case, it all depends on how much you want to learn.

How to get 15 days data in SQL? ›

Get Last 15 Days Record in MySQL Example:

where order_date > now() - INTERVAL 15 day; In the above query, we use the now() function to get the current date, and the INTERVAL() function to get the last 15 days records.

Can I master SQL in 2 days? ›

It should take an average learner about two to three weeks to master the basic concepts of SQL and start working with SQL databases. But in order to start using them effectively in real-world scenarios, you'll need to become quite fluent; and that takes time.

Can I learn SQL in 30 days? ›

Considering the depth of this topic, we would be requiring 30 days to learn SQL from the beginning to the advanced level. After 30 days, you will be able to apply SQL to real-life problems and crack the interviews. Stay committed to the roadmap and solve as many questions as you can solve daily to maintain consistency.

Top Articles
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 6433

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.