# The query parameter that reaches SQL
<!--
ref: @protocol/the-query-parameter-that-reaches-sql
tags: [security, sql-injection, pagination, sorting, validation, chokepoint]
triggers: [adding or reviewing a list endpoint with sort or pagination, a caller-supplied string is about to be interpolated into SQL, validating query parameters, an ORDER BY built from a request]
trigger_prompt: When a query-string parameter reaches SQL — a sort property interpolated into ORDER BY, or page/size interpolated into LIMIT/OFFSET — these are the three defects and the chokepoint fix.
version: 2
updated_at: 2026-10-15T20:00:53.733Z
-->

A list endpoint takes `?page=`, `?size=` and `?sort=`. Two of those are VALUES, which a
driver can bind. The third is an IDENTIFIER, which it cannot — a column name is part of the
statement, so `ORDER BY $1` does not work and every paginator in every framework
interpolates that string. Interpolating it is not the bug. Interpolating it **unchecked**
is, and the shape hides well: the code reads like a formatting concern, and the type
signature says the values are numbers.

Three defects, all found in one small pagination helper, all reachable from a query string.

## 1 — the sort property reaches ORDER BY

`ORDER BY` cannot return a value, which is why this gets filed as cosmetic and left. It
orders by one, and that is enough:

- `?sort=(select password_hash from users limit 1)` — the page's ORDER changes with another
  table's content. A boolean oracle, a page at a time.
- `?sort=(select 1 from pg_sleep(10))` — ORDER BY takes a function call. A timing oracle.
- Stacked statements usually are NOT available: a Postgres driver switches to the extended
  protocol as soon as the statement carries any bound parameter, which refuses multiple
  statements. So expect read and delay, not DROP — and do not let the absence of DROP make
  it a low finding.

A comma looks like a defence when the parser splits `property,direction` on commas. It is
not: `?sort=a&sort=b` arrives as an array, and the clause joins the parts with commas.

## 2 — the transform that reads like a sanitiser

Between the parameter and the clause there is often a naming transform, and it is the reason
nobody looks twice:

```js
const snakeCase = (s) => s.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/^_/, '');
```

It mangles uppercase, so a payload is written in lowercase and the transform is a no-op on
it. Quotes, parens, spaces, semicolons and operators pass through untouched. **Any transform
standing between caller input and a statement will be mistaken for a check** — by the next
reader, and by the person who put it there.

## 3 — `x || default` does not guard a query-string number

The same helper validated the other two parameters like this:

```js
page: Math.max(0, pageable.page || 0)
```

`page` is typed `number` and is a STRING at runtime on any route that binds the whole query
object. `'abc'` is truthy, so the `|| 0` never fires, and `Math.max(0, 'abc')` is **NaN** —
which is then interpolated into `LIMIT … OFFSET …` as the literal `NaN` and comes back as a
database syntax error. `?page=1e999` is `Infinity` by the same path.

The quiet half: on the happy path the strings survive validation unchanged and are handed
back to the caller inside the page object, where ITS helpers do arithmetic on them —
`page === 0` is false for `'0'`, and `page + 1` is `'01'`.

## What to do

**Validate the identifier by SHAPE, at the chokepoint.** One regex —
`/^[A-Za-z_][A-Za-z0-9_]*$/` — and a 400 otherwise. Nothing with a quote, paren, space,
comma, semicolon or operator can reach the clause after that, and shape is all a raw-SQL
paginator can check, because it does not know the columns.

**Put it in the shared parser, not at the call sites.** Count them first: a tree with three
paginators (an ORM `order` object, a query builder's `addOrderBy`, a raw string append) has
them written three different ways, and a project cloned from it adds the fourth. The parser
they all call is the only place the check lands once.

**Then check the NAME where the names are known.** An ORM path has entity metadata, so an
unknown column can be a 400 instead of the framework's own 500 — which matters most on a
public read route, where a typo in a query string was a 500 from a published page. A raw
path has no metadata and gets shape validation only; that is the division of labour, not a
gap.

**Resolve the sort BEFORE any statement runs.** A paginator that runs its count query first
and parses the sort second lets a refused request still cost a statement — and, for a blind
oracle, the count query is a signal too.

**Coerce the numbers, falling back rather than coercing to zero.** `Number('')` is 0, so an
empty `?size=` would mean a one-row page; absent, empty and non-numeric all mean "not said".
Return finite integers and let the clamps run on those. Then **re-validate inside the
function that interpolates them**: every caller validating first is a convention, not a
guarantee, and an idempotent validator makes the second call free.

## The general rule

An identifier interpolated into a statement needs a check at the point of interpolation,
not a convention upstream of it. Values are the driver's job; identifiers are yours. And a
helper named `validate` that returns its input unchanged for a whole class of inputs is
worse than no helper, because every call site reads as already handled.

---

*Related: `@content/web/github/2026-11-29-convex-backend-skill-issue-64` · `@content/youtube/tiago-forte/i-connected-claude-to-everything-then-i-saw-the-gap` · `@content/youtube/nate-herk/i-deleted-all-my-claude-skills-and-claude-got-smarter` · `@content/youtube/starter-story/my-apps-make-36k-month-watch-me-build-one-in-17-minutes` · `@content/youtube/indy-dev-dan/mac-mini-agents-openclaw-is-a-nightmare-use-these-skills-instead`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*