Skip to content

SQL Select or join two separate subsets of a table

Say I have a table Element in my SQL Server database with, we’ll suppose, nothing other than an Id column.

I also have tables Foo and Bar, which each have a many-to-many relationship with Element, such as I have some tables FooElement (FkId INT, FkFoo INT) and BarElement (FkId INT, FkBar INT) tables to handle the relationship. Note that Elements can be either linked to a Foo, a Bar, both or none.

If I want to find which Elements are linked to a Foo, I can easily find them using

And I can easily do the same for BarElements.

Here is my question: what is the best way to find which Elements are either linked to a Foo or a Bar? Below is my current solution, but I was wondering if there was a better option, in particular performance-wise, as all three tables, especially Element will be extremely packed with data.

Advertisement

Answer

I would use exists:

With indexes on FooElement(FkId) and BarElement(FkId), I would expect this to have comparable or better performance than most alternatives.

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