Want to keep learning?

This content is taken from the University of Southampton's online course, Introduction to Linked Data and the Semantic Web. Join the course to learn more.

Ordering query results

For some queries you might want the results to be presented in a particular order. For instance, if your music portal retrieves albums made by the Beatles, using the query given previously, you might want to present these in alphabetical order of title.

This can be done using the keywords ORDER BY, as in the following example:

PREFIX dbpedia: <http://dbpedia.org/resource/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX mo: <http://purl.org/ontology/mo/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>

WHERE { dbpedia:The_Beatles foaf:made ?album .
        ?album a mo:SignalGroup .
        ?album dc:title ?title
ORDER BY ?title

The key element in this query is the ORDER BY component at the end, which stipulates that rows should be presented in alphabetical order of the values in the ?title column.

Note also one other change from the previous example, the use of the asterisk shorthand in the SELECT clause, which asks for all variables in the WHERE clause to be tabulated. This shorthand is not always used, since often the selected variables are a strict subset of those mentioned in the WHERE clause.

Try replacing ORDER BY ?title with ORDER BY DESC(?title), which will present the rows in descending rather than ascending order of title (i.e., ascending is the default).

What exactly do these tables show? The columns, as we have seen, correspond to variables in the query for which tabulation is requested after SELECT, either explicitly by name, or implicitly by the ‘*’ option.

The rows give all variable bindings that match the graph pattern in the WHERE clause. A binding is an assignment of identifiers or literals to the variables which, when instantiated in these patterns, will yield a subgraph of the dataset.

Note that when computing these bindings, the query engine makes the key assumption that variables occurring in more than one pattern are bound to the same resource. In this way it avoids returning a row in which an album is paired with the title of a different album.

We can now get our results ordered by a particular variable. But what if – for example – we only wanted to retrieve a small number of results at a time, or only wanted to know about albums beginning with the letter ‘B’?

This work is a derivative of ‘Using Linked Data Effectively’ by The Open University (2014) and licensed under CC by 4.0 International Licence adapted and used by the University of Southampton. http://www.euclid-project.eu/

Share this article:

This article is from the free online course:

Introduction to Linked Data and the Semantic Web

University of Southampton

Get a taste of this course

Find out what this course is like by previewing some of the course steps before you join: