Anna Gabrielyan
Anna Gabrielyan

Reputation: 2170

What is happening on sql server when you run this sql command

I have this sql query. I now what is it returning , but can't understand how server parses and execute it step by step. I want to understand the principles of work in deep level, what is going on server when you run sql command, how it iterates in each row before return result.

enter image description here

I have users and friends table, in last one have friend_id and user_id combination, both of them are ids of users.

select u.id,f.user_id, f.friend_id from friends f
    INNER JOIN users u on (u.id = f.friend_id or u.id = f.user_id)
    where f.user_id = 72 or f.friend_id = 72

Upvotes: 3

Views: 178

Answers (1)

Mathias Florin
Mathias Florin

Reputation: 88

Without a query plan I can only make a guess how the engine could potentially execute your query, I hope it helps:

First step - FROM:

If you have an index on the where columns (user_id, user_id), an index seek can be executed on your friends table with the where conditions to limit the results which need to be evaluated later in the execution plan. If you don't have an index, a table scan can be performed.

Your query would select all rows from the friends table where user_id or friend_id is equal to 72.

OR means here that only one condition needs to be true for the row to be added to the data stream of rows from friends.

2nd step - JOIN:

After the friends rows are found applying the where predicate, the actual join processing would start. Depending on the table statistics and query costs the engine could do a nested loop join where each row is evaluated from friends against users. It could also build a hash table for one table and probe each row from the other table using the hash key function. This way the ids can be matched between your two tables (friends and users)

The ON defines which columns it needs to compare.

Let's consider the case of a nested loop join which is easier to understand. This join type loops through both data streams ( friends and users ) which are being joined together in a row by row fashion and evaluates each row.

In your query it will compare the u.id against friend_id. If this condition returns true the join will be fulfilled and the engine will combine the matching row from table friends and users for further processing. If the first condition of ON is false or unknown the engine will evaluate the second condition user_id. True fulfills the join, false or unknown means the row is not matched so it will not be returned as in this case both on conditions would fail.

3rd step - SELECT:

After the tables are joined the engine has all the data it needs to finally execute the SELECT statement returning the columns you've asked it for.

Upvotes: 2

Related Questions