When to use SQL sub-queries versus a standard join? -


i working on rewriting poorly written sql queries , over-utilizing sub-queries. looking best-practices regarding use of sub-queries.

any appreciated.

subqueries fine unless dependent subqueries (also known correlated subqueries). if using independent subqueries , using appropriate indexes should run quickly. if have dependent subquery might run performance problems because dependent subquery typically needs run once each row in outer query. if outer query has 1000 rows, subquery run 1000 times. on other hand independent subquery typically needs evaluated once.

if you're not sure meant subquery being dependent or independent here's rule of thumb - if can take subquery, remove context, run it, , result set it's independent subquery.

if syntax error because refers tables outside of subquery dependent subquery.

the general rule of course has few exceptions. example:

  • many optimizers can take dependent subquery , find way run efficiently join. example not exists query might result in anti join query plan, not slower writing query join.
  • mysql has bug independent subquery inside in expression incorrectly identified dependent subquery , suboptimal query plan used. apparently fixed in newest versions of mysql.

if performance issue measure specific queries , see works best you.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -