Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested loops in MySQL

In this O'Reilly presentation, there is a paragraph introducing some key concepts for understanding MySQL's EXPLAIN:

What is a JOIN?

  • Everything is a JOIN, because MySQL always uses nested-loops
  • Even a single-table SELECT or a UNION or a subquery

Can anyone explain how this works for a single table SELECT?

like image 227
RADA Avatar asked Jan 14 '11 17:01

RADA


People also ask

What is nested loop join in SQL Server?

A simple nested-loop join (NLJ) algorithm reads rows from the first table in a loop one at a time, passing each row to a nested loop that processes the next table in the join. This process is repeated as many times as there remain tables to be joined.

What happened to the block nested loop in MySQL?

Starting with MySQL 8.0.20, the block nested loop is no longer used by MySQL, and a hash join is employed for in all cases where the block nested loop was used previously. See Section 8.2.1.4, “Hash Join Optimization” .

What is loops in MySQL?

Loops in MySQL 1 labelname : It is an optional label at the start and end. 2 statements : They could have one or multiple statements, each ended by a semicolon (;) and executed by LOOP. More ...

How do you check if a while loop is nested?

Nested SQL While Loop Syntax 1 First, it checks for the condition inside the first While loop. ... 2 It will verify the condition in the Nested SQL While Loop (second While loop). ... 3 Once exit from second While loop, it will check for the condition inside the first While loop (repeating Step 1 )


1 Answers

Nested loops is one way of processing joins:

for each row of table A
  if this row matches where clauses
    for each row of joined table B
      if this row matches where clauses and join clauses
        accept row
      end
    end
  end
end

That can be optimized with indexes quite a bit, by doing "for each row found at key K in some index" instead of "each row of table A", and the same with table B.

The presentation is saying this is the only way MySQL processes joins. There are other methods than can be used, but MySQL doesn't implement them. This OraFAQ entry gives several that Oracle implements: http://www.orafaq.com/tuningguide/join%20methods.html Similarly: http://oracle-online-help.blogspot.com/2007/03/nested-loops-hash-join-and-sort-merge.html

"Everything is a join" is just an implementation detail, I believe. Not really that important.

like image 179
derobert Avatar answered Sep 18 '22 00:09

derobert