Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgresql query where statement positions

I have two tables that I want to join. It works without where conditions. After adding where conditions, I got syntax error near a (where I give table1 an alternative name). From my understanding, the syntax looks correct?

My query

select * from table1 where date >= '2020-10-01' and date <= '2020-10-31' a
  left join table2 b where registered >= '2020-10-01' and registered <= '2020-10-31' b
      on a.id = cast(b.id as varchar)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Some issues:

  • where goes after all tables (and their join conditions)
  • aliases go immediately after the table name

Applying these two corrections and some formatting:

select *
from table1 a
left join table2 b on a.id = cast(b.id as varchar)
  and registered >= '2020-10-01' and registered <= '2020-10-31'
where date >= '2020-10-01' and date <= '2020-10-31'

Conventionally, join conditions that describe access to joined rows (typically the keys) are coded first, then filtering conditions (ones involving only columns in the joined table) are coded last.


Which can be slightly simplified using between to:

select *
from table1 a
left join table2 b on a.id = cast(b.id as varchar)
  and registered between '2020-10-01' and '2020-10-31'
where date between '2020-10-01' and '2020-10-31'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading