Does the order of tables in a JOIN matter?


#1

Question

When we write a JOIN query, does the order we specify the tables matter?
For example,
FROM table1 JOIN table2
vs
FROM table2 JOIN table1

Answer

Generally, no, the order of the tables in the JOIN will not affect the overall results of the query.

As long as you specify what columns to select, the results should appear essentially the same, just that the rows will be ordered according to the appearance in the first table.

However, if you do not specify specific columns, then the order of columns will be different depending on the order of the tables. Without specifying columns in your SELECT, by using just SELECT *, the result query will order the columns by the first table’s columns followed by the second table’s columns.

For example, say we had two tables:
orders, with the columns order_id, customer_id
and
customers, with the columns customer_id, address.

If we run the following query,

SELECT *
FROM orders
JOIN customers
ON orders.customer_id = customers.customer_id;

the columns in this query’s results will be ordered from left to right as:
order_id, customer_id, customer_id, address

Conversely, if we ran this query,

SELECT *
FROM customers
JOIN orders
ON orders.customer_id = customers.customer_id;

it will return the columns in the following order from left to right:
customer_id, address, order_id, customer_id

If the order of your columns matters in the result query, then it will be important to keep this in mind.