Skip to content
Advertisement

PostgreSQL subquery COUNT fails when the subquery is joined more than once

I have 2 tables:

Table class:

Table class_event, where I store events related to classes, such as “started” and “ended”.

I need a query the amount of times each class has been started and ended. This works:

But when I do exactly the same to get the amount of ended classes it shows incorrect amounts:

Also, the query takes significantly more time to execute. Is there anything I’m missing?

Advertisement

Answer

Is there anything I’m missing?

Yes, multiple joins multiply rows. It’s exactly the same problem as discussed here:

While you query the whole table it’s typically cleaner and faster to aggregate first and join later. See:

This also avoids the original problem on principle, even for multiple joins – which we don’t need.

NULLS LAST because it’s conceivable that some of the classes have no related rows in table class_event (yet), and the resulting NULL values surely shouldn’t sort on top. See:

About the aggregate FILTER clause:

Aside:

For just a hand full of allowed values, I would consider the data type "char" instead of varchar(1) for event_type. See:

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