In this project, I’m learning how to filter data effectively using the WHERE and HAVING clauses. Instead of working with the entire dataset, these techniques allow me to focus only on the specific information I need for analysis.
What You’ll Learn
- How to filter individual rows using WHERE
- How to combine multiple conditions with AND, OR, IN, BETWEEN, and LIKE
- How to filter grouped results using HAVING
- Practical examples using the Medicare Hospital Readmission dataset
1. Filtering with WHERE
The WHERE clause is used to filter rows before any grouping happens.
-- Example: Filter hospitals in California only
SELECT
Facility_Name,
State,
Predicted_Readmission_Rate
FROM Hospital_Readmissions
WHERE State = 'CA'
ORDER BY Predicted_Readmission_Rate DESC;
2. Using AND / OR
You can combine multiple conditions using AND and OR.
-- Hospitals in California with readmission rate over 20%
SELECT
Facility_Name,
State,
Predicted_Readmission_Rate
FROM Hospital_Readmissions
WHERE State = 'CA'
AND Predicted_Readmission_Rate > 20
ORDER BY Predicted_Readmission_Rate DESC;
3. Using IN
The IN operator is useful when you want to filter by multiple specific values.
-- Example: Show hospitals in CA, NY, or TX
SELECT
Facility_Name,
State,
Predicted_Readmission_Rate
FROM Hospital_Readmissions
WHERE State IN ('CA', 'NY', 'TX')
ORDER BY Predicted_Readmission_Rate DESC;
4. Using BETWEEN
BETWEEN is used to filter within a range of values.
-- Example: Hospitals with readmission rates between 15 and 25
SELECT
Facility_Name,
State,
Predicted_Readmission_Rate
FROM Hospital_Readmissions
WHERE Predicted_Readmission_Rate BETWEEN 15 AND 25
ORDER BY Predicted_Readmission_Rate DESC;
5. Using LIKE (Pattern Matching)
LIKE is used for partial text matching. It is helpful when you don’t know the exact value.
-- Example: Find hospitals containing "Medical Center" in the name
SELECT
Facility_Name,
State
FROM Hospital_Readmissions
WHERE Facility_Name LIKE '%Medical Center%'
ORDER BY Predicted_Readmission_Rate DESC;
6. Filtering with HAVING
While WHERE filters rows before grouping, HAVING filters after grouping. It is commonly used with aggregate functions.
-- Example: States with more than 500 hospitals
SELECT
State,
COUNT(DISTINCT Facility_ID) AS Total_Hospitals
FROM Hospital_Readmissions
GROUP BY State
HAVING COUNT(DISTINCT Facility_ID) > 500
ORDER BY Total_Hospitals DESC;
Summary
| Clause | When it filters | Works with aggregates? | Common Use Case |
|---|---|---|---|
| WHERE | Before grouping | No | Filter individual rows |
| HAVING | After grouping | Yes | Filter aggregated results |
| AND / OR | Combine conditions | — | Multiple filter conditions |
| IN | Multiple specific values | — | Filter by a list of values |
| BETWEEN | Range of values | — | Numeric or date ranges |
| LIKE | Partial text match | — | Search within text fields |