How does SQL know what c.* means if there is no table by that name?

Screen Link:
Using SQL Joins To Combine Data From Two Tables — Understanding Inner Joins | Dataquest

My Code:

select c.*, f.name as country_name
inner JOIN cities  c ON c.facts_id=f.id
limit 5

How does SQL know what table c.* is at the beginning? There is no table by the name of c. The tables are cities and facts. Is it because SQL actually does not know it but is defined later in the code when it says ‘cities c’?

@hliu19922019

SQL queries are read / executed in the following order:

So, the queries with FROM and JOIN are executed first, and SQL sees the aliases c, f

So the table cities is now c, and the table facts is now f

SELECT c.*,
       f.name country_name
FROM facts f
INNER JOIN cities c ON c.facts_id = f.id
LIMIT 5;

That makes sense. I guess I’ve been understanding the order of execution for SQl wrong. I always thought you “picked” the columns that you want to use to get the results but in reality it’s one of the last steps it performs. With that logic in mind, it makes much more sense.

2 Likes