Bug or mistake? GROUP BY returns empty element

Whenever I use the GROUP BY clause in a query that gets no results, I get an empty item as a result, instead of 0 items. This has been happening since old Stardog versions. Is this a bug?

SELECT distinct ?s
WHERE { ?s a rdf:Notexists . 
      }  GROUP BY ?s

No, it's the intended behaviour (per 18.5.1 iirc). Here's one of the SPARQL DAWG tests specifically for it: https://www.w3.org/2009/sparql/docs/tests/summary.html#aggregates-agg-empty-group

This result set

<results><result></result></results>

means one empty binding set.

You can use something like HAVING to filter out the empty groups.

Cheers,
Pavel

I see, thanks. It is very confusing and counter intuitive to expect one result when there is actually nothing to return.... Not sure why they decided this way, since it does not add value and creates extra complications.

How could I filter results in something like here?

SELECT distinct ?s ?title
WHERE { ?s a ex:Book .
        OPTIONAL(?s ex:title ?title)
      }
GROUP BY ?s ?title
HAVING (?s)
ORDER BY ...

This works if I only request ?s, but not any other optional value. I just need to "simulate" the effect of 0 results if the query returned effectively 0 results.

What's the intention of using both DISTINCT and GROUP BY for the same keys? GROUP BY without aggregates is basically de-duplication, except for this corner case.

None in this case, but does it have any effect? The actual query has a SAMPLE, that is the reason of the GROUP BY:

SELECT ?s ?title (SAMPLE(?cover_) as ?cover)
WHERE { ?s a ex:Book .
        OPTIONAL{ ?s ex:title ?title }
        OPTIONAL{ ?s ex:cover ?cover_ }
      }
GROUP BY ?s ?title
HAVING (?s)
ORDER BY ...

Alright, for this query you can use HAVING(BOUND(?s)). ?s can be unbound only if your result is the (single) empty group tuple.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.