› Forums › SQL › π Learning Post: Using SQL Subqueries with WHERE and AND (Fixing a Common Mistake)
- This topic is empty.
-
AuthorPosts
-
March 21, 2026 at 8:32 am #6258
When working with SQL, it’s very common to compare values against averages using subqueries. But small syntax mistakes can break your query β like using multiple
WHEREclauses.Letβs walk through this step-by-step.
π― Problem Statement
We want to find:
Districts that spend more than average per student AND have above-average exemplary staff ratings
β Initial (Incorrect) Query
SELECT districts.name, expenditures.per_pupil_expenditure, staff_evaluations.exemplary FROM districts JOIN expenditures ON districts.id = expenditures.district_id JOIN staff_evaluations ON districts.id = staff_evaluations.district_id WHERE expenditures.per_pupil_expenditure > (SELECT AVG(expenditures.per_pupil_expenditure) FROM expenditures) AND WHERE staff_evaluations.exemplary > ( SELECT AVG(staff_evaluations.exemplary) FROM staff_evaluations;
π¨ What Went Wrong?
1. β Two
WHEREClausesSQL allows only one
WHEREclause per query.π You must combine conditions using:
ANDOR
2. β Missing Parenthesis
The second subquery is not properly closed:
FROM staff_evaluations;Needs a closing
)before the semicolon.
β Correct Query
SELECT districts.name, expenditures.per_pupil_expenditure, staff_evaluations.exemplary FROM districts JOIN expenditures ON districts.id = expenditures.district_id JOIN staff_evaluations ON districts.id = staff_evaluations.district_id WHERE expenditures.per_pupil_expenditure > (SELECT AVG(per_pupil_expenditure) FROM expenditures) AND staff_evaluations.exemplary > (SELECT AVG(exemplary) FROM staff_evaluations);
π§ Concept Breakdown
πΉ 1. Subqueries
A subquery is a query inside another query.
Example:
SELECT AVG(per_pupil_expenditure) FROM expenditures;π This returns a single value (average), which we compare against.
πΉ 2. Combining Conditions
Instead of:
WHERE condition1 AND WHERE condition2 βUse:
WHERE condition1 AND condition2 β
πΉ 3. Logical Flow
SQL evaluates like this:
- Calculate average expenditure
- Calculate average exemplary score
- Filter districts:
- Keep only those above both averages
π§ͺ Debugging Tip (Very Important)
Always test subqueries separately:
SELECT AVG(per_pupil_expenditure) FROM expenditures; SELECT AVG(exemplary) FROM staff_evaluations;π This helps you:
- Verify correctness
- Understand what your main query is comparing against
π‘ Pro Insight
This type of query is very common in:
- π Data analysis
- π« Education datasets
- πΌ Business intelligence dashboards
π Practice Exercise
Try modifying the query to find:
π Districts that:
- Spend below average
- But still have above-average exemplary ratings
-
AuthorPosts
- You must be logged in to reply to this topic.
