SQL:SQL Subqueries: Correlated and Non-Correlated Subqueries
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:

ParameterTypeDescription
SubqueryQuery ExpressionNested SELECT statement executed within an outer query.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler