Search code examples
sparqldbpedia

Missing value in Sparql due to where clause


I have a query which return no records because there isn't a thumbnail in the where clause

PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource/>

    SELECT *
    WHERE { 
        dbpedia:Nancy_Mairs dbpedia-owl:abstract ?abstract; dbpedia-owl:thumbnail ?thumbnail .
    }
    LIMIT 1

If I miss the second condition out it returns a record

PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource/>

    SELECT *
    WHERE { 
        dbpedia:Nancy_Mairs dbpedia-owl:abstract ?abstract
    }
    LIMIT 1

Rather than say if the first returns nothing then run the second can I do it all in one go and return an empty thumbnail if there is none?


Solution

  • To expand a bit on Stanislav's comment, you can use the OPTIONAL keyword to describe graph patterns that are... well... optional. If there is a solution to this pattern, it will be returned with the rest of the solution; otherwise, only the "mandatory" part of the pattern will be returned.

    SELECT * WHERE { 
        dbpedia:Nancy_Mairs dbpedia-owl:abstract ?abstract
        OPTIONAL {
            dbpedia:Nancy_Mairs dbpedia-owl:thumbnail ?thumbnail
        }
    }
    

    If you want to factor out the repetition of dbpedia:Nancy_Mairs, you can use the BIND keyword:

    SELECT * WHERE {
        BIND(dbpedia:Nancy_Mairs AS ?topic)
    
        ?topic dbpedia-owl:abstract ?abstract
        OPTIONAL {
            ?topic dbpedia-owl:thumbnail ?thumbnail
        }
    }