examples · sql · 8 / 13 · limited
8. LIMIT (ORDER BY is roadmap)
← SQL examplesheads up
ORDER BY through the SQL translator is on the roadmap. The executor has a Sort operator but it isn't wired through SQL yet. For sorted results today, fetch a wider LIMIT and sort in your app.
what works today
LIMIT caps the result count. Combined with a WHERE filter, you can fetch a bounded set of matching rows.
the request - just LIMIT
POST /v1/tenants/:t/sql
# LIMIT works. ORDER BY through /sql is on the roadmap.
curl -X POST "https://$OC_HOST/v1/tenants/$OC_TENANT/sql" \
-H "Authorization: Bearer $OC_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"sql": "SELECT id, amount_cents FROM shop.orders WHERE amount_cents > 0 LIMIT 3"
}' workaround - fetch + sort client-side
fetch a wider LIMIT, then sort in your app
# Fetch a wider LIMIT, sort in Python.
result = db.sql("SELECT id, amount_cents FROM shop.orders WHERE amount_cents > 0 LIMIT 50")
sorted_rows = sorted(result.rows, key=lambda r: r["amount_cents"], reverse=True)[:3]
for row in sorted_rows:
print(row["id"], row["amount_cents"])// Fetch a wider LIMIT, sort in TypeScript.
const result = await db.sql(`SELECT id, amount_cents FROM shop.orders WHERE amount_cents > 0 LIMIT 50`);
if (result.kind === "select") {
const sorted = [...result.rows]
.sort((a, b) => Number(b.amount_cents) - Number(a.amount_cents))
.slice(0, 3);
console.log(sorted);
}// Fetch a wider LIMIT, sort in Go.
result, _ := db.SQL(ctx, `SELECT id, amount_cents FROM shop.orders WHERE amount_cents > 0 LIMIT 50`)
sort.Slice(result.Rows, func(i, j int) bool {
return result.Rows[i]["amount_cents"].(float64) > result.Rows[j]["amount_cents"].(float64)
})
top3 := result.Rows[:3] when this workaround stops working
Fetch-then-sort is fine for small result sets (hundreds of rows). For "top 10 of a million", it doesn't scale - you'd be moving the entire candidate set over the wire. If that's your workload, use Ask (which has Sort wired through), or contact us if it's a blocker - ORDER BY in SQL is high-priority.