Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite natural join broken?

I am just getting to know NATURAL JOIN and SQLite is not behaning as I expect.

SELECT * FROM r1 NATURAL JOIN (r2 NATURAL JOIN r3);

and

SELECT * FROM (r1 NATURAL JOIN r2) NATURAL JOIN r3;

produce the same (correct) results.

However if I omit the parentheses as in:

SELECT * FROM r1 NATURAL JOIN r2 NATURAL JOIN r3;

I see that r1 and r2 are joined correctly however r3 is not joined to the result at all, instead the cartesian product of r1 NATURAL JOIN r2, r3 is formed.

Is there an issue with the attribute names of the first join result, or am I misinterpreting SQL?

like image 606
Panayiotis Karabassis Avatar asked Nov 24 '12 20:11

Panayiotis Karabassis


People also ask

What is natural join in SQLite?

The natural join automatically detects the common column names in participating tables and links them together. The SQLite NATURAL JOIN is structured in such a way that, columns with the same name of associate tables will appear once only. Natural Join: Guidelines - The associated tables have one or more pairs of identically named columns.

What is the SQLite left join syntax?

SQLite LEFT JOIN syntax is the same as INNER JOIN; you write the LEFT JOIN between the two tables, and then the join condition comes after the ON clause. The first table after the from clause is the left table. Whereas the second table specified after the natural LEFT JOIN is the right table.

What are the different types of outer joins in SQLite?

The SQL standard defines three types of OUTER JOINs: LEFT, RIGHT, and FULL but SQLite supports only the natural LEFT OUTER JOIN.

How to combine records from two tables in SQLite?

SQLite Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. Before we proceed, let's consider two tables COMPANY and DEPARTMENT.


1 Answers

I don't use that database myself, but according to this documentation, all joins in SQLite are based on the cartesian product of the left and right tables.

NATURAL joins use common column names as "keys" to combined two tables. Using parentheses forces a "derived table" to be built before the outer join is processed. Without parentheses, it does not "see" the common column names, so the second NATURAL keyword is ignored.

A little advice: it's good to understand the mechanics of how a NATURAL JOIN works in case you ever see it in code, but do not use it yourself. It is a "dangerous" construct with little value. Just my opinion.

like image 138
BellevueBob Avatar answered Sep 23 '22 06:09

BellevueBob