SQL•Subqueries
SQL Subqueries: Correlated and Non-Correlated Subqueries
Subqueries allow computing dynamic thresholds and filtering based on secondary table lookups.
Syntax
SELECT * FROM table WHERE price > (SELECT AVG(price) FROM table);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| Subquery | Query Expression | Nested SELECT statement executed within an outer query. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT,
price REAL
);
INSERT INTO products VALUES
(1, 'Keyboard', 120.00),
(2, 'Mouse', 45.00),
(3, 'Monitor', 350.00),
(4, 'Webcam', 60.00);
-- Find products priced above the catalog average
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products);Expected Output:
name price ------- ----- Monitor 350.0
How It Works: Step-by-Step
- Lines 7-11: Catalog average is (120+45+350+60)/4 = 143.75.
- Lines 14-16: Subquery (SELECT AVG(price) FROM products) evaluates to 143.75; returns Monitor.
Key Concepts
- Subqueries in WHERE clauses can return single values (scalars) or lists with IN.
- Correlated subqueries reference columns from the outer query for each row.
Common Mistake: Using scalar comparison (=) when a subquery returns multiple rows
WHERE col = (subquery) throws an error if subquery returns > 1 row. Use IN instead.
❌ Incorrect
WHERE id = (SELECT id FROM users WHERE active = 1) // Fails if > 1 user!
✅ Correct
WHERE id IN (SELECT id FROM users WHERE active = 1)
Related SQL Tutorials & Compiler
SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
Combine related data across tables using INNER JOIN and LEFT OUTER JOIN with ON keys.
SQL Set Operations: UNION, UNION ALL, and INTERSECT
Combine result sets from multiple queries using UNION, UNION ALL, and INTERSECT.
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.