SQL GROUP BY
The GROUP BY clause in SQL is used to group rows that have the same values in specified columns. It is commonly used with aggregate functions to perform calculations on each group.
Basic Syntax
SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name;
GROUP BY with COUNT(): Count how many students are in each city.
SELECT city, COUNT(*) FROM students GROUP BY city;
GROUP BY with AVG(): Find the average marks in each city.
SELECT city, AVG(marks) FROM students GROUP BY city;
GROUP BY with Multiple Columns
SELECT city, marks FROM students GROUP BY city, marks; This groups rows by both city and marks.
Example: Combining GROUP BY and ORDER BY
SELECT city, COUNT(*) FROM students GROUP BY city ORDER BY city; This: Groups students by city Counts them Sorts the result by city name
Example: find duplicates is using GROUP BY:
SELECT email, COUNT(*) FROM Students GROUP BY email HAVING COUNT(*) > 1;