How does SELECT from two tables separated by a comma work? (SELECT * FROM T1, T2)
The comma between the two tables signifies a CROSS JOIN, which gives the Cartesian product of the two tables. Your query is equivalent to:
SELECT *
FROM T1
CROSS JOIN T2
The result is every pairing of a row from the first table with a row from the second table. The number of rows in the result is therefore the product of the number of rows in the original tables. In this case the answer is 3 x 3 = 9.
The rows will be as follows:
T1.foo T2.bar
A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
C 3
What type of join is this?
Cartesian product of the 2 tables...
Explanation of the SQL query below
Another way of writing that query is this...
SELECT DISTINCT
T.name
FROM
instructor AS T
CROSS JOIN
instructor AS S
WHERE
T.salary > S.salary
In general CROSS JOIN
s are a bad idea. And here they're a really bad idea. If you have 100 instructors, you evaluate 4950 different combinations to get a unique list of 99 instructors.
- Instructor001 has 99 instructors who are paid less
- Instructor002 has 98 instructors who are paid less
- ...
- Instructor100 has 00 instructors who are paid less
- Totalling 4950 combinations
If you have 1000 instructors you evaluate 499500 combinations to get a unique list of 999 instructors.
A better idea would be...
SELECT
i.Name
FROM
instructor i
WHERE
i.salary > (SELECT MIN(salary) FROM instructor)
Or...
SELECT
i.Name
FROM
instructor i
WHERE
i.Name <> (SELECT Name FROM instructor ORDER BY Salary ASC LIMIT 1)
Or...
SELECT
i.*
FROM
instructor i
EXCEPT
SELECT
i.*
FROM
instructor i
ORDER BY
Salary ASC
LIMIT 1
So, you're right, it's not necessary (or even a good idea) to do it that way.
Related Topics
Create Postgresql Role (User) If It Doesn't Exist
Convert a String to Int Using SQL Query
Update Multiple Columns in SQL
How to Insert Table Values from One Database to Another Database
What Is the Most Appropriate Data Type for Storing an Ip Address in SQL Server
Check If Null Exists in Postgres Array
What Is the Purpose for Using Option(Maxdop 1) in SQL Server
When Would You Use a Table-Valued Function
Prevent Duplicate Values in Left Join
Designing SQL Database to Represent Oo Class Hierarchy
SQL Join on Multiple Columns in Same Tables
Mysql: Count Records from One Table and Then Update Another
Why Doesn't Oracle SQL Allow Us to Use Column Aliases in Group by Clauses
How to Backup and Restore a Database as a Copy on the Same Server