SQL Server – Do Multiple Queries in Batch Execute in Parallel

parallelismsql serversql-server-2008-r2sql-server-2017temporary-tables

If I have a batch of two different SELECT statements, is it possible for them to be executed in parallel (if the SQL Optimizer deems it to be the most efficient execution method)?

If the first SELECT statement is selecting into a temp table and the second SELECT statement is then inserting into that same temp table, does that prevent it from being possible for the two statements to be ran in parallel?

(I'm guessing the answers are yes and yes :).

Best Answer

Batch statements are only ever executed serially in the order they appear in the batch.

Now, if you have two statements sent to the server by two different batches, they will run independently and essentially simultaneously (locking and latching aside).

Take for example the following code:

CREATE TABLE #t
(
    i int
);

INSERT INTO #t (i) VALUES (0);

The CREATE TABLE always runs prior to the INSERT INTO statement. Consider this:

SELECT 1;

SELECT 2;

The above code will always be ran in order, i.e. SELECT 1 runs first, then after it completes, SELECT 2 runs.

There are multiple ways independent batches can be ran simultaneously, including the use of Multiple Active Result Sets, or MARS, however none of those affect the serial processing of statements within a single batch.