{
    "slug": "mysql_subqueries",
    "term": "MySQL Subqueries",
    "category": "database",
    "difficulty": "intermediate",
    "short": "A query nested inside another — useful for filtering and deriving values, but correlated subqueries re-execute per outer row and can be O(n²).",
    "long": "Subqueries can appear in SELECT (scalar), FROM (derived table), WHERE, or HAVING. Correlated subqueries reference the outer query and re-execute for each outer row — potentially catastrophically slow on large tables. Non-correlated subqueries execute once. IN (subquery) evaluates the full subquery; EXISTS short-circuits on first match — EXISTS is usually faster for large sets. MySQL 8+ improves subquery decorrelation automatically in some cases.",
    "aliases": [
        "SQL subquery",
        "correlated subquery MySQL",
        "derived table",
        "EXISTS vs IN MySQL"
    ],
    "tags": [
        "mysql",
        "database",
        "sql",
        "performance"
    ],
    "misconception": "IN (SELECT ...) and EXISTS (SELECT ...) are always equivalent. EXISTS short-circuits; IN evaluates everything. On large subqueries EXISTS is significantly faster.",
    "why_it_matters": "A correlated subquery in a WHERE or SELECT clause is the SQL equivalent of the N+1 problem — executing thousands of times on large datasets and turning a fast query into a slow one.",
    "common_mistakes": [
        "Using a correlated subquery in SELECT to fetch a related value — re-executes for every row.",
        "Using IN with a large subquery instead of a JOIN or EXISTS.",
        "Nesting subqueries more than two levels deep — readability and optimisability both suffer."
    ],
    "when_to_use": [
        "Use EXISTS for semi-join checks — checking whether any related row exists.",
        "Use derived tables in FROM for complex aggregations that need to be joined back."
    ],
    "avoid_when": [
        "Avoid correlated subqueries in SELECT — replace with a JOIN.",
        "Avoid deep nesting — flatten with CTEs (WITH clause) in MySQL 8 for readability."
    ],
    "related": [
        "mysql_joins",
        "mysql_n_plus_one",
        "mysql_group_by"
    ],
    "prerequisites": [
        "mysql_joins",
        "mysql_group_by"
    ],
    "refs": [
        "https://dev.mysql.com/doc/refman/8.0/en/subqueries.html"
    ],
    "bad_code": "-- Correlated: re-runs for every user row → O(n²)\nSELECT email,\n       (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS cnt\nFROM users u;",
    "good_code": "-- EXISTS short-circuits on first match\nSELECT * FROM users u\nWHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.status = 'paid');\n\n-- Derived table in FROM (executes once)\nSELECT u.email, stats.total\nFROM users u\nJOIN (SELECT user_id, SUM(total) AS total FROM orders GROUP BY user_id) stats\n    ON stats.user_id = u.id;",
    "quick_fix": "Replace correlated subqueries with a JOIN — use EXISTS instead of IN for large subquery result sets",
    "effort": "medium",
    "created": "2026-03-31",
    "updated": "2026-03-31",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/mysql_subqueries",
        "html_url": "https://codeclaritylab.com/glossary/mysql_subqueries",
        "json_url": "https://codeclaritylab.com/glossary/mysql_subqueries.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[MySQL Subqueries](https://codeclaritylab.com/glossary/mysql_subqueries) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/mysql_subqueries"
            }
        }
    }
}