Can alias in SQL be used within the same table? - sql

I have difficulty understanding alias. Can alias in SQL be used within the same table?

In a query, you can use multiple aliases for a single table:
SELECT alias1.Name, alias2.Name
FROM table as alias1
INNER JOIN table as alias2
ON alias1.ChildId = alias2.Id
In the code above I am aliasing table as alias1 and alias2. It is the same table, with 2 different aliases.

Not sure I understand your question completely...
A good read on aliases # http://www.w3schools.com/sql/sql_alias.asp
http://www.sqltutorial.org/sqlalias.aspx
There are 2 kinds of aliases, one for tables and one for columns. Aliaes are used as a way to make your sql code more readable. It can give meaningful names to column and table names that might be long and/or confusing.

check the w3schools breif description and examples for SQL Alias
You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names.

Which alias as you referring to: 'table alias' or 'column alias'?
In the SQL-92 Standard, the vernacular 'table alias' is referred to as a correlation name. A correlation name much be unique within its scope. The actual wording is as follows:
An identifier that is a correlation
name is associated with a table
within a particular scope. The scope
of a correlation name is either a
select statement: single row,
subquery, or query specification.
Scopes may be nested. In different
scopes, the same correlation name
may be associated with different
tables or with the same table.
In the SQL-92 Standard, the vernacular 'column alias' is referred to (rather wordily) as an as clause that contains a column name. There is no general condition that the same column name shall not be specified more than once in column lists (but there are context-specific restrictions e.g. a view column list). In fact, SQL's allowance of duplicate column names is often cited as a fatal flaw as regards being turly relational.

Related

(SQL) How do I differentiate 2 columns from different tables with the same name when selecting?

I'm using an Oracle 12c SQL server. The goal is to create a view containing each company and the drugs it produces.
How can I differentiate two columns with the exact same name but located in different tables using SELECT?
All relevant code below, including results with error.
I understand why I might be getting a duplicate name error as they both have the same header "name", but thought I handled it by identifying the table beforehand (i.e. pc.name and dg.name). Help!
SQL Tables Being Joined:
SQL Column Naming Error:
You have ambiguous column names in output from your view:
pc.name, dg.name
Adding alias for columns should solve this:
pc.name as pc_name, dg.name as dg_name

Table field naming convention and SQL statements

I have a practical question regarding naming table fields in a database. For example, I have two tables:
student (id int; name varchar(30))
teacher (id int, s_id int; name varchar(30))
There are both 'id' and "name" in two tables. In SQL statement, it will be ambiguous for the two if no table names are prefixed. Two options:
use Table name as prefix of a field in SQL 'where' clause
use prefixed field names in tables so that no prefix will be used in 'where' clause.
Which one is better?
Without a doubt, go with option 1. This is valid sql in any type of database and considered the proper and most readable format. It's good habit to prefix the table name to a column, and very necessary when doing a join. The only exception to this I've most often seen is prefixing the id column with the table name, but I still wouldn't do that.
If you go with option 2, seasoned DBA's will probably point and laugh at you.
For further proof, see #2 here: https://www.periscopedata.com/blog/better-sql-schema.html
And here. Rule 1b - http://www.isbe.net/ILDS/pdf/SQL_server_standards.pdf
As TT mentions, you'll make your life much easier if you learn how to use an alias for the table name. It's as simple as using SomeTableNameThatsWayTooLong as long_table in your query, such as:
SELECT LT.Id FROM SomeTableNameThatsWayTooLong AS LT
For queries that aren't ad-hoc, you should always prefix every field with either the table name or table alias, even if the field name isn't ambiguous. This prevents the query from breaking later if someone adds a new column to one of the tables that introduces ambiguity.
So that would make "id" and "name" unambiguous. But I still recommend naming the primary key with something more specific than "id". In your example, I would use student_id and teacher_id. This helps prevent mistakes in joins. You will need more specific names anyway when you run into tables with more than one unique key, or multi-part keys.
It's worth thinking these things through, but in the end consistency may be the more important factor. I can deal with tables built around id instead of student_id, but I'm currently working with an inconsistent schema that uses all of the following: id, sid, systemid and specific names like taskid. That's the worst of both worlds.
I would use aliases rather than table names.
You can assign an alias to a table in a query, one that is shorter than the table name. That makes the query a lot more readable. Example:
SELECT
t.name AS teacher_name,
s.name AS student_name
FROM
teacher AS t
INNER JOIN student AS s ON
s.id=t.s_id;
You can of course use the table name if you don't use aliases, and that would be preferred over your option 2.
If it doesn't get too long, I prefer prefixing in the table themselves, e.g. teacher.teacher_id, student.student_name. That way, you are always sure which name or id your are talking about, even if you for get to prefix the table name.

How to update a field in a table basing on a field from another table

So I have two tables, InTheMiddle and Table2.
The 1st one contains Name column, the 2nd one contains ID and Name columns.
(they also have other columns, but irrelevant to this question)
I want to update/change the names in the 1st table with the IDs from the second one, but of course only when the names match and there's only one name (so there aren't any semicolons ";").
Here's a query that I tried to use, but Access tells me "Operation must use an updateable query"
UPDATE InTheMiddle
SET [Name] =
(SELECT [Table2].ID
FROM [Table2]
WHERE InTheMiddle.[Name] = [Table2].[Name]
AND InTheMiddle.[Name] NOT LIKE "*;*"
);
Possible duplicate to Operation must use an updatable query. (Error 3073) Microsoft Access, in which the accepted answer suggests that the only way to avoid that error message is to use temporary tables.
Besides the accepted answer, this answer suggests a workaround to code looking like yours

T-SQL - Using Column Name in where condition without any references when having multiple tables that are engaged using multiple joins

I am a newbie for T-Sql, I came across a SP where multiple tables are engaged using multiple joins but the where clause contain a column field without any table reference and assigned for an incoming variable,like
where 'UserId = #UserId'
instead - no table reference like
'a.UserId = #Userid'`
Can any please do refer to me any material that clears my mind regarding such issue.
If the query works it means that there is only one Column with the name UserId, if there are multiple columns with the same name you have to reference the table too.
If you don't specify the table reference you will get
Ambiguous column name 'UserId'. error
Which means there are more then 2 tables with a column name UserId.
Anyway, always try and use the reference table.

SQL: Ambiguity on key fields

I don't understand why the interpreter cannot handle the following:
SELECT id
FROM a
INNER JOIN b ON a.id = b.id
This query wil result in an error: Ambiguous column name 'id'
Which makes sense because the column in defined in multiple tables in my query. However, I clearly stated to only return the rows where the id's of both table are the same. So it wouldn't matter what table the id is from.
So just out of curiosity: Is there a reason why the interpreter demands a table for the field?
(My example is from SQLServer, not sure if other interpreters CAN handle this?)
Let's be clear about a few things. First, it is always a good idea to include table aliases when referring to columns. This makes the SQL easier to understand.
Second, you are assuming that because of the = in the on condition, the two fields are the same. This is not true. The values are the same.
For instance, one field could be int and the other float (I do not recommend using float for join keys, but it is allowed). What is the type of id? SQL wants to assign a type to all columns, and it is not clear what type to assign.
More common examples abound. One id might be a primary key and defined NOT NULL. The other might be a foreign keys and quite nullable. What is the nullability of just id?
In other words, SQL is doing the right thing. This is not about whether SQL can recognize something obvious, which sometimes it does. This is about a column being genuinely ambiguous and the SQL compiler not knowing how to define the result in the SELECT clause.
How do you exepect the interpreter to know which column to use ?
Since it doesn't have a real brain (sadly..!), you need to explicitly specify the table where you want the id from.
In this example it could be :
SELECT a.id
FROM a
INNER JOIN b ON a.id=b.id
Even if the id values are the same, the column still has to come from one of the tables which the interpreter cannot choose for you ;-)
The SELECT id, should be SELECT a.id since id is in both tables it does not know "which one" you referring to.