pola-rs/polars · error · SQLSyntax
negative ordinal values are invalid for
Error message
negative ordinal values are invalid for {}; found -{} What it means
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.
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.
Example fix
// before
ctx.execute("SELECT a, b FROM t ORDER BY -2")
// after
ctx.execute("SELECT a, b FROM t ORDER BY 2 DESC") Defensive patterns
Strategy: validation
Validate before calling
ord = -2
assert isinstance(ord, int) and 1 <= ord <= n_selected_columns, f"ordinal must be in 1..{n_selected_columns}"
sql = f"SELECT a, b FROM t ORDER BY {ord} DESC" Type guard
def valid_ordinal(v: int, n_cols: int) -> bool:
return isinstance(v, int) and 1 <= v <= n_cols Try / catch
try:
ctx.execute(sql)
except sqlglot_errors / pl.exceptions.InvalidOperationError as e:
raise ValueError(f"bad ORDER BY ordinal in: {sql}") from e Prevention
- 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
When it happens
Trigger: 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.
Common situations: Writing SQL by hand with a minus typo, or programmatically generating ORDER BY from a signed index variable that happens to be negative.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- only a single SQL query string is accepted for adbc, got a
- 'pre_execution_query' is only supported in connectorx…
- statements are not valid 'read' queries
- {response["result"]}
- unrecognised frame type
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/00959b67234b880c.
Report an issue: GitHub.
Appendix: source
Thrown at crates/polars-sql/src/context.rs:567
clause: &str,
) -> PolarsResult<Expr> {
match e {
SQLExpr::UnaryOp {
op: SQLUnaryOperator::Minus,
expr,
} if matches!(
**expr,
SQLExpr::Value(ValueWithSpan {
value: SQLValue::Number(_, _),
..
})
) =>
{
if let SQLExpr::Value(ValueWithSpan {
value: SQLValue::Number(ref idx, _),
..
}) = **expr
{
Err(polars_err!(
SQLSyntax:
"negative ordinal values are invalid for {}; found -{}",
clause,
idx
))
} else {
unreachable!()
}
},
SQLExpr::Value(ValueWithSpan {
value: SQLValue::Number(idx, _),
..
}) => {
// note: sql queries are 1-indexed
let idx = idx.parse::<usize>().map_err(|_| {
polars_err!(
SQLSyntax:View on GitHub (pinned to fe841f959e)