Solution modifiers — DISTINCT, ORDER BY, LIMIT, OFFSET
Modifiers shape the list of solutions after the pattern has matched. They run inside pgrdf.sparql(), so there's no need to wrap the call in SQL DISTINCT, ORDER BY or LIMIT.
Examples use the sample data.
| Modifier | Effect |
|---|---|
DISTINCT | Remove duplicate solutions. |
REDUCED | Allow duplicates to be removed. |
ORDER BY ?v, ASC(?v), DESC(?v) | Sort. Numbers sort by value, strings alphabetically. Several keys and expressions are allowed. |
LIMIT n | Return at most n solutions. |
OFFSET n | Skip the first n solutions. |
Paging
sql
SELECT * FROM pgrdf.sparql($$
SELECT DISTINCT ?p
WHERE { ?s ?p ?o }
ORDER BY ?p
LIMIT 2 OFFSET 1
$$);
-- {"p": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}
-- {"p": "http://xmlns.com/foaf/0.1/knows"}Sorting
sql
SELECT * FROM pgrdf.sparql($$
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/>
SELECT ?name ?age
WHERE { ?p foaf:name ?name ; ex:age ?age }
ORDER BY DESC(?age)
$$);
-- {"age": "41", "name": "Bob"}
-- {"age": "34", "name": "Alice"}
-- {"age": "29", "name": "Carol"}Numeric values sort as numbers, so an age of 9 comes before 29, even though the values reach you as strings.
Sort keys can be expressions, and you can give several:
sql
SELECT * FROM pgrdf.sparql($$
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?n WHERE { ?p foaf:name ?n }
ORDER BY DESC(STRLEN(?n)) ?n
$$);
-- {"n": "Alice"}
-- {"n": "Carol"}
-- {"n": "Bob"}DISTINCT with an expression sort key
DISTINCT (or REDUCED) together with ORDER BY an expression is refused with an error. Compute the key with BIND, then sort by the variable:
sql
SELECT * FROM pgrdf.sparql($$
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT DISTINCT ?name ?key
WHERE { ?p foaf:name ?name BIND(LCASE(?name) AS ?key) }
ORDER BY DESC(?key)
$$);
-- {"key": "carol", "name": "Carol"}
-- {"key": "bob", "name": "Bob"}
-- {"key": "alice", "name": "Alice"}Top-N inside a subquery
A subquery can carry its own ORDER BY and LIMIT. Here: the name of the oldest person.
sql
SELECT * FROM pgrdf.sparql($$
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/>
SELECT ?name ?age
WHERE { ?p foaf:name ?name .
{ SELECT ?p ?age WHERE { ?p ex:age ?age } ORDER BY DESC(?age) LIMIT 1 } }
$$);
-- {"age": "41", "name": "Bob"}