Summary

Query scans 2 tables, joins via block nested-loopLearn → and sorts the result; examines ~11,000 rows to return 5 in 1284 ms. Main finding: join predicate wraps the column in CONCAT() — no regular index can be used (only a functional index on that exact expression).

Total time
1.28 s
Rows returned
5
Rows examined
11.00K
Operators
4
Fix first

Primary recommendation

Rewrite the join condition to compare the bare column on both sides (e.g. 'a.id = b.other_id' instead of 'CONCAT(a.id)=CONCAT(b.other_id)').

Why does this help?

wrapping a column in a function means the optimizer cannot use any index on that column — every row-pair is evaluated in the server layer, making the cost O(outer × inner). Dropping the function lets MySQL/MariaDB pick an index lookup or hash joinLearn → with real selectivity, typically 100–1000× faster on mid-sized tables.

SQL

SELECT u.country, SUM(o.amount) AS total
FROM users u
  JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id)
WHERE u.status='active'
GROUP BY u.country
ORDER BY total DESC

Execution plan (flamegraph)

Click a plan operator to inspect details.

Warnings (5)

  1. ERROR

    Non-sargable join predicate: CONCAT(...) in concat('u',o.user_id) = concat('u',u.`id`) — a function wrapped around the join column prevents index use.

    Labeled: Table scan [o]

  2. WARN

    Full table scan: u (3000 rows), o (8000 rows)

    Labeled: Table scan [u] Table scan [o]

  3. WARN

    1 sort operationLearn →(s) — 5 rows; may use disk-based filesortLearn →

    Labeled: Sort

  4. WARN

    Block Nested-LoopLearn → (BNLLearn →) join buffer detected — uses join_buffer_size (Extra: 'Using join buffer (Block Nested Loop)Learn →', type ALL/index/range)

    Labeled: Table scan [o]

  5. WARN

    Block Nested-LoopLearn → detected but join_buffer_size is only 256.0 KB. Build/batch phase may spill to tmpdir.

Suggestions (5)

  1. HIGH

    Rewrite the join condition to compare the bare column on both sides (e.g. 'a.id = b.other_id' instead of 'CONCAT(a.id)=CONCAT(b.other_id)').

    Why?

    wrapping a column in a function means the optimizer cannot use any index on that column — every row-pair is evaluated in the server layer, making the cost O(outer × inner). Dropping the function lets MySQL/MariaDB pick an index lookup or hash joinLearn → with real selectivity, typically 100–1000× faster on mid-sized tables.

  2. HIGH

    Add indexes on filter/join columns to avoid full table scans

  3. MEDIUM

    Increase sort_buffer_size or add an ordered index to avoid filesortLearn →

  4. MEDIUM

    Add indexes to eliminate BNLLearn → full/index scans, or increase join_buffer_size. In MySQL 8.0.20+, set block_nested_loopLearn →=off to force hash joinLearn → instead

  5. MEDIUM

    Raise join_buffer_size per-session to 2M–8M (SET SESSION join_buffer_size = 8*1024*1024).

    Why?

    BNLLearn → scans the inner table once per outer batch that fits in the join buffer. A tiny buffer means more batches, and each batch triggers another full scan of the inner side. Bigger win: add an index on the join column — that removes the need for the join buffer entirely by turning the join into an indexed lookup.

Collected environment

Session variables

version11.4.13-MariaDB-ubu2404
innodb_buffer_pool_size128.0 MB
sort_buffer_size2.0 MB
join_buffer_size256.0 KB
tmp_table_size16.0 MB
max_heap_table_size16.0 MB
innodb_flush_log_at_trx_commit1
optimizer_switch
38 flags (click to expand)
index_merge=onindex_merge_union=onindex_merge_sort_union=onindex_merge_intersection=onindex_merge_sort_intersection=offindex_condition_pushdown=onderived_merge=onderived_with_keys=onfirstmatch=onloosescan=onmaterialization=onin_to_exists=onsemijoin=onpartial_match_rowid_merge=onpartial_match_table_scan=onsubquery_cache=onmrr=offmrr_cost_based=offmrr_sort_keys=offouter_join_with_cache=onsemijoin_with_cache=onjoin_cache_incremental=onjoin_cache_hashed=onjoin_cache_bka=onoptimize_join_buffer_size=ontable_elimination=onextended_keys=onexists_to_in=onorderby_uses_equalities=oncondition_pushdown_for_derived=onsplit_materialized=oncondition_pushdown_for_subquery=onrowid_filter=oncondition_pushdown_from_having=onnot_null_range_scan=offhash_join_cardinality=oncset_narrowing=offsargable_casefold=on

Tables (click a name to expand)

demodb.ordersrows8,213data416.0 KBindexes176.0 KB

Columns (5)

  • id int(11)
  • user_id int(11)
  • status varchar(20)
  • amount decimal(10,2)
  • created_at datetime

Indexes (2)

  • INDEX (unnamed) (id)
  • INDEX idx_user (user_id)
demodb.usersrows3,000data176.0 KBindexes80.0 KB

Columns (5)

  • id int(11)
  • name varchar(80)
  • country varchar(2)
  • status varchar(20)
  • created_at datetime

Indexes (2)

  • INDEX (unnamed) (id)
  • INDEX idx_country (country)

myteach — interactive algorithm catalog

Every operator shown above has a hands-on lesson with a cost-model slider and an animated walk-through. The catalog is the central index — bookmark it once, revisit per query:

Open the full catalog →

Lessons relevant to this plan

Raw sidecar (JSON)

{
  "$schema": "https://myflames.dev/schemas/sidecar-v1.json",
  "schema_version": "1.3",
  "generated_at": "2026-10-15T19:55:14Z",
  "myflames_version": "2.3.0",
  "source": {
    "type": "live",
    "engine": "mariadb",
    "engine_version": "11.4.13-MariaDB-ubu2404"
  },
  "plan_summary": {
    "total_time_ms": 1283.554,
    "rows_sent": 5,
    "rows_examined_estimate": 11000,
    "operator_count": 4,
    "max_depth": 3
  },
  "optimizer_switches": [
    {
      "name": "block_nested_loop",
      "value": "on",
      "explanation": "Buffers a batch of outer rows in a join buffer and scans the inner table once per batch instead of once per row. Inner still does a full/index/range scan — a missing index on the join column is the root cause.",
      "node_labels": [
        "Table scan [o]"
      ]
    }
  ],
  "warnings": [
    {
      "severity": "error",
      "category": "nonsargable_join",
      "text": "Non-sargable join predicate: CONCAT(...) in concat('u',o.user_id) = concat('u',u.`id`) — a function wrapped around the join column prevents index use.",
      "source": "plan",
      "node_labels": [
        "Table scan [o]"
      ]
    },
    {
      "severity": "warn",
      "category": "full_scan",
      "text": "Full table scan: u (3000 rows), o (8000 rows)",
      "source": "plan",
      "node_labels": [
        "Table scan [u]",
        "Table scan [o]"
      ]
    },
    {
      "severity": "warn",
      "category": "filesort",
      "text": "1 sort operation(s) — 5 rows; may use disk-based filesort",
      "source": "plan",
      "node_labels": [
        "Sort"
      ]
    },
    {
      "severity": "warn",
      "category": "bnl",
      "text": "Block Nested-Loop (BNL) join buffer detected — uses join_buffer_size (Extra: 'Using join buffer (Block Nested Loop)', type ALL/index/range)",
      "source": "plan",
      "node_labels": [
        "Table scan [o]"
      ]
    },
    {
      "severity": "warn",
      "category": "env",
      "text": "Block Nested-Loop detected but join_buffer_size is only 256.0 KB. Build/batch phase may spill to tmpdir.",
      "source": "environment"
    }
  ],
  "suggestions": [
    {
      "severity": "high",
      "category": "rewrite",
      "action": "Rewrite the join condition to compare the bare column on both sides (e.g. 'a.id = b.other_id' instead of 'CONCAT(a.id)=CONCAT(b.other_id)').",
      "source": "plan",
      "why": "wrapping a column in a function means the optimizer cannot use any index on that column — every row-pair is evaluated in the server layer, making the cost O(outer × inner). Dropping the function lets MySQL/MariaDB pick an index lookup or hash join with real selectivity, typically 100–1000× faster on mid-sized tables."
    },
    {
      "severity": "high",
      "category": "index",
      "action": "Add indexes on filter/join columns to avoid full table scans",
      "source": "plan"
    },
    {
      "severity": "medium",
      "category": "tuning_variable",
      "action": "Increase sort_buffer_size or add an ordered index to avoid filesort",
      "source": "plan",
      "target_variable": "sort_buffer_size"
    },
    {
      "severity": "medium",
      "category": "tuning_variable",
      "action": "Add indexes to eliminate BNL full/index scans, or increase join_buffer_size. In MySQL 8.0.20+, set block_nested_loop=off to force hash join instead",
      "source": "plan",
      "target_variable": "join_buffer_size"
    },
    {
      "severity": "medium",
      "category": "tuning_variable",
      "action": "Raise join_buffer_size per-session to 2M–8M (SET SESSION join_buffer_size = 8*1024*1024).",
      "source": "environment",
      "why": "BNL scans the inner table once per outer batch that fits in the join buffer. A tiny buffer means more batches, and each batch triggers another full scan of the inner side. Bigger win: add an index on the join column — that removes the need for the join buffer entirely by turning the join into an indexed lookup.",
      "target_variable": "join_buffer_size"
    }
  ],
  "executive_summary": "Query scans 2 tables, joins via block nested-loop and sorts the result; examines ~11,000 rows to return 5 in 1284 ms. Main finding: join predicate wraps the column in CONCAT() — no regular index can be used (only a functional index on that exact expression).",
  "plan_tree": {
    "node_id": "n:f4f29c429056",
    "short_label": "Sort",
    "folded_label": "SORT starts=1 rows=5",
    "children": [
      {
        "node_id": "n:71b4ad99c5af",
        "short_label": "Nested loop inner join",
        "folded_label": "NESTED LOOP INNER starts=1 rows=8000",
        "children": [
          {
            "node_id": "n:ad535b01566b",
            "short_label": "Table scan [u]",
            "folded_label": "TABLE SCAN [u] starts=1 rows=3000",
            "children": []
          },
          {
            "node_id": "n:ee0a97ddd30d",
            "short_label": "Table scan [o]",
            "folded_label": "TABLE SCAN [o] starts=1 rows=8000",
            "children": []
          }
        ]
      }
    ]
  },
  "query": {
    "raw": "SELECT u.country, SUM(o.amount) AS total FROM users u JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id) WHERE u.status='active' GROUP BY u.country ORDER BY total DESC",
    "beautified": "SELECT u.country, SUM(o.amount) AS total\nFROM users u\n  JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id)\nWHERE u.status='active'\nGROUP BY u.country\nORDER BY total DESC"
  },
  "index_suggestions": [
    {
      "table": "u",
      "columns": [
        "status"
      ],
      "ddl": "CREATE INDEX idx_u_status ON u (status);",
      "reason": "Full scan on u with filter on (status)"
    },
    {
      "table": "o",
      "columns": [
        "user_id"
      ],
      "ddl": "CREATE INDEX idx_o_user_id ON o (user_id);",
      "reason": "Full scan on o with filter on (user_id)"
    }
  ],
  "primary_action": {
    "ref": "suggestions[0]"
  },
  "collected": {
    "variables": {
      "bulk_insert_buffer_size": "8388608",
      "character_set_connection": "utf8mb4",
      "character_set_server": "utf8mb4",
      "collation_connection": "utf8mb4_uca1400_ai_ci",
      "collation_server": "utf8mb4_uca1400_ai_ci",
      "eq_range_index_dive_limit": "200",
      "innodb_buffer_pool_size": "134217728",
      "innodb_file_per_table": "ON",
      "innodb_flush_log_at_trx_commit": "1",
      "innodb_flush_method": "O_DIRECT",
      "innodb_io_capacity": "200",
      "innodb_log_buffer_size": "16777216",
      "innodb_log_file_size": "100663296",
      "join_buffer_size": "262144",
      "max_allowed_packet": "16777216",
      "max_connections": "151",
      "max_heap_table_size": "16777216",
      "optimizer_prune_level": "2",
      "optimizer_search_depth": "62",
      "optimizer_switch": "index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,index_condition_pushdown=on,derived_merge=on,derived_with_keys=on,firstmatch=on,loosescan=on,materialization=on,in_to_exists=on,semijoin=on,partial_match_rowid_merge=on,partial_match_table_scan=on,subquery_cache=on,mrr=off,mrr_cost_based=off,mrr_sort_keys=off,outer_join_with_cache=on,semijoin_with_cache=on,join_cache_incremental=on,join_cache_hashed=on,join_cache_bka=on,optimize_join_buffer_size=on,table_elimination=on,extended_keys=on,exists_to_in=on,orderby_uses_equalities=on,condition_pushdown_for_derived=on,split_materialized=on,condition_pushdown_for_subquery=on,rowid_filter=on,condition_pushdown_from_having=on,not_null_range_scan=off,hash_join_cardinality=on,cset_narrowing=off,sargable_casefold=on",
      "read_buffer_size": "131072",
      "read_rnd_buffer_size": "262144",
      "sort_buffer_size": "2097152",
      "table_open_cache": "2000",
      "thread_cache_size": "151",
      "tmp_table_size": "16777216",
      "version": "11.4.13-MariaDB-ubu2404",
      "version_comment": "mariadb.org binary distribution",
      "version_compile_os": "debian-linux-gnu"
    },
    "stats": {
      "demodb.users": {
        "table_schema": "demodb",
        "table_name": "users",
        "table_rows": 3000,
        "data_length": 180224,
        "index_length": 81920,
        "data_free": 0,
        "auto_increment": 4096,
        "engine": "InnoDB",
        "row_format": "Dynamic"
      },
      "demodb.orders": {
        "table_schema": "demodb",
        "table_name": "orders",
        "table_rows": 8213,
        "data_length": 425984,
        "index_length": 180224,
        "data_free": 0,
        "auto_increment": 8192,
        "engine": "InnoDB",
        "row_format": "Dynamic"
      }
    },
    "schema": {
      "demodb.users": {
        "ddl": "CREATE TABLE `users` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `name` varchar(80) DEFAULT NULL,\n  `country` varchar(2) DEFAULT NULL,\n  `status` varchar(20) DEFAULT NULL,\n  `created_at` datetime DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `idx_country` (`country`)\n) ENGINE=InnoDB AUTO_INCREMENT=4096 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci",
        "table_name": "users",
        "columns": [
          {
            "name": "id",
            "type": "int(11)",
            "rest": "NOT NULL AUTO_INCREMENT"
          },
          {
            "name": "name",
            "type": "varchar(80)",
            "rest": "DEFAULT NULL"
          },
          {
            "name": "country",
            "type": "varchar(2)",
            "rest": "DEFAULT NULL"
          },
          {
            "name": "status",
            "type": "varchar(20)",
            "rest": "DEFAULT NULL"
          },
          {
            "name": "created_at",
            "type": "datetime",
            "rest": "DEFAULT NULL"
          }
        ],
        "indexes": [
          {
            "kind": "PRIMARY KEY",
            "name": null,
            "columns": [
              "id"
            ],
            "parts": [
              {
                "name": "id",
                "length": null,
                "desc": false,
                "expression": false
              }
            ],
            "using": null
          },
          {
            "kind": "KEY",
            "name": "idx_country",
            "columns": [
              "country"
            ],
            "parts": [
              {
                "name": "country",
                "length": null,
                "desc": false,
                "expression": false
              }
            ],
            "using": null
          }
        ],
        "engine": "InnoDB",
        "charset": "utf8mb4"
      },
      "demodb.orders": {
        "ddl": "CREATE TABLE `orders` (\n  `id` int(11) NOT NULL AUTO_INCREMENT,\n  `user_id` int(11) DEFAULT NULL,\n  `status` varchar(20) DEFAULT NULL,\n  `amount` decimal(10,2) DEFAULT NULL,\n  `created_at` datetime DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  KEY `idx_user` (`user_id`)\n) ENGINE=InnoDB AUTO_INCREMENT=8192 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci",
        "table_name": "orders",
        "columns": [
          {
            "name": "id",
            "type": "int(11)",
            "rest": "NOT NULL AUTO_INCREMENT"
          },
          {
            "name": "user_id",
            "type": "int(11)",
            "rest": "DEFAULT NULL"
          },
          {
            "name": "status",
            "type": "varchar(20)",
            "rest": "DEFAULT NULL"
          },
          {
            "name": "amount",
            "type": "decimal(10,2)",
            "rest": "DEFAULT NULL"
          },
          {
            "name": "created_at",
            "type": "datetime",
            "rest": "DEFAULT NULL"
          }
        ],
        "indexes": [
          {
            "kind": "PRIMARY KEY",
            "name": null,
            "columns": [
              "id"
            ],
            "parts": [
              {
                "name": "id",
                "length": null,
                "desc": false,
                "expression": false
              }
            ],
            "using": null
          },
          {
            "kind": "KEY",
            "name": "idx_user",
            "columns": [
              "user_id"
            ],
            "parts": [
              {
                "name": "user_id",
                "length": null,
                "desc": false,
                "expression": false
              }
            ],
            "using": null
          }
        ],
        "engine": "InnoDB",
        "charset": "utf8mb4"
      }
    }
  },
  "teach_hooks": [
    {
      "lesson": "filesort",
      "match": {
        "folded_label": "SORT starts=1 rows=5",
        "short_label": "Sort"
      },
      "controls": {
        "rows": 5,
        "row_size": 200,
        "sbs": 2097152
      },
      "note": "Sort: sum(o.amount) desc",
      "query_sql": "SELECT u.country, SUM(o.amount) AS total FROM users u JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id) WHERE u.status='active' GROUP BY u.country ORDER BY total DESC"
    },
    {
      "lesson": "nested_loop",
      "match": {
        "folded_label": "NESTED LOOP INNER starts=1 rows=8000",
        "short_label": "Nested loop inner join"
      },
      "controls": {
        "outer_rows": 3000,
        "inner_rows": 8000,
        "row_size": 200,
        "jbs": 262144
      },
      "note": "Nested loop inner join",
      "query_sql": "SELECT u.country, SUM(o.amount) AS total FROM users u JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id) WHERE u.status='active' GROUP BY u.country ORDER BY total DESC"
    },
    {
      "lesson": "full_scan",
      "match": {
        "folded_label": "TABLE SCAN [u] starts=1 rows=3000",
        "short_label": "Table scan [u]"
      },
      "controls": {
        "rows": 3000,
        "row_size": 200,
        "selectivity": 10.0
      },
      "note": "Table scan on u (u)",
      "query_sql": "SELECT u.country, SUM(o.amount) AS total FROM users u JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id) WHERE u.status='active' GROUP BY u.country ORDER BY total DESC"
    },
    {
      "lesson": "bnl",
      "match": {
        "folded_label": "TABLE SCAN [o] starts=1 rows=8000",
        "short_label": "Table scan [o]"
      },
      "controls": {
        "outer_rows": 8000,
        "inner_rows": 8000,
        "row_size": 200,
        "jbs": 262144
      },
      "note": "Table scan on o (o)",
      "query_sql": "SELECT u.country, SUM(o.amount) AS total FROM users u JOIN orders o ON CONCAT('u', o.user_id) = CONCAT('u', u.id) WHERE u.status='active' GROUP BY u.country ORDER BY total DESC"
    }
  ],
  "operator_complexities": [
    {
      "node_id": "n:f4f29c429056",
      "folded_label": "SORT starts=1 rows=5",
      "short_label": "Sort",
      "complexity": {
        "big_o": "O(n log n)",
        "short": "n log n",
        "severity": "medium",
        "rationale": "Filesort: MySQL sorts the output in the server layer. Priority-queue filesort (LIMIT) is not detected today — we report the upper bound.",
        "confidence": "worst_case",
        "learn_more": "filesort"
      }
    },
    {
      "node_id": "n:71b4ad99c5af",
      "folded_label": "NESTED LOOP INNER starts=1 rows=8000",
      "short_label": "Nested loop inner join",
      "complexity": {
        "big_o": "O(n · m)",
        "short": "n · m",
        "severity": "bad",
        "rationale": "Unindexed nested loop: every outer row drives a full scan of the inner side. This is the classic O(n²)-class blow-up.",
        "confidence": "exact",
        "learn_more": "nested_loop_join"
      }
    },
    {
      "node_id": "n:ad535b01566b",
      "folded_label": "TABLE SCAN [u] starts=1 rows=3000",
      "short_label": "Table scan [u]",
      "complexity": {
        "big_o": "O(n)",
        "short": "n",
        "severity": "medium",
        "rationale": "Full table scan: the storage engine returns every row; cost scales with the table size.",
        "confidence": "exact",
        "learn_more": "full_table_scan"
      }
    },
    {
      "node_id": "n:ee0a97ddd30d",
      "folded_label": "TABLE SCAN [o] starts=1 rows=8000",
      "short_label": "Table scan [o]",
      "complexity": {
        "big_o": "O(n)",
        "short": "n",
        "severity": "medium",
        "rationale": "Full table scan: the storage engine returns every row; cost scales with the table size.",
        "confidence": "exact",
        "learn_more": "full_table_scan"
      }
    }
  ]
}

Teach: Operator deep dive