Sql – Does filtering or joining happen first in T-SQL


I have two tables:

Customers(Id, Name, TownId) T
Towns(Id, Name)

I have an SQL statement like this:

FROM Customers
INNER JOIN Towns ON Towns.Id = Customers.TownId
WHERE Customers.Id > 5

What would happen first?
Would it filter the Customers table and then join the selected records with Towns table?
Would it join all Customers with Towns and then filter? Or is it that you cannot tell?

Best Solution

The optimizer will do whatever it thinks will be fastest.

You can force certain behaviors with join hints or encourage certain behaviors with statistics and indexes. It's usually best to Trust the Optimizer, though.

If you want a detailed explanation of how a query is executed, look at the execution plan.