In SQL, given tables T
and S
that have the same schema, say,
CREATE TABLE "T" ("ID" INTEGER, "Salary" REAL);
CREATE TABLE "S" ("ID" INTEGER, "Salary" REAL);
we can union the two relations with the command
(SELECT * FROM "S") UNION (SELECT * FROM "T");
but the following command gives an error:
"S" UNION "T";
Error message in SQLite: near "UNION": syntax error
Error message in SQL Server: Incorrect syntax near the keyword 'UNION'.
Why can’t we use the latter command? Algebraically speaking, the union operator is defined to take two table operands and output another table as a result. So "S" UNION "T"
must work. This is analogous to how the selection and projection operators take a table operand, and output another table.
I understand that while the output of a SELECT
statement should algebraically be a table, it is in practice a “virtual table”. My understanding from C. J. Date’s An Introduction to Database Systems is that tables like S
and T
above are “base relvars/relations” whereas virtual tables like (SELECT * FROM "S")
and (SELECT * FROM "T")
are “derived relations”; and that both (base and derived) are considered tables. So why don’t they act the same when UNION
operates on them?
Interestingly, if we give the names view1
and view2
to the outputs of the SELECT
(SELECT * FROM "S")
and (SELECT * FROM "T")
respectively to create views,
CREATE VIEW "view1" AS SELECT * FROM "S";
CREATE VIEW "view2" AS SELECT * FROM "T";
we again get the above-mentioned errors if we give the views to UNION
as operands:
"view1" UNION "view2";
Error message in SQLite: near "UNION": syntax error
Error message in SQL Server: Incorrect syntax near 'view1'.
What’s happening? Why must the operands necessarily be SELECT
statements?