Solution modifiers — ORDER BY, LIMIT, DISTINCT

Shape the result set: sort, paginate, de-duplicate, project expressions.

0/2 done

Theory

After the WHERE clause produces a bag of solutions, solution modifiers shape it. They are applied in a fixed logical order:

WHERE → GROUP BY → HAVING → (project & BIND) → ORDER BY → DISTINCT → OFFSET → LIMIT
ModifierEffect
ORDER BY ?x / ORDER BY DESC(?x)Sort ascending / descending
LIMIT nReturn at most n rows
OFFSET kSkip the first k rows (pagination)
DISTINCTRemove duplicate rows (set semantics)
REDUCEDMay remove duplicates — a perf hint, not a guarantee
(expr AS ?v)Project a computed column

Two professional cautions

  1. LIMIT without ORDER BY is non-deterministic. The store may return any n rows, and a different n next time. Stable pagination requires a total ORDER BY (add a tiebreaker like the IRI if your sort key isn't unique).
  2. DISTINCT is computed over the projected columns. Adding a column can resurrect 'duplicates' that differ only in that column. If you de-dupe on ?person but also project ?role, you get one row per (person, role).

Worked example — stable Top-N pagination

Worked example — deterministic 'top 3 masters by student count'.

SELECT ?master (COUNT(?ninja) AS ?students)
WHERE { ?master :teaches ?ninja . }
GROUP BY ?master
ORDER BY DESC(?students) ?master   # tiebreaker keeps paging stable
LIMIT 3

The second ORDER BY key (?master) makes ties deterministic, so OFFSET 3 LIMIT 3 reliably returns the next page rather than a random reshuffle.

Reading in progress · 0 of 2 activities done