Re: [GENERAL] Select from tableA - if not exists then tableB - Mailing list pgsql-general

From David Rowley
Subject Re: [GENERAL] Select from tableA - if not exists then tableB
Date
Msg-id CAKJS1f9ZrSc5soC4nZphommYd0VpG5YoZ3eXU_oGAPU+x=v27Q@mail.gmail.com
Whole thread Raw
In response to [GENERAL] Select from tableA - if not exists then tableB  (Patrick B <patrickbakerbr@gmail.com>)
List pgsql-general
On 9 May 2017 at 09:56, Patrick B <patrickbakerbr@gmail.com> wrote:
> Hi guys,
>
> I have two tables that supports the same data, but different table DDL (We
> are migrating all the data from one to another).
>
> What I need is basically:
>
> 1. Query looks for the data on table A,
> 2. if it doesn't find it on table A, go look for it on table B
>
> Now, how could I do that in a Select? Can you please provide some examples?
>
>
> I'm using PostgreSQL 9.1.

You could exploit DISTINCT ON for this.

Something like:

select distinct on (id) id,value from (select *,'a' tablename from a
where id=1 union all select *,'b' tablename from b where id=1) ab
order by id,tablename;

Assuming that id is what you want to be unique.


--
 David Rowley                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


pgsql-general by date:

Previous
From: Adrian Klaver
Date:
Subject: Re: [GENERAL] Select from tableA - if not exists then tableB
Next
From: Brian Dunavant
Date:
Subject: Re: [GENERAL] Select from tableA - if not exists then tableB