What's the scope of table aliases? - sql

This question is in the context of Sqlite but I wonder in general what's the rule for aliases. Suppose I have the following query:
SELECT *
FROM (SELECT * FROM tableA as t1 inner join tableB as t2 on t1.id=t2.some_id) as t3,
(SELECT * FROM tableC as t1 inner join tableD as t2 on t1.id=t2.some_id) as t4
WHERE t3.id=t4.id
The question is, will the two t1's and t2's clash? in my experience with multiple database vendors they won't clash, but, could it confuse the optimizer to the point of producing a buggy result? I have this hypothesis for a query giving bogus results in Sqlite.

No, the aliases will not clash. They are known only in their respective subqueries.
Of course, the query will fail because of the trailing comma. And in general, you should avoid commas in the FROM clause. Always use proper, explicit, standard, readable JOIN syntax.

Related

joining three tables between each other

Is it possible to join three tables in this way .
select T1.[...],T2.[...],T3.[...]
from T1
full outer join T2 on T1.[key]=T2.[key]
full outer join T3 on T1.[key]=T3.[key]
full outer join T2 on T2.[key]=T3.[key]
My question is : Is this a valid Form?
And if no is there a way to do such operation?
It is "valid" but the full joins are not correct. The on conditions will change them to some other type of join.
Your query has other errors. But I speculate that you want:
select T1.[...], T2.[...], T3.[...]
from T1 full join
T2
on T2.[key] = T1.[key] full join
T3 join
on T3.[key] = coalesce(T2.[key], T1.[key]);
It is possible to join three tables, and your example could run with some changes, but you have syntax and scoping errors in the FROM clause.
Even those aside, I don't think it will do what you intend it to do. You'll probably want to use GROUP BY
See the examples / discussion here :
Multiple FULL OUTER JOIN on multiple tables
I also used this site as a source, as its been a while since I've touched SQL, it may be helpful to you also :
https://learnsql.com/blog/how-to-join-3-tables-or-more-in-sql/

Are these SQL queries equivalent [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Explicit vs implicit SQL joins
Is there a difference using join andselect from multi-tables?
SQL Joins: Future of the SQL ANSI Standard (where vs join)?
What is the difference between JOIN and declaring multiple tables in the FROM clause?
Such as:
SELECT *
FROM table1 AS t1,
table2 AS t2
WHERE t1.id = t2.id
Compared to:
SELECT *
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t2.id = t1.id
The second version, with the explicit JOIN and join condition is standardized SQL.
The implicit join syntax with a WHERE clause is deprecated syntax (or, rather, considered bad) - partially because it is easy to forget the WHERE clause and cause a Cartesian product.
Why Use the new syntax?
As others have stated, the new syntax has become the preferred convention. In larger queries the new syntax is easier to read, debug, and ensure the join criteria is added (meaning no accidental CROSS JOINS.
Is the old syntax deprecated (for inner joins)?
Not according to ANSI -- both are valid, even if the first is disfavored. Although, performing outer joins in the old syntax has been deprecated -- mainly because it can be ambiguous.
How consensus is the "use the new syntax" view ?
Aaron Bertran considers it a "bad habit to kick"
SQL Server Central the consensus was "Kill kill kill it with fire"
Joe Celko -- meh, but it's easier to read.
Both will output the same and are just different variations of writing the query.
SELECT *
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t2.id = t1.id
Is the preferred join method as you are explicitly stating which type of join you are using, i.e. LEFT, OUTER, INNER.

What Does *= means in WHERE Clause in TSQL?

some one have asked me the output of below query.
Select *
from TableA t1, TableB t2
where t1.Id *= t2.Id
Can anyone explain me, if such type of any query exists, if so then how its works. Because i have never seen such type of query Thanks.
UPDATE:
Also when i run this query in SQL Server, i get this;
The query uses non-ANSI outer join operators ("*=" or "=*").
To run this query without modification, please set the compatibility level
for current database to 80, using the SET COMPATIBILITY_LEVEL option
of ALTER DATABASE.
It is strongly recommended to rewrite the query using ANSI outer join
operators (LEFT OUTER JOIN, RIGHT OUTER JOIN).
In the future versions of SQL Server, non-ANSI join operators will
not be supported even in backward-compatibility modes.
Using asterisk in a WHERE is an old non-ANSI compliant syntax for OUTER JOINing tables and therefore should not be used anymore.
Here's the link.
The asterisk in the where condition is actually part of a non-ANSI outer join operator, it is used to define an implicit outer join.
It will cause trouble in modern databases as this operator has been obsolete since 1992.
Essentially the below are the same:
SELECT * FROM TableA LEFT OUTER JOIN TableB ON t1.Id = t2.Id
SELECT * FROM TableA , TableB WHERE t1.Name *= t2.Name
The *= operator means LEFT OUTER JOIN.

NESTED INNER JOIN using MS Access 2003 via ODBC

If this works:
SELECT COUNT(t1.ID) AS count FROM Project t1
INNER JOIN (SELECT DISTINCT t.Site,t.id FROM _Equipment_id t WHERE t.OEM LIKE '%ABC%') t2 ON t1.Site=t2.Site AND t1.id=t2.id
and this works:
SELECT COUNT(t3.ID) AS count FROM Wall t3
INNER JOIN Project t1 ON t3.Project_number=t1.Project_number
Why doesn't this work:
SELECT COUNT(t3.ID) AS count FROM Wall t3
INNER JOIN Project t1 ON t3.Project_number=t1.Project_number
INNER JOIN (SELECT DISTINCT t.Site,t.id FROM _Equipment_id t WHERE t.OEM LIKE '%ABC%') t2 ON t1.Site=t2.Site AND t1.id=t2.id
Ultimately, I have 10 tables like the Wall table that I am trying to get a total count from the first SELECT....
SELECT COUNT(t3.ID) AS count FROM Wall t3
INNER JOIN (Project t1
INNER JOIN (SELECT DISTINCT t.Site,t.id FROM _Equipment_id t WHERE t.OEM LIKE '%ABC%') t2
ON t1.Site=t2.Site AND t1.id=t2.id)
ON t3.Project_number=t1.Project_number
Maybe it's just a syntax error? Office Help at the bottom where they mention nesting. The other possibility is that the aliases are somehow scoped so that they are not available to the join, but I'm no expert on MS Access. Maybe you should just try dropping the aliases altogether.
You have a couple of minor issues with your code: a table name that starts with an underscore character (_Equipment_id) and an AS clause ("alias") that is a SQL keyword (AS count). When these are corrected, your SQL is valid SQL-92 syntax.
Sadly, the problem is that Access (ACE, Jet, whatever) does not support the SQL-92 Standard. Access insists that each nested JOIN clause is put in parentheses.
[Aside: JOINs in parentheses are allowed in Standard SQL because it can potentially change the query results. However Access, does not respect the order specified by the coder and allows itself to evaluate JOINs in order it sees fir. So not only Access's syntax non-compliant with the Standard, there is also a loss of functionality! However, this further problem with Access will have no ill effect for this particular query.]
You have two JOINs in the same scope here:
...
INNER JOIN Project t1 ON t3.Project_number=t1.Project_number
INNER JOIN
...
Your code needs to work around Access's problem by enclosing the JOIN in parentheses; because all your JOINs are INNER flavour, it probably doesn't matter where they go.
Also, as regards correcting your AS clause, Access again doesn't support Standard SQL's quoted identifiers (...AS "count"...) and insists you use its proprietary square brackets syntax (...AS [count]...) -- of course, you could choose a different name but there may exist application code that relies on it.
Code to workaround both Access problems:
SELECT COUNT(t3.ID) AS [count]
FROM (Wall t3
INNER JOIN Project AS t1
ON t3.Project_number = t1.Project_number)
INNER JOIN (
SELECT DISTINCT t.Site,t.id
FROM _Equipment_id AS t
WHERE t.OEM LIKE '%ABC%'
) AS t2
ON t1.Site = t2.Site
AND t1.id = t2.id;

TABLE1 T1, TABLE2 T2 WHERE T1.Blah = T2.Blah - VS - INNER JOIN

Provided that the tables could essentially be inner joined, since the where clause excludes all records that don't match, just exactly how bad is it to use the first of the following 2 query statement syntax styles:
SELECT {COLUMN LIST}
FROM TABLE1 t1, TABLE2 t2, TABLE3 t3, TABLE4 t4 (etc)
WHERE t1.uid = t2.foreignid
AND t2.uid = t3.foreignid
AND t3.uid = t4.foreignid
etc
instead of
SELECT {COLUMN LIST}
FROM TABLE1 t1
INNER JOIN TABLE2 t2 ON t1.uid = t2.foreignid
INNER JOIN TABLE3 t3 ON t2.uid = t3.foreignid
INNER JOIN TABLE4 t4 ON t3.uid = t4.foreignid
I'm not sure if this is limited to microsoft SQL, or even a particular version, but my understanding is that the first scenario does a full outer join to make all possible correlations accessible.
I've used the first approach in the past to optimise queries that access two significantly large stores of data that each have peripheral table joined to them, with the product of those joins coming together late in the query. By allowing each of the "larger" table to join to their respective lookup tables, and only combining a specific subset of each of the larger tables, I found that there were notable speed improvements over introducing the large tables to each other prior to specific filtering.
Under normal (simple joins) circumstance, would it not be far better to use the second scenario? I find it to be more easily readable and it seems like it'll be much faster.
INNER JOIN ON vs WHERE clause
Maybe the best way to answer this is to take a look at how the database handles the query internally. If you're on SQL Server, use Profiler to see how many reads etc. each query takes and the query plan to see what route is being taken through the data. Statistics, skewing etc. will also most likely play a role.
The first query doesn't produce a full OUTER join (which is the union of both LEFT and RIGHT joins). Essentially unless there are some [internal] SQL parser - specific optimizations, both queries are equal.
Personally I would never use the first syntax. It may be the same performancewise but it is harder to maintain and far more subject to accidental cross joins when things get complex. If you miss an ON condition, it will fail the syntax check , if you miss one of the WHERE conditions that is the equivalent of an ON condition, it will happily do a cross join. It is also a syntax that is 17 years out of date for goodness sakes!
Further, the left and right join syntax in the old syntax are broken in SQL Server and do NOT always return the correct results (it can sometimes interpet the results as a corss join instead of an outerjoin) and they have been deprecated and will not be useable at all in the next version. If you need to change one of the queries to use an outer join, then you can be looikng at a major rewrite as it is especially bad to try to mix the two kinds of syntax.