In SQL, filtering data is essential for querying specific results from a database. Here's an explanation of how the WHERE, ORDER BY, GROUP BY, and HAVING clauses work, along with examples to demonstrate their differences.
Sql joins cheat sheets |
1. WHERE Clause
The WHERE
clause is used to filter records before any grouping or aggregation happens. It specifies the condition that must be met for rows to be included in the result set.
Example:
sql
SELECT * FROM Employees
WHERE Age > 30;
- Explanation: This query retrieves all employees who are older than 30.
2. ORDER BY Clause
The ORDER BY
clause is used to sort the result set by one or more columns, either in ascending (ASC
) or descending (DESC
) order. It is applied after any filtering (WHERE
) and grouping (GROUP BY
).
Example:
sql
SELECT * FROM Employees
WHERE Age > 30
ORDER BY Name ASC;
- Explanation: This query retrieves all employees older than 30, then sorts them by their name in ascending order.
3. GROUP BY Clause
The GROUP BY
clause is used to group rows that have the same values in specified columns into summary rows, like "total" or "average". It is typically used with aggregate functions such as COUNT()
, SUM()
, AVG()
, MAX()
, MIN()
.
Example:
sql
SELECT Department, COUNT(*) as EmployeeCount
FROM Employees
GROUP BY Department;
- Explanation: This query groups employees by department and calculates the number of employees in each department.
4. HAVING Clause
The HAVING
clause is used to filter the result set after the GROUP BY
operation. It is similar to WHERE
but is applied to groups created by GROUP BY
rather than individual rows.
Example:
sql
SELECT Department, COUNT(*) as EmployeeCount
FROM Employees
GROUP BY Department
HAVING COUNT(*) > 5;
- Explanation: This query groups employees by department, calculates the count for each department, and then filters the result to only include departments with more than 5 employees.
Differences Between WHERE, ORDER BY, GROUP BY, and HAVING
Clause | Purpose | Applied To | Example Use Case |
---|---|---|---|
WHERE | Filters rows before grouping or aggregation. | Individual rows | WHERE Age > 30 (filter rows based on a condition) |
ORDER BY | Sorts the result set in a specified order. | Entire result set | ORDER BY Name ASC (sort rows by name) |
GROUP BY | Groups rows by one or more columns for aggregation. | Groups of rows | GROUP BY Department (group employees by department) |
HAVING | Filters groups after grouping and aggregation. | Groups of rows after GROUP BY | HAVING COUNT(*) > 5 (filter groups based on aggregate result) |
Summary of Differences:
- WHERE: Filters rows before
GROUP BY
andHAVING
. It works on individual rows. - ORDER BY: Sorts the entire result set, applied last.
- GROUP BY: Groups rows into summary data, often with aggregate functions.
- HAVING: Filters groups after
GROUP BY
, typically used with aggregate functions likeCOUNT()
.
No comments:
Post a Comment