- You are nesting SELECTs 3 levels deep. From long time personal experience, I have adopted the practice to never go more than 2 levels deep, and that only if absolutely needed and never without reconsidering better alternatives.
- To make things a lot worse, the innermost level is not even a singular query, but contains 3 SELECTs, and even combines them via UNION. UNIONs are dangerous and should be avoided as much as possible.
- Also questionable, concerning the UNIONs: Are ss.id and sf.snapshot_id_name type compatible?
- You are using the same table alias (ss) 3 times, 2 times alone on the deepest nesting level. You are really asking for big trouble here.
- And you do all this only to fetch 1 field from 1 single row. Can you guarantee there will be at least 1, or is an empty result set possible?
Honestly, and even if it might not make you happy, all this is a sign of poor database or application design, or even both. And definetely they don't match very well, to say the least.
If I had to deal with this, I would check/fix/redesign the following issues, in order:
- Type compatibility of ss.id and sf.snapshot_id_name. In theory you should get an error message in case of incompatibility, but in practice you might not, especially considering all the layers you are running through (database/web server etc.). Checking the server logs (if available) might provide some insight, though.
- The table alias 'ss' - avoid using any table alias for more than 1 context.
- The UNIONs. Avoid them - there are always alternatives.
- Try using your target attribute instead of the '*' in your 'SELECT DISTINCT *'. Or, even better, consider removing it altogether, if possible.
- Reduce the query nesting depth.
- Rethink the overall query design.
- As a second-to-last resort, a database redesign might be necessary. Consider optimized helper views, for example.
- Last resort: application redesign.
Hope it helps, good luck, keep us updated, and don't be shy to ask for more help, if needed.
Carsten
P.S.:
On the funny side, I think every reasonable database engine should reply to such a query with a message like
Indignantly, the database shakes its virtual head and asks 'Are you kidding me?'