In which sequence are queries and sub-queries executed by the SQL engine?

后端 未结 5 1503
轻奢々
轻奢々 2020-11-29 06:40

Hello I made a SQL test and dubious/curious about one question:

In which sequence are queries and sub-queries executed by the SQL engine?

th

相关标签:
5条回答
  • 2020-11-29 06:48

    It's usually depends from your DBMS, but ... I think second answer is more plausible. Prime query usually can't be calculated without sub query results.

    0 讨论(0)
  • 2020-11-29 06:58

    The SQL engine tries to optimise the order in which (sub)queries are executed. The part deciding about that is called a query optimizer. The query optimizer knows how many rows are in each table, which tables have indexes and on what fields. It uses that information to decide what part to execute first.

    0 讨论(0)
  • 2020-11-29 06:58

    If you want something to read up on these topics, get a copy of Inside SQL Server 2008: T-SQL Querying. It has two dedicated chapters on how queries are processed logically and physically in SQL Server.

    0 讨论(0)
  • 2020-11-29 07:06

    Option 4 is close.

    SQL is declarative: you tell the query optimiser what you want and it works out the best (subject to time/"cost" etc) way of doing it. This may vary for outwardly identical queries and tables depending on statistics, data distribution, row counts, parallelism and god knows what else.

    This means there is no fixed order. But it's not quite "on the fly"

    Even with identical servers, schema, queries, and data I've seen execution plans differ

    0 讨论(0)
  • 2020-11-29 07:09

    I think answer 4 is correct. There are a few considerations:

    type of subquery - is it corrrelated, or not. Consider:

    SELECT *
    FROM   t1
    WHERE  id IN (
                 SELECT id
                 FROM   t2
                )
    

    Here, the subquery is not correlated to the outer query. If the number of values in t2.id is small in comparison to t1.id, it is probably most efficient to first execute the subquery, and keep the result in memory, and then scan t1 or an index on t1.id, matching against the cached values.

    But if the query is:

    SELECT *
    FROM   t1
    WHERE  id IN (
                 SELECT id
                 FROM   t2
                 WHERE  t2.type = t1.type
                )
    

    here the subquery is correlated - there is no way to compute the subquery unless t1.type is known. Since the value for t1.type may vary for each row of the outer query, this subquery could be executed once for each row of the outer query.

    Then again, the RDBMS may be really smart and realize there are only a few possible values for t2.type. In that case, it may still use the approach used for the uncorrelated subquery if it can guess that the cost of executing the subquery once will be cheaper that doing it for each row.

    0 讨论(0)
提交回复
热议问题