How can I use a subquery to filter rows by an aggregate threshold?
Quick answer
Put the aggregate query in parentheses inside the outer query’s WHERE clause. For example, WHERE salary > (SELECT AVG(salary) FROM employees) compares each employee’s salary with the average across the employees table. The inner query supplies one comparison value; the outer query returns rows above it. The example below uses invented data and illustrates SQLite syntax. [S1]
The question, the details, the next step.
A practical checklist
Confirm the threshold is the overall average, not a separate average per department.
Run
SELECT AVG(salary) FROM employees;by itself to inspect the comparison value.Use the same employee table for the aggregate and the outer filter if both should cover the same rows.
Choose
>to exclude values equal to the average, or>=to include them.Replace the illustrative table and column names with the names in your database.
A few more useful answers
Why use a subquery instead of typing the average into the WHERE clause?
The subquery calculates the threshold from the table rather than requiring you to enter a fixed number. That makes the comparison follow the aggregate produced by the inner query.
Does this query return employees earning exactly the average?
No. The shown > condition excludes equality. Use >= if equal-to-average salaries should also be returned.
Does the example prove this syntax works in every SQL database?
No. The cited evidence describes SQLite’s scalar-subquery behavior and illustrates this pattern in SQLite; it does not establish behavior for every database system. [S1]
Sources
References used for this guide.
- [S1] SQLite SQL Language Expressions: Scalar Subqueries sqlite.org · Checked
