INSERT only unique records

From: Mark Felegyhazi <m_felegyhazi(at)yahoo(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: INSERT only unique records
Date: 2009-07-10 20:32:40
Message-ID: 1247.13639.qm@web54409.mail.yahoo.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


Hey guys,

I'm learning Postgresql and trying to inserts only new entries in a table and skips duplicates. I know this is a recurrent question, but maybe you could point out what I'm doing wrong in this specific case.

Initially, I have two tables: from_t and to_t (empty);

mydb=> select * from from_t;
num
-----
1
1
2
3
4
5
5
5
(8 rows)

The basic inserts I'm trying to make is the following:

mydb=> insert into to_t (select num from from_t where num<4);
AND
mydb=> insert into to_t (select num from from_t where num>2);

To avoid duplicates, I had the following ideas:

1. put a unique constraint on num in to_t
-> problem: the first violation breaks the subquery and the remaining records are never inserted - I don't know how to catch the error in subqueries

2. create the following insert rule:

create or replace rule to_t_insert as on insert to to_t where exists (select num from to_t where num=NEW.num) do instead nothing;
-> problem below - apparently, the rule checks for unique records, but the check is not iterated as new entries are inserted. 3 is not inserted twice, but 1 and 5 are.

mydb=> insert into to_t (select num from from_t where num<4);
INSERT 0 4
mydb=> select * from to_t;
num
-----
1
1
2
3
(4 rows)
mydb=> insert into to_t (select num from from_t where num>2);
INSERT 0 4
mydb=> select * from to_t;
num
-----
1
1
2
3
4
5
5
5
(8 rows)

Could you point me to a solution?

Thanks,
Mark

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Scot Kreienkamp 2009-07-10 20:38:46 Re: Idle in transaction help
Previous Message James B. Byrne 2009-07-10 20:31:42 [Fwd: Re: How to trace client sql requests?]