This is an English translation of a Japanese blog. Some content may not be fully translated.
📝

SPARQL Query Collection Notes

Notes on SPARQL queries to run against an unfamiliar SPARQL endpoint. Try these on the DBPedia SPARQL endpoint:

http://ja.dbpedia.org/sparql

What Triples Exist at the Endpoint

SELECT *
WHERE {
  ?s ?p ?o .
}
LIMIT 100
OFFSET 0

Number of Triples at the Endpoint

SELECT (COUNT(*) AS ?count)
WHERE {
  ?s ?p ?o .
}

Check Types

SELECT DISTINCT ?type WHERE {
  ?s a ?type
}

Check What Properties Exist

SELECT DISTINCT ?p WHERE {
  ?s a <http://dbpedia.org/ontology/Anime> ;
    ?p ?o.
}

Count Triples Including Named Graphs

SELECT (COUNT(*) AS ?count)
WHERE {
  {
    ?s ?p ?o .
  } UNION {
    GRAPH ?g {
      ?s ?p ?o .
    }
  }
}

Get a List of Named Graphs

SELECT DISTINCT ?g
WHERE {
  GRAPH ?g {
    ?s ?p ?o .
  }
}

Count Records Per Named Graph

SELECT ?g count(?g) WHERE {GRAPH ?g {?s ?p ?o}} GROUP BY ?g

Search Data in a Named Graph

SELECT * WHERE { GRAPH <some-graph> {?s ?p ?o }}

Get a List of Properties

SELECT DISTINCT ?p
WHERE {
  ?s ?p ?o .
}
LIMIT 100

Get Properties Ordered by Frequency of Use

SELECT ?p (COUNT(?p) AS ?count)
WHERE {
  ?s ?p ?o .
}
GROUP BY ?p
ORDER BY DESC(?count)
LIMIT 100

Average Number of Properties per Subject

SELECT (AVG(?count) AS ?average)
WHERE {
  SELECT ?s (COUNT(?p) as ?count)
  WHERE {
    ?s ?p ?o .
  }
  GROUP BY ?s
}

Find Data Containing <search-value> (Search by Subject)

SELECT * { GRAPH ?g { ?s ?p ?o . FILTER( contains(str(?s),'<search-value>') ) }}

Find Data Containing <search-value> (Search by Predicate)

SELECT * { GRAPH ?g { ?s ?p ?o . FILTER( contains(str(?p),'<search-value>') ) }}

Find Data Containing <search-value> (Search by Object)

SELECT * { GRAPH ?g { ?s ?p ?o . FILTER( contains(str(?o),'<search-value>') ) }}

Find Data with Exact Match on Graph

SELECT * { GRAPH <graph> {?s ?p ?o}}

Find Data with Exact Match on Subject

SELECT * { GRAPH ?g {<subject> ?p ?o}}

Find Data with Exact Match on Predicate

SELECT * { GRAPH ?g {?s <predicate> ?o}}

Find Data with Exact Match on Object

SELECT * { GRAPH ?g {?s ?p 'object'}}

References:

Frequently Used SPARQL Sample Queries - Qiita https://qiita.com/hodade/items/30158fba9e943132023f

Introduction to SPARQL http://www.aise.ics.saitama-u.ac.jp/~gotoh/IntroSPARQL.html

Suggest an edit on GitHub