{"record":{"id":"4e9b68c3243b516f","repo":"dgraph-io/dgraph","slug":"variable-not-found-in-math","errorCode":null,"errorMessage":"Variable not found in math","messagePattern":"Variable not found in math","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"dql/math.go","lineNumber":351,"sourceCode":"\tif valueStack.empty() {\n\t\t// This happens when we have math(). We can either return an error or\n\t\t// ignore. Currently, let's just ignore and pretend there is no expression.\n\t\treturn nil, false, errors.Errorf(\"Empty () not allowed in math block.\")\n\t}\n\n\tif valueStack.size() != 1 {\n\t\treturn nil, false, errors.Errorf(\"Expected one item in value stack, but got %d\",\n\t\t\tvalueStack.size())\n\t}\n\tres, err := valueStack.pop()\n\treturn res, false, err\n}\n\nfunc (t *MathTree) subs(vmap varMap) error {\n\tif strings.HasPrefix(t.Var, \"$\") {\n\t\tva, ok := vmap[t.Var]\n\t\tif !ok {\n\t\t\treturn errors.Errorf(\"Variable not found in math\")\n\t\t}\n\t\tvar err error\n\t\tt.Const, err = parseValue(va)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.Var = \"\"\n\t}\n\tfor _, i := range t.Child {\n\t\tif err := i.subs(vmap); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// debugString converts mathTree to a string. Good for testing, debugging.\n// nolint: unused","sourceCodeStart":333,"sourceCodeEnd":369,"githubUrl":"https://github.com/dgraph-io/dgraph/blob/759e242be62c91f8d084da06ad0c8d21256d9c07/dql/math.go#L333-L369","documentation":"MathTree.subs substitutes query variables (names starting with `$`) in a math expression tree with their concrete values using the provided varMap. This error is thrown when a `$var` referenced in a math() block is not present in the variable map, i.e. the variable was never defined by an earlier query clause. The library cannot evaluate the expression without it, so it fails fast.","triggerScenarios":"A DQL query contains `math($someVar ...)` but no prior query node defines `someVar as *someVar` (variable not bound), so vmap lookup for \"$someVar\" misses.","commonSituations":"Typos in variable names (case mismatch: `$count` vs `$Count`), restructuring a query and removing the clause that emitted the variable, or running a sub-query standalone that depended on variables from a parent query.","solutions":["Define the variable before the math block, e.g. add a clause like `countOfFriends as count(friend)` so `$countOfFriends` exists in the var map.","Check for case/typo mismatches between the `$name` used in math() and the name emitted by the defining clause.","If the query was split into parts, re-join it so variable-producing clauses execute in the same request.","Wrap the math expression in a guard (e.g. math($var == nil ? 0 : ...)) only if the version supports nil checks; otherwise provide a default value clause."],"exampleFix":"// before\n{\n  me(func: uid(0x1)) {\n    val(score) // $score never defined\n    f as math($score * 2)\n  }\n}\n// after\n{\n  var(func: uid(0x1)) {\n    friend {\n      score as math(1)\n    }\n    s as sum(val(score))\n  }\n  me(func: uid(0x1)) {\n    f as math($s * 2)\n  }\n}","handlingStrategy":"validation","validationCode":"func hasVarDef(query, varName string) bool {\n    // varName like \"score\"; look for 'as ...' clause producing it before use\n    return strings.Contains(query, varName+\" as \") || strings.Contains(query, \" as \"+varName)\n}\n// check every $var in math() has a corresponding 'X as ...' definition","typeGuard":null,"tryCatchPattern":"err := runQuery(txn, q)\nif err != nil && strings.Contains(err.Error(), \"Variable not found in math\") {\n    return fmt.Errorf(\"query variable used in math() is not defined by any prior clause: %w\", err)\n}","preventionTips":["Define every $variable with an 'as' clause earlier in the same query.","Keep variable names consistent (Dgraph variables are case-sensitive).","After refactoring queries, grep for remaining $vars and verify their defining clauses still exist."],"tags":["dql","query-variable","math-expression"],"backgroundTag":"undefined-query-variable","analyzedSha":"759e242be62c91f8d084da06ad0c8d21256d9c07","analyzedAt":"2026-09-01T14:42:12.034Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}