From: | "Guy Rouillier" <guyr(at)masergy(dot)com> |
---|---|
To: | <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: sql question; checks if data already exists before inserted |
Date: | 2006-06-22 19:51:06 |
Message-ID: | D4D1632DC736E74AB95FE78CD609007901272D@mtxexch01.add0.masergy.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
nuno wrote:
> hi, there. i'm trying to write a SQL statement which does the
> following things.
>
> 1. checks if data already exists in the database
> 2. if not, insert data into database otherwise skip.
>
> for example, i'd like to insert a student called 'Michael Jordan'
> whose ID is 'JORDANMICHAEL' only if the id, 'JORDANMICHAEL' does not
> already exist in the database. anyway, my query looks like...
>
> insert into student (studentid, fname, lname)
> select 'JORDANMICHAEL', 'Michale', 'Jordan' from student where
> studentid not in (select studentid from student);
>
> however, this does not seem to work. it does not insert data even if
> it does not exist in the database. hmm!
>
> any clue?
Your query is not doing what you think it's doing. Try running just the
select portion of the query you provide above (minus the "insert into"
part.) You are selecting from student where studentid not in (select
studentid from student). That will always return the empty set, since
you are looking at the same column and the same table in both the inner
and outer selects.
What you want to do is create a primary key on your student table. Then
try to do the insert, catching the "not unique" error return.
--
Guy Rouillier
From | Date | Subject | |
---|---|---|---|
Next Message | Alvaro Herrera | 2006-06-22 19:56:22 | Re: auto-vacuum & Negative "anl" Values |
Previous Message | Jim Nasby | 2006-06-22 19:46:10 | Re: How to build with bigger WAL segment file? |