Skip to content
Advertisement

Why can identifiers in SQL be referenced before assignment?

In a SQL query you can reference a name before that name has been declared.

SELECT A.id FROM table_a A;

What is the history of this behavior and how does it relate to programming languages that require you to assign to variables before you can reference them?

Advertisement

Answer

You are misunderstanding the nature of the SQL language. It is a not a procedural language, but a declarative language. The statement describes what the result should look like, and the database builds the actual query plan accordingly – which, by default, you don’t get to see.

Some databases provide some kind of procedural sub-language, which can be used to write procedures – eg PL/SQL in Oracle. However, what you are showing here is a standard SQL SELECT statement. There is no notion of variable declaration in there. A in the FROM clause is an alias for table_a, aka an identifier, that you can the use to refer to the columns of table, using an expression like <table identifier>.<column name>.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement