%META:TOPICPARENT{name="VirtTipsAndTricksGuide"}% ---+ Running an aggregate like COUNT over multiple columns in SPARQL 1.1 SPARQL 1.1 added aggregates, but [[https://www.w3.org/TR/sparql11-query/#rAggregate][it only permits them to be run over a single column, or over all columns in the result set]]. For instance, this query gets a [[http://live.dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&qtxt=SELECT+%0D%0A+++DISTINCT++%3Fs+%3Fp+%3Fo+%0D%0AWHERE%0D%0A++%7B+%0D%0A++++VALUES+%3Fs+%7B+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FTreaty_of_Bern%3E+%7D+%0D%0A++++%3Fs+%3Fp+%3Fo%0D%0A++++OPTIONAL+%7B+%3Fs+a+%3Ftype+%7D+.%0D%0A++++FILTER+%28+BOUND+%28+%3Ftype+%29+%29+.%0D%0A++%7D%0D%0A&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&signal_void=on&signal_unconnected=on&run=+Run+Query+][large number of rows]], and you might want to know how many without running the full query -- SELECT DISTINCT ?s ?p ?o WHERE { VALUES ?s { } ?s ?p ?o OPTIONAL { ?s a ?type } . FILTER ( BOUND ( ?type ) ) . } A simple COUNT(DISTINCT *) includes all variables bound in the WHERE clause -- which here means a Cartesian result set, [[http://live.dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&qtxt=SELECT+%0D%0A+++%28+COUNT%28+DISTINCT+*+%29+AS+%3FHowManyTriples+%29%0D%0AWHERE%0D%0A++%7B+%0D%0A++++VALUES+%3Fs+%7B+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FTreaty_of_Bern%3E+%7D+%0D%0A++++%3Fs+%3Fp+%3Fo%0D%0A++++OPTIONAL+%7B+%3Fs+a+%3Ftype+%7D+.%0D%0A++++FILTER+%28+BOUND+%28+%3Ftype+%29+%29+.%0D%0A++%7D%0D%0A&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&signal_void=on&signal_unconnected=on&run=+Run+Query+][multiplying the count]] of DISTINCT ?s ?p ?o by the count of DISTINCT ?type. A workaround is to wrap the aggregate around a sub-query. [[http://live.dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&qtxt=SELECT+%0D%0A+++%28+COUNT%28+*+%29+AS+%3FHowManyTriples+%29%0D%0AWHERE%0D%0A++%7B+%0D%0A++++%7B+SELECT+%0D%0A+++++++++DISTINCT++%3Fs+%3Fp+%3Fo+%0D%0A++++++WHERE%0D%0A+++++++%7B+%0D%0A+++++++++VALUES+%3Fs+%7B+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FTreaty_of_Bern%3E+%7D+%0D%0A+++++++++%3Fs+%3Fp+%3Fo%0D%0A+++++++++OPTIONAL+%7B+%3Fs+a+%3Ftype+%7D+.%0D%0A+++++++++FILTER+%28+BOUND+%28+%3Ftype+%29+%29+.%0D%0A+++++++%7D%0D%0A++++%7D%0D%0A++%7D%0D%0A%0D%0A%0D%0A&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=30000&signal_void=on&signal_unconnected=on&run=+Run+Query+][The query below returns an accurate count]] of DISTINCT ?s ?p ?o rows. SELECT ( COUNT( DISTINCT * ) AS ?HowManyTriples ) WHERE { { SELECT DISTINCT ?s ?p ?o WHERE { VALUES ?s { } ?s ?p ?o OPTIONAL { ?s a ?type } . FILTER ( BOUND ( ?type ) ) . } } }