HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Crossjoin-like operation except A x {} = A?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
crossjoinexceptlikeoperation

Problem

Is there a way to implement operation (let's annotate it ∘) that behaves just like regular cross join except for empty sets it returns non empty side.

∘ - new operation
x - cross join
{} - empty result set

A ∘ B  = A x B
A ∘ {} = A
{} ∘ B = B
{} ∘ {} = {}


Columns of A and B differ and are non empty.

Solution

If by empty set, you mean "that has zero column", then CROSS JOIN with an empty SELECT already does that:

postgres=# \echo :SERVER_VERSION_NAME 
10.3 (Debian 10.3-1.pgdg90+1)

postgres=# select * from (select 'a') A cross join (select ) B;
 ?column? 
----------
 a
(1 row)


Note that the empty select (no column) is a relatively recent addition in PostgreSQL.On older versions, the above query will cause a syntax error.

Another interpretation of the question could be that in A ∘ {}, A is a table-type with certain columns, and {} is a arbitrarily different table-type with different columns but that happens to contain 0 row.
In that case there will be no operation in SQL that satisfies the question, because the result type of a query cannot depend on the contents of relations. It must always depend only on the definitions of the relations involved, so that it can be determined without actually running the query.

Code Snippets

postgres=# \echo :SERVER_VERSION_NAME 
10.3 (Debian 10.3-1.pgdg90+1)

postgres=# select * from (select 'a') A cross join (select ) B;
 ?column? 
----------
 a
(1 row)

Context

StackExchange Database Administrators Q#205838, answer score: 2

Revisions (0)

No revisions yet.