Fork me on GitHub

I want todo a count on the number of prices in a database, this works fine using (count ?prices) except when there are none then I get no data returned from the query how can i handle this so 0 is returned ?


Not sure how to achieve that within the query itself, but you could wrap the query in an or expression: (or (my-query db) 0)


I think the issue with that is the query returns multiple fields, I always want the other fields only the aggregate to be 0 and not remove the other data


unless you mean i can use the or in the middle of the where conditions ?


Ah I think I misunderstood your original question. Could you post an example of the query?


(d/q '[:find ?e ?i ?n ?slug  (count ?eid2)
                :keys eid id product/name product/slug ?prices
                :in $ ?product-id
                [?e :product/id ?i]
                [?eid2 :price/product ?prices]
                [?e :product/name ?n]
                [?e :product/slug ?slug]] @conn product-id)


That's what i currently have, I can split it out in this situation but Its something that would be good to know how to achieve


Is that ?eid2 supposed to fetch all prices in the DB? It doesn't seem to be related to any other clause in the query. If so, I'd just do a separate query for it (queries are cheap, don't need to join them into one big one). Otherwise, if you want to fetch something that may or may not exist (but want to ensure it's absence does not remove it from the result set), you want to pull that info, not query it. A pull would work like a maybe, but a where clause works like a must.


You can also consider, if this kind of aggregate should not be done as a separate query (or even just using the indexes directly, if it's a simple relationship).


And just a friendly reminder: whenever working with aggregates, don't forget to ask yourself if you need :with to make sure the results are accurate. (If you're aggregating on eids, this won't be an issue).