Skip to content
Advertisement

Sum of two counts from one table with additional data from another table

I have two tables as follows:

I want to get the sum of two counts, which are the number of true values in col_a and number of true values in col_b. I want to group that data by user_id. I also want to join Table B and get the name of each user. The result would look like this:

So far I got the total sum with the following query:

However, I’m not sure how to proceed with grouping these counts by user_id.

Advertisement

Answer

Something like this is typically fastest:

While fetching all rows, aggregate first, join later. That’s cheaper. See:

The aggregate FILTER clause is typically fastest. See:


Often, you want to keep total counts of 0 in the result. You did say:

get the name of each user.

count(col_a OR NULL) is an equivalent alternative, shortest, and still fast. (Use the FILTER clause from above for best performance.)
The LEFT JOIN keeps all rows from "TABLE_B" in the result.
COALESCE() return 0 instead of NULL for the total count.


If col_a and col_b have only few true values, this is typically (much) faster – basically what you had already:

Especially with (small in this case!) partial indexes like:

Aside: use legal, lower-case unquoted names in Postgres to make your like simpler.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement