Search code examples
formatsparqlinstancesubclass

Listing instances next to each class in SPARQL query


I want to write a SPARQL query that will give me a list that has all the subclasses of a specific class and all the instances of each subclass. E.g., if I have the class Animal with subclasses Dog and Cat and instances of Dog: Fido, Bowser and Cat: Fluffy, Whiskers I want the output to look like:

Dog  Fido Bowser

Cat  Fluffy Whiskers

I have a query to get all the instances of each subclass:

SELECT ?class_label ?instance_label
WHERE {?anmlclass rdfs:subClassOf ex:Animal;
                 rdfs:label ?class_label.
        ?anml a ?anmlclass;
               rdfs:label ?instance_label.}

But this gives output like:

Dog Fido

Dog Bowser

Is there a way to format the result so that all the instances are shown in the same row as the relevant class?


Solution

  • From a comment by UninformedUser:

    SELECT ?class_label (group_concat(?instance_label; separator=", ") as ?instances)
    WHERE {
      ?anmlclass
          rdfs:subClassOf ex:Animal ;
          rdfs:label      ?class_label .         
    
      ?anml
          a          ?anmlclass ;               
          rdfs:label ?instance_label 
    }
    GROUP BY ?anmlclass