This seems like a fairly obvious question, but I haven’t been able to think of the proper term for what I am trying to ask, so coming up with reference material for this has been tricky. The answers seem obvious, though.
When examining the Pluralsight training material for SQL Server, they recommended always referring to tables in both “regular” queries (something you might write for a basic web service) and for a SQL query in perhaps a stored procedure, like the following:
[databasename].[dbo].[some_table].[sometimesacolumngoeshere]
Though I have found it very common to come across stored procs, etc., that simply use:
my_column or [my_column]
The difference here is obviously that one provides an absolute “address” explicitly, whereas the other is implicit.
How do you know when it is appropriate to use one over the other, and also what do you call this, addressing?
My preference would be to always be explicit, and if you need to save space and/or make things more clear, you could alias to an explicit full “address”, correct?
You are correct. Basically SQL will attempt to find the field you are looking for “my_column” in all of the tables in your FROM and JOIN sections. If however you happen to have a “my_column” in table A and in table B then you need to explicitly tell it which “my_column” you are looking for by including the table name. This goes on up the chain to dbo and databasename if you have collisions there as well.
Most of the time you will find that people don’t explicitly call out the tables a column is in unless they are joining multiple tables.
For example I write my queries like this:
Here I am using the AS to alias tableA and tableB down to more readable a and b. I could have just as easily written my query like this:
Or like this, if field1 and field2 are unique to there tables, but this gets a bit confusing as to where each piece of data is coming from.