- SQL Basics
-
Overview
- Introduction to Databases and SQL
- Creating and Managing Tables in SQL
- Data Types and Constraints
- SELECT Queries and Filtering Data
- GROUP BY, HAVING, and ORDER BY
- SQL Joins (INNER, LEFT, RIGHT, FULL)
- Subqueries and Nested Queries
- UNION, INTERSECT, and EXCEPT
- Common Table Expressions (CTE)
- SQL Views and Stored Procedures
GROUP BY, HAVING, and ORDER BY
Add to BookmarkIntroduction
In SQL, when working with large datasets, it's often necessary to group records, filter aggregated results, and arrange the output in a meaningful order. The GROUP BY, HAVING, and ORDER BY clauses help achieve these functionalities. In this tutorial, we will explore each of these clauses with practical examples.
1. GROUP BY Clause
The GROUP BY clause is used to group rows that have the same values in specified columns into summary rows, typically used with aggregate functions like COUNT, SUM, AVG, MAX, and MIN.
Syntax:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
Example:
Consider a sales
table with the following structure:
id | customer_name | product | amount |
---|---|---|---|
1 | Raj | Laptop | 50000 |
2 | Neha | Mobile | 20000 |
3 | Raj | Tablet | 15000 |
4 | Rahul | Laptop | 52000 |
5 | Neha | Mobile | 25000 |
To find the total amount spent by each customer:
SELECT customer_name, SUM(amount) AS total_spent
FROM sales
GROUP BY customer_name;
Output:
customer_name | total_spent |
Raj | 65000 |
Neha | 45000 |
Rahul | 52000 |
2. HAVING Clause
The HAVING clause is used to filter records after the GROUP BY operation. Unlike WHERE, which filters before aggregation, HAVING filters after the aggregation is performed.
Syntax:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Example:
To find customers who spent more than 50,000:
SELECT customer_name, SUM(amount) AS total_spent
FROM sales
GROUP BY customer_name
HAVING SUM(amount) > 50000;
Output:
customer_name | total_spent |
Raj | 65000 |
Rahul | 52000 |
3. ORDER BY Clause
The ORDER BY clause is used to sort the result set in ascending (ASC) or descending (DESC) order.
Syntax:
SELECT column_name
FROM table_name
ORDER BY column_name ASC|DESC;
Example:
To display the total amount spent by each customer in descending order:
SELECT customer_name, SUM(amount) AS total_spent
FROM sales
GROUP BY customer_name
ORDER BY total_spent DESC;
Output:
customer_name | total_spent |
Raj | 65000 |
Rahul | 52000 |
Neha | 45000 |
Combining GROUP BY, HAVING, and ORDER BY
These clauses can be used together to refine SQL queries effectively.
Example:
To get customers who spent more than 40,000, sorted in descending order of spending:
SELECT customer_name, SUM(amount) AS total_spent
FROM sales
GROUP BY customer_name
HAVING SUM(amount) > 40000
ORDER BY total_spent DESC;
Output:
customer_name | total_spent |
Raj | 65000 |
Rahul | 52000 |
Neha | 45000 |
Conclusion
- GROUP BY is used to aggregate data based on specific columns.
- HAVING filters grouped data after aggregation.
- ORDER BY sorts the results based on one or more columns.
These clauses are essential for analyzing and summarizing large datasets in SQL efficiently. Mastering them will enhance your database querying skills significantly.
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- Google’s Core Update in May 2020: What You Need to Know
- How AI Companies Are Making Humans Fools and Exploiting Their Data
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- How to Start Your Career as a DevOps Engineer
- Time Series Analysis on Air Passenger Data
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- String Operations in Python
- Government Datasets from 50 Countries for Machine Learning Training
- Datasets for Speech Recognition Analysis
- What Is SEO and Why Is It Important?
- Types of Numbers in Python
- Top 10 Knowledge for Machine Learning & Data Science Students
- Convert RBG Image to Gray Scale Image Using CV2
- Datasets for Natural Language Processing
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset