When I add an aggregate function to the SQL query, I get a row of empty values returned. If I take the aggregate function out, I get no rows returned. Why is this? If there is nothing to return, I don’t want a row. In my schema, each envelope can have many transactions. Here is an example of what I’m seeing:
sqlite> SELECT envelopes.*, SUM(transactions.amount) FROM envelopes LEFT OUTER JOIN transactions ON transactions.envelope_id = envelopes.id WHERE envelopes.user_id = 1;
id name user_id income unassigned parent_envelope_id expense created_at updated_at SUM(transactions.amount)
---------- ---------- ---------- ---------- ---------- ------------------ ---------- ---------- ---------- ------------------------
sqlite> SELECT envelopes.* FROM envelopes LEFT OUTER JOIN transactions ON transactions.envelope_id = envelopes.id WHERE envelopes.user_id = 1;
sqlite> select sqlite_version();
sqlite_version()
----------------
3.7.5
sqlite>
I would love to know how to use the SUM() function and still get no row returned when there is no information. I tried grouping by all the columns in the envelopes table and that seemed to fix it, but I’d rather not group if I don’t have to.
You don’t need to group on every column. You just need to group on
envelopes.IDand then join to get the remaining columns. Try this query instead: