Re: fast insert-if-key-not-already-there

From: "Richard Broersma" <richard(dot)broersma(at)gmail(dot)com>
To: "Patrick Scharrenberg" <pittipatti(at)web(dot)de>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: fast insert-if-key-not-already-there
Date: 2008-08-04 15:59:58
Message-ID: 396486430808040859p1b8e784cl625a4e92fc488ff7@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, Aug 4, 2008 at 8:51 AM, Patrick Scharrenberg <pittipatti(at)web(dot)de> wrote:

> My current approach is to query for the key (ip-address), and if the
> result is null I do the insert.
> For every IP-Address I need the ip_addr_id from the same table.

> INSERT INTO ip_addresses ( ip_addr ) VALUES( v_ip_addr ) RETURNING
> ip_addr_id INTO v_ip_id ;

another option is to only insert if the addresses if they do not yet
exist. You might have to rethink some of your other logic however:

INSERT INTO Ip_addresses ( ip_addr )
SELECT ip_addr
FROM ( VALUES ( v_ip_addr )) AS A( ip_addr )
LEFT JOIN Ip_addresses AS B
ON A.ip_addr = B.ip_addr
WHERE B.ip_addr IS NULL;

--
Regards,
Richard Broersma Jr.

Visit the Los Angeles PostgreSQL Users Group (LAPUG)
http://pugs.postgresql.org/lapug

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Jorge Medina 2008-08-05 15:14:18 more than 1000 connections
Previous Message Thomas Kellerer 2008-08-04 15:55:32 Re: fast insert-if-key-not-already-there