Skip to content
Advertisement

Postgres Left Join with where condition

I need to left join two tables with a where condition:

time_table
record_table

I need to get all those records which are present under given date range. In the above example, I need those records that lie under range for rid = 2 only. Hence the output for the above query needs to be:

Advertisement

Answer

left join two tables with a where condition

It’s typically wrong to use a LEFT [OUTER] JOIN and then filter with a WHERE condition, thereby voiding the special feature of a LEFT JOIN to include all rows from the left table unconditionally. Detailed explanation:

Put conditions supposed to filter all rows into the WHERE clause (rid = 2), but make conditions to left-join rows from record_table out to be actual join conditions:

As commented, it makes sense to include columns from time_table in the result, but that’s my optional addition.

You also need to be clear about lower and upper bounds. The general convention is to include the lower and exclude the upper bound in time (timestamp) ranges. Hence my use of >= and < above.

Related:

Performance should be no problem at all with the right indexes. You need an index (or PK) on time_table(rid) and another on record_table(date).

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