{"record":{"id":"00959b67234b880c","repo":"pola-rs/polars","slug":"negative-ordinal-values-are-invalid-for-found","errorCode":null,"errorMessage":"negative ordinal values are invalid for {}; found -{}","messagePattern":"negative ordinal values are invalid for (.+?); found -(.+?)","errorType":"validation","errorClass":"SQLSyntax","httpStatus":null,"severity":"error","filePath":"crates/polars-sql/src/context.rs","lineNumber":567,"sourceCode":"        clause: &str,\n    ) -> PolarsResult<Expr> {\n        match e {\n            SQLExpr::UnaryOp {\n                op: SQLUnaryOperator::Minus,\n                expr,\n            } if matches!(\n                **expr,\n                SQLExpr::Value(ValueWithSpan {\n                    value: SQLValue::Number(_, _),\n                    ..\n                })\n            ) =>\n            {\n                if let SQLExpr::Value(ValueWithSpan {\n                    value: SQLValue::Number(ref idx, _),\n                    ..\n                }) = **expr\n                {\n                    Err(polars_err!(\n                    SQLSyntax:\n                    \"negative ordinal values are invalid for {}; found -{}\",\n                    clause,\n                    idx\n                    ))\n                } else {\n                    unreachable!()\n                }\n            },\n            SQLExpr::Value(ValueWithSpan {\n                value: SQLValue::Number(idx, _),\n                ..\n            }) => {\n                // note: sql queries are 1-indexed\n                let idx = idx.parse::<usize>().map_err(|_| {\n                    polars_err!(\n                        SQLSyntax:","sourceCodeStart":549,"sourceCodeEnd":585,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-sql/src/context.rs#L549-L585","documentation":"In polars-sql, ORDER BY (and similar) clauses accept ordinal literals like ORDER BY 2. A negative number was given as the ordinal reference. The library rejects it with a SQLSyntax error since -1 is not a valid column ordinal.","triggerScenarios":"Executing SQL via SQLContext.execute/execute_registered with e.g. 'SELECT a FROM t ORDER BY -2' — the expr_or_ordinal helper in process_order_by parses a negative numeric literal as the ordinal.","commonSituations":"Writing SQL by hand with a minus typo, or programmatically generating ORDER BY from a signed index variable that happens to be negative.","solutions":["Remove the minus sign or use a positive integer between 1 and the number of selected columns.","If descending order was intended, use ORDER BY 2 DESC instead of a negative ordinal.","Validate/abs() any programmatically supplied ordinal before interpolating it into the SQL string."],"exampleFix":"// before\nctx.execute(\"SELECT a, b FROM t ORDER BY -2\")\n// after\nctx.execute(\"SELECT a, b FROM t ORDER BY 2 DESC\")","handlingStrategy":"validation","validationCode":"ord = -2\nassert isinstance(ord, int) and 1 <= ord <= n_selected_columns, f\"ordinal must be in 1..{n_selected_columns}\"\nsql = f\"SELECT a, b FROM t ORDER BY {ord} DESC\"","typeGuard":"def valid_ordinal(v: int, n_cols: int) -> bool:\n    return isinstance(v, int) and 1 <= v <= n_cols","tryCatchPattern":"try:\n    ctx.execute(sql)\nexcept sqlglot_errors / pl.exceptions.InvalidOperationError as e:\n    raise ValueError(f\"bad ORDER BY ordinal in: {sql}\") from e","preventionTips":["Use column names instead of ordinals in generated SQL","Clamp/validate any index variable before string interpolation","Prefer ORDER BY <col> DESC over negative ordinals for descending order","Lint generated SQL before execution"],"tags":["sql","syntax","ordinal","polars-sql"],"backgroundTag":"invalid-argument-value","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}