Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain which table to choose "FROM" in a JOIN statement

Tags:

sql

join

mysql

I'm new to SQL and am having trouble understanding why there's a FROM keyword in a JOIN statement if I use dot notation to select the tables.columns that I want. Does it matter which table I choose out of the two? I didn't see any explanation for this in w3schools definition on which table is the FROM table. In the example below, how do I know which table to choose for the FROM? Since I essentially already selected which table.column to select, can it be either?

For example:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
like image 484
benishky Avatar asked Oct 03 '14 18:10

benishky


People also ask

What are the 5 different types of tables joins?

As known, there are five types of join operations: Inner, Left, Right, Full and Cross joins.

How do I choose which join to use in SQL?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

What is left and right table in join?

If you want to know exact left and right tables. From left to right the table attached with from is [left] and table attached with join is [right].

What are the 4 types of database joins?

Four types of joins: left, right, inner, and outer.


2 Answers

The order doesn't matter in an INNER JOIN.

However, it does matter in LEFT JOIN and RIGHT JOIN. In a LEFT JOIN, the table in the FROM clause is the primary table; the result will contain every row selected from this table, while rows named in the LEFT JOIN table can be missing (these columns will be NULL in the result). RIGHT JOIN is similar but the reverse: rows can be missing in the table named in FROM.

For instance, if you change your query to use LEFT JOIN, you'll see customers with no orders. But if you swapped the order of the tables and used a LEFT JOIN, you wouldn't see these customers. You would see orders with no customer (although such rows probably shouldn't exist).

like image 177
Barmar Avatar answered Oct 01 '22 15:10

Barmar


The from statement refers to the join not the table. The join of table will create a set from which you will be selecting columns.

like image 38
subas_poudel Avatar answered Oct 01 '22 17:10

subas_poudel