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.
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.
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;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;| customer_name | total_spent |
| Raj | 65000 |
| Neha | 45000 |
| Rahul | 52000 |
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.
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;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;| customer_name | total_spent |
| Raj | 65000 |
| Rahul | 52000 |
The ORDER BY clause is used to sort the result set in ascending (ASC) or descending (DESC) order.
SELECT column_name
FROM table_name
ORDER BY column_name ASC|DESC;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;| customer_name | total_spent |
| Raj | 65000 |
| Rahul | 52000 |
| Neha | 45000 |
These clauses can be used together to refine SQL queries effectively.
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;| customer_name | total_spent |
| Raj | 65000 |
| Rahul | 52000 |
| Neha | 45000 |
These clauses are essential for analyzing and summarizing large datasets in SQL efficiently. Mastering them will enhance your database querying skills significantly.
Sign in to join the discussion and post comments.
Sign in