Using SQL Alias vs Inner Join, what is the difference? - sql

In http://www.w3schools.com/sql/sql_alias.asp, it mentions using alias to do the following query,
SELECT
Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM
Customers, Orders
WHERE
Customers.CustomerName = "Around the Horn"
AND Customers.CustomerID = Orders.CustomerID;
This confuses me with the usage of JOIN. Isn't this kind of query joining the columns from two tables? What are the differences between this kind of query and JOIN?

JOIN and alias are two differnt concept .. the alias is for create a substitutive name (shorter usually) for a more easy object reference and for a more easy read .. so you can have column name alias or table name alias eg:
select a.col1
from my_table as a
a is an alias for the table my_table
or
select a.col1 as c1
from my_table as a
where c1 is an alias for col1
JOIN are for build relation between table
The Join can be implict or explict
In your code you are using implici join and the condition between the tables that keep the relation is based on where clause
but you could use a more espressive way using explict join
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers
INNER JOIN Orders on Customers.CustomerID=Orders.CustomerID;
WHERE Customers.CustomerName="Around the Horn"

Both the same, there is no difference.
There are differences only in readability.
In my opinion, PLSQL(ORACLE) developer choosing alias when writing queries then TSQL(SQL Server) developer choosing by Join

The answer to your question is there is no difference between your query and an inner join but many times, your write queries between tables where the relationships are not explicitly defined or a table may not require a relationship. In those cases, you would use a left join to return data from a first table and zero to many items from the table on the right. Using your format, makes that a lot more difficult to write and read. As for table Aliases, when writing self joins for example, you will need to use them so understanding them is essential.

Related

How to do self join

I want to do self-join I have written a code as well but its throwing an error and it seems that there is some issue with an alias.
Apart from this it would also be helpful for me if someone let me know any best site where I can learn query in MS Access. I searched a number of places everywhere, it is showing through UI Interface but I want to learn query in MS Access.
(SELECT distinct itemname,vendorname,price,count(*)
from vendor_Details1
group by itemname,vendorname,price
order by vendorname) A
inner join
(SELECT distinct itemname,vendorname,price,count(*)
from vendor_Details1
group by itemname,vendorname,price
order by vendorname) B
on A.vendorname=B.vendorname
It is entirely unclear what you are trying to do. However, "join" is an operator in the FROM clause that operates on two tables, views, or subqueries.
The structure of a self-join looks like:
select . . . -- list of columns here
from t as t1 inner join -- you need aliases for the table so you can distinguish the references
t as t2
on t1.? = t2.? -- the join condition goes here
Your query doesn't even have a select.

Commutativity of Inner Join

I read from this answer (click), the following conditional statements
Invoices.CustomerID=Customers.CustomerID
and
Customers.CustomerID=Invoices.CustomerID
are identical because it produces the same result set.
Now, my problem is about commutativity of inner join. I have tried both of the following approaches and they produce the same result set (except for the column order).
Customers table first
use MMABooks
select *
from Customers
inner join Invoices
on Invoices.CustomerID=Customers.CustomerID
where Customers.CustomerID=10
Invoices table first
use MMABooks
select *
from Invoices
inner join Customers
on Invoices.CustomerID=Customers.CustomerID
where Invoices.CustomerID=10
Questions
Is inner join commutative by design?
Is there a best practice that suggest or prefer one approach over the other one? I mean, which approach should I use?
It would be really weird if they didn't produce the same result. Did you expect a difference?
A best practice is to start with the table from which you select most of the columns.
You do have to worry about the order when you work with LEFT or RIGHT JOINS.

When to use SQL natural join instead of join .. on?

I'm studying SQL for a database exam and the way I've seen SQL is they way it looks on this page:
http://en.wikipedia.org/wiki/Star_schema
IE join written the way Join <table name> On <table attribute> and then the join condition for the selection. My course book and my exercises given to me from the academic institution however, use only natural join in their examples. So when is it right to use natural join? Should natural join be used if the query can also be written using JOIN .. ON ?
Thanks for any answer or comment
A natural join will find columns with the same name in both tables and add one column in the result for each pair found. The inner join lets you specify the comparison you want to make using any column.
IMO, the JOIN ON syntax is much more readable and maintainable than the natural join syntax. Natural joins is a leftover of some old standards, and I try to avoid it like the plague.
A natural join will find columns with the same name in both tables and add one column in the result for each pair found. The inner join lets you specify the comparison you want to make using any column.
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.
Different Joins
* JOIN: Return rows when there is at least one match in both tables
* LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
* RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
* FULL JOIN: Return rows when there is a match in one of the tables
INNER JOIN
http://www.w3schools.com/sql/sql_join_inner.asp
FULL JOIN
http://www.w3schools.com/sql/sql_join_full.asp
A natural join is said to be an abomination because it does not allow qualifying key columns, which makes it confusing. Because you never know which "common" columns are being used to join two tables simply by looking at the sql statement.
A NATURAL JOIN matches on any shared column names between the tables, whereas an INNER JOIN only matches on the given ON condition.
The joins often interchangeable and usually produce the same results. However, there are some important considerations to make:
If a NATURAL JOIN finds no matching columns, it returns the cross
product. This could produce disastrous results if the schema is
modified. On the other hand, an INNER JOIN will return a 'column does
not exist' error. This is much more fault tolerant.
An INNER JOIN self-documents with its ON clause, resulting in a
clearer query that describes the table schema to the reader.
An INNER JOIN results in a maintainable and reusable query in
which the column names can be swapped in and out with changes in the
use case or table schema.
The programmer can notice column name mis-matches (e.g. item_ID vs itemID) sooner if they are forced to define the ON predicate.
Otherwise, a NATURAL JOIN is still a good choice for a quick, ad-hoc query.

Group by in SQL Server giving wrong count

I have a query which works, goes like this:
Select
count(InsuranceOrderLine.AntallPotensiale) as potensiale,
COUNT(InsuranceOrderLine.AntallSolgt) as Solgt,
InsuranceProduct.Name,
InsuranceProductCategory.Name as Kategori
From
InsuranceOrderLine, InsuranceProduct, InsuranceProductCategory
where
InsuranceOrderLine.FKInsuranceProductId = InsuranceProduct.InsuranceProductID
and InsuranceProduct.FKInsuranceProductCategory = InsuranceProductCategory.InsuranceProductCategoryID
Group by
InsuranceProduct.name, InsuranceProductCategory.Name
This query over returns what I need, but when I try to add more table (InsuranceOrder) to be able to get the regardingUser column, then all the count values are way high.
Select
count(InsuranceOrderLine.AntallPotensiale) as Potensiale,
COUNT(InsuranceOrderLine.AntallSolgt) as Solgt,
InsuranceProduct.Name,
InsuranceProductCategory.Name as Kategori,
RegardingUser
From
InsuranceOrderLine, InsuranceProduct, InsuranceProductCategory, InsuranceSalesLead
where
InsuranceOrderLine.FKInsuranceProductId = InsuranceProduct.InsuranceProductID
and InsuranceProduct.FKInsuranceProductCategory = InsuranceProductCategory.InsuranceProductCategoryID
Group by
InsuranceProduct.name, InsuranceProductCategory.Name,RegardingUser
Thanks in advance
You're adding one more table to your FROM statement, but you don't specify any JOIN condition for that table - so your previous result set will do a FULL OUTER JOIN (cartesian product) with your new table! Of course you'll get duplication of data....
That's one of the reasons that I'm recommending never to use that old, legacy style JOIN - do not simply list a comma-separated bunch of tables in your FROM statement.
Always use the new ANSI standard JOIN syntax with INNER JOIN, LEFT OUTER JOIN and so on:
SELECT
count(iol.AntallPotensiale) as Potensiale,
COUNT(iol.AntallSolgt) as Solgt,
ip.Name,
ipc.Name as Kategori,
isl.RegardingUser
FROM
dbo.InsuranceOrderLine iol
INNER JOIN
dbo.InsuranceProduct ip ON iol.FKInsuranceProductId = ip.InsuranceProductID
INNER JOIN
dbo.InsuranceProductCategory ipc ON ip.FKInsuranceProductCategory = ipc.InsuranceProductCategoryID
INNER JOIN
dbo.InsuranceSalesLead isl ON ???????? -- JOIN condition missing here !!
When you do this, you first of all see right away that you're missing a JOIN condition here - how is this new table InsuranceSalesLead linked to any of the other tables already used in this SQL statement??
And secondly, your intent is much clearer, since the JOIN conditions linking the tables are where they belong - right with the JOIN - and don't clutter up your WHERE clauses ...
It looks like you added the table join which slightly multiplies count of rows - make sure, that you properly joining the table. And be careful with aggregate functions over several joined tables - joins very often lead to duplicates

how to best organize the Inner Joins in (select) statement

let's say i have three tables, each one relates to another,
when i need to get a column from each table, does it make difference how to organize
the (inner joins)??
Select table1.column1,table2.column2,table3.column2
From table1
Inner Join table2 on ..... etc
Inner Join table3 on .....
in another words, can i put (table2) after (From )??
Select table1.column1,table2.column2,table3.column2
From table2
Inner Join table1 on ..... etc
Inner Join table3 on .....
For most queries, order does not matter.
An INNER JOIN is both associative and commutative so table order does not matter
SQL is declarative. That is, how you define the query is not how the optimiser works it out. It does not do it line by line as you wrote it.
That said...
OUTER JOINs are neither associative nor commutative
For complex queries, the optimiser will "best guess" rather than go through all possibilities which "costs" too much. Table order may matter here
The inner join operation has left to right associativity. It doesn't matter much in which order you write the tables, as long as you don't refer to any tables in the ON condition before they have been joined.
When the statement is executed the database engine will determine the best order to execute the join and this may be different from the order they appear in the SQL query.