Question on UNION - Mailing list pgsql-sql

From
Subject Question on UNION
Date
Msg-id 21062336.1148324291670.JavaMail.root@eastrmwml05.mgt.cox.net
Whole thread Raw
Responses Re: Question on UNION
List pgsql-sql
Everyone,

I ran into something I wasn't expecting while developing a new application.  I have two similar tables that are
occasionallyunioned pulling only about 3 fields from each.  During my testing phase I noticed that the union statement
wasreturning what appeared to be a distinct list rather than a pure union such as is illustrated below:
 

create table t1 (     f1 serial primary key,     f2 text,     f3 text,     f4 integer
);

create table t2 (     f1 serial primary key,     f2 text,     f3 text,     f4 integer
);

insert into t1 (f2, f3, f4) values ('A', 'a', 1);
insert into t1 (f2, f3, f4) values ('A', 'a', 1);
insert into t1 (f2, f3, f4) values ('B', 'b', 2);
insert into t1 (f2, f3, f4) values ('B', 'b', 2);

insert into t2 (f2, f3, f4) values ('C', 'c', 3);
insert into t2 (f2, f3, f4) values ('C', 'c', 3);
insert into t2 (f2, f3, f4) values ('D', 'd', 4);
insert into t2 (f2, f3, f4) values ('D', 'd', 4);

temp=# select * from t1;f1 | f2 | f3 | f4
----+----+----+---- 1 | A  | a  |  1 2 | A  | a  |  1 3 | B  | b  |  2 4 | B  | b  |  2
(4 rows)

temp=# select * from t2;f1 | f2 | f3 | f4
----+----+----+---- 1 | C  | c  |  3 2 | C  | c  |  3 3 | D  | d  |  4 4 | D  | d  |  4
(4 rows)

When I leave out f1 I receive a distinct list:

temp=# (select f2, f3, f4 from t1) UNION (select f2, f3, f4 from t2) order by f4;f2 | f3 | f4
----+----+----A  | a  |  1B  | b  |  2C  | c  |  3D  | d  |  4
(4 rows)

When the key field is included I get a full list:

temp=# (select * from t1) UNION (select * from t2) order by f4;f1 | f2 | f3 | f4
----+----+----+---- 1 | A  | a  |  1 2 | A  | a  |  1 3 | B  | b  |  2 4 | B  | b  |  2 1 | C  | c  |  3 2 | C  | c  |
33 | D  | d  |  4 4 | D  | d  |  4
 
(8 rows)

Can anyone explain the underlying principle(s) in the UNION that would cause this?

Thanks in advance
Mark



pgsql-sql by date:

Previous
From: Manlio Perillo
Date:
Subject: Re: Does PG have a database
Next
From: Markus Schaber
Date:
Subject: Re: Question on UNION