Re: Insert Data Into Tables Linked by Foreign Key

From: Alban Hertroys <dalroi(at)solfertje(dot)student(dot)utwente(dot)nl>
To: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Insert Data Into Tables Linked by Foreign Key
Date: 2010-01-04 13:03:58
Message-ID: 7227984E-253C-44E5-9565-7AD63ED1862A@solfertje.student.utwente.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 4 Jan 2010, at 13:15, A. Kretschmer wrote:

> In response to Alban Hertroys :
>> On 4 Jan 2010, at 9:53, Yan Cheng Cheok wrote:
>>
>>> For example, "John" place "1.34" priced order.
>>>
>>> (1) Get Customer_ID from Customer table, where name is "John"
>>> (2) If there are no Customer_ID returned (There is no John), insert "John"
>>> (3) Get Customer_ID from Customer table, where name is "John"
>>> (4) Insert "Customer_ID" and "1.34" into Order table.
>>>
>>> There are 4 SQL communication with database involved for this simple operation!!!
>>>
>>> Is there any better way, which can be achievable using 1 SQL statement?
>>
>>
>> You don't need the 3rd statement if you use INSERT .. RETURNING at step 2.
>>
>> The one way you could achieve this by calling only one statement that
>> I can think of is to wrap this in a stored procedure. Plain SQL
>> doesn't provide any means to do what you want.
>
> Writeable CTE can do that ;-)
> http://wiki.postgresql.org/images/c/c0/PGDay2009-EN-Writeable_CTEs_The_Next_Big_Thing.pdf

That looked interesting enough that I gave it a try, even though AFAIK we don't have writable CTE's yet (8.5 maybe?).
Below is my first attempt at any CTE at all. Is there anything that can be improved here? It doesn't look all that optimal...

WITH t1 AS (
SELECT * FROM Customer WHERE name = 'John'
UNION
INSERT INTO Customer (name)
SELECT 'John' FROM generate_series(1,1) AS C1
WHERE NOT EXISTS (
SELECT 1 FROM Customer AS C2 WHERE name = 'John'
)
RETURNING *
)
INSERT INTO Order (t1.id, 1.34);

Alban Hertroys

--
If you can't see the forest for the trees,
cut the trees and you'll see there is no forest.

!DSPAM:737,4b41e73f9952042619622!

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message A. Kretschmer 2010-01-04 13:23:35 Re: Insert Data Into Tables Linked by Foreign Key
Previous Message Sam Mason 2010-01-04 12:59:27 Re: Insert Data Into Tables Linked by Foreign Key