LEFT JOIN alternative

97 views
Skip to first unread message

Hugo Larson

unread,
Nov 14, 2021, 4:45:49 AM11/14/21
to Firebird-support
Hi,

Consider this SQL:

select * from PRODUCT p
left join PRODUCTCATEGORY pc on p.CATEGORY_ID = pc.ID

I have LEFT join to include any PRODUCT that does not have a belonging (orphan) PRODUCTCATEGORY.

After a while we notices that LEFT JOIN is extremely slow.
Is there a clever way fetch orphan PRODUCT without LEFT JOIN?

The actual SQL is more complicated.

Thanks,
Hugo

Ariel Álvarez

unread,
Nov 14, 2021, 7:31:10 AM11/14/21
to firebird...@googlegroups.com
Try:
Select * from product p where not exists (select 1 from productcategory pc where pc.id=p.category_id)

Regards,
Ariel

--
You received this message because you are subscribed to the Google Groups "firebird-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email to firebird-suppo...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/firebird-support/1240736290.404201.1636883101039%40mail.yahoo.com.

Svein Erling Tysvær

unread,
Nov 14, 2021, 2:46:54 PM11/14/21
to firebird...@googlegroups.com
I only know older versions of Firebird (still on 2.5), but there I always make sure to put inner joins before left joins if possible, i.e. I normally write select * from PRODUCTS p join SALES s left join PRODUCTCATEGORY pc and avoid writing select * from PRODUCTS p left join PRODUCTCATEGORY pc join SALES s, since the optimizer doesn't work equally well with joins after the first outer join (there are a few exceptions).

Though to only answer your original question, yes, it is possible to have subselects as long as they produce single results, select *, (select pc.NAME from PRODUCTCATEGORY pc where p.ID =pc.CATEGORY_ID) as CATEGORY_NAME from PRODUCTS p

Hth,
Set

--

Hugo Larson

unread,
Nov 15, 2021, 4:34:30 AM11/15/21
to firebird...@googlegroups.com
I'm on FB 2.5 too :)
You mean that LEFT JOIN should be last?

Reply all
Reply to author
Forward
0 new messages