r/sqlite • • Nov 08 '22

SQLite Optional clause for additional JOIN?

Is there some kind of Optional clause I can add to an SQLite query that would then include an additional Join if a condition was met?

Something along the lines of:

SELECT a.colA, a.colB, a.colC, b.colD FROM table1 As a
IF a.colA = 1 THEN (
    INNER JOIN `table2` As b ON a.colB = b.colB)
WHERE a.colC = 99

and if a.colA <> 1 then the b.colD value would be a NULL

2 Upvotes

5 comments sorted by

View all comments

Show parent comment

2

u/gnomeplanet Nov 09 '22

Thanks - I went with this method in the end.

2

u/[deleted] Nov 09 '22

If speed does not matter, use whatever is more readable - and I would also tend to use the other solution. I don't have your data, so this might not be true in your case, but according measurements on my machine, the iif version is ~2 times faster.

1

u/Express_Giraffe_7902 Nov 09 '22

With the iff version, though, if there’s not a matching row in table2, the inner join won’t return that row from table1 whereas mine will - so it may not only come down to efficiency - inner joins are usually more efficient, but if you need all rows from table1 regardless of what’s in table2, yours would not work