37

When we prefix an SQL query with the keyword "explain" we get a table with some columns. Please tell me what is the "type" column. What does eq_ref and ref mean in that context.

0

2 Answers 2

100

I'll try an explanation...

eq_ref – imagine that you have two tables. Table A with columns (id, text) where id is a primary key. Table B with the same columns (id, text) where id is a primary key. Table A has the following data:

1, Hello 
2, How are

Table B has the following data:

1, world!
2, you?

Imagine eq_ref as JOIN between A and B:

select A.text, B.text where A.ID = B.ID

This JOIN is very fast because for each row scanned in table A there can be only ONE row in table B which satisfies the JOIN condition. One and no more than one. That is because B.id is UNIQUE.
Here you are: pseudo code which illustrates the processing at server side:

foreach (rowA in A)
{
    if (existsInBRowWithID(rowA.id)
    {
        addToResult(rowA.text, getRowInBWithID(rowA.id).text);
    }
}

ref - Now imagine another table C with columns (id, text) in which id an index but a non UNIQUE one. Table C has the following data:

1, John!
1, Jack!

Imagine ref as JOIN between A and C:

select A.text, C.text where A.ID = C.ID

Here you are: pseudo code illustrating the server side processing:

foreach (rowA in A)
{
    foreach (rowC in C)
    {
        if (rowA.id == rowC.id)
        {
            addToResult(rowA.text, rowC.text);
        }
    }
}

This JOIN is NOT as fast as the former one because for each row scanned in table A there are SEVERAL possible rows in table C which may satisfy the JOIN condition (nested loops). That is because C.ID is NOT UNIQUE.

1
  • 2
    perfect explanation !
    – julio
    Jan 30, 2017 at 9:32
34

The "type" refers to the join type made in your request. From best to worst, here is the list :

  • system
  • const
  • eq_ref
  • ref
  • range
  • index
  • all

You will find a more detailed explanation at the MySQL documentation : http://dev.mysql.com/doc/refman/5.0/en/explain-output.html

1
  • 2
    yes, thank you, but am not looking for that...i have understood what system and const mean in that type....but what does eq_ref and ref mean? I have read the explanation in mysql documentation but couldn't understand it.... Dec 24, 2010 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.