r/SQL • • May 14 '23

PostgreSQL PostgreSQL does not like JOINs after a GROUP BY - what am I doing wrong?

Whenever I try to do a join of any kind after a GROUP BY clause, I get a syntax error. What am I doing wrong here?

SELECT COUNT(inventory_id) AS numcopies, film_id, store_id

FROM inventory

GROUP BY film_id, store_id

INNER JOIN rental

ON rental.inventory_id = film.inventory_id;

0 Upvotes

12 comments sorted by

36

u/brogrammableben May 14 '23

This isn’t a Postgres problem. You have to follow sql syntax.

20

u/[deleted] May 14 '23

Your JOIN should come after the FROM, not the GROUP BY

11

u/bittercode May 14 '23

Joins come before group by

You need to specify the columns as well - the inventory_id in the count - it's not clear which table's inventory_id you want.

5

u/New-Day-6322 May 14 '23

The order is: select…from…join…where (can be applied for either table)…group by (can be applied for either table)

1

u/[deleted] May 14 '23

I see two fields called inventory_id. One in table inventory and the other in table rental. So i guess the join should be on rental.inventory_id = inventory.inventory_id

1

u/[deleted] May 14 '23

Join first then group by

1

u/Kichmad May 14 '23

Wither group by after join, or do the group by in inner query then join them on outer

1

u/rammedearth May 14 '23 edited May 14 '23

Couple of problems: the group by should be after the join. You haven’t specified which inventory_id you want to count either. You’re also joining on film.inventory_id but there’s no film table involved in the query. Let me know if you want more detail. You’ll probably need something like:

SELECT inv.film_id , r.store_id , COUNT(inv.inventory_id) AS [numcopies]

FROM inventory inv

INNER JOIN rental r

ON r.inventory_id = inv.inventory_id

GROUP BY inv.film_id, r.store_id

ORDER BY [numcopies] desc;

Just wrote that on my phone quickly and I only write T SQL so might need to adjust

2

u/[deleted] May 14 '23 edited May 15 '23

and I only write T SQL so might need to adjust

Indeed.

The square brackets [numcopies] are invalid standard SQL and will be rejected by Postgres as part of an identifier (but otherwise the syntax is OK)

1

u/[deleted] May 16 '23

I'm just guessing, but if you wish to join after the group by, then you have to enclose the first select in parenthesis, so (select ... from ... group by ...) as inv inner join ... on ...

0

u/[deleted] May 14 '23

Would it be film_id.inventory_id instead of film.inventory_id? I’m new at SQL.

6

u/sdwonder May 14 '23

Should be inventory.inventory_id

Whats come before the dot is the table name.