This syntax
FROM tablename p
or
JOIN tablename p
create an alias for a table name. In most cases, it is simply a way to shorten your statement, because you can use a shorter name in place of a full table name.
However, in some instances an alias is required: when you need to reference the same table more than once in the same query, you must create an alias to disambiguate your statement.
Specific examples where an alias is required are sub-queries on the same table and self-joins.
Here is an example of a query with a subquery:
SELECT
FROM Orders o
JOIN OrderItem oi on o.ID=oi.OrderID
JOIN Item i on i.ID=oi.ItemID
WHERE EXISTS (
SELECT *
FROM OrderItem oi2
JOIN Item i2 ON i2.ID=oi2.ItemId
WHERE i2.Description='BACKPACK'
AND oi2.OrderID=o.ID
)
The above query finds all orders that contain a backpack. Note that Item
and OrderItem
tables need to be included twice each, so they have multiple aliases.
Here is example of a query with a self join:
SELECT
e.Name as EmployeeName
, m.Name as ManagerName
FROM EMPLOYEE e
OUTER JOIN EMPLOYEE m ON m.ID=e.ManagerID
ORDER BY m.Name, e.Name
Above, the same table EMPLOYEE
is referenced twice in the same query, because it participates in two different roles - as an employee, and as a manager. Giving the table two aliases lets us disambiguate the join condition m.ID=e.ManagerID
.