From: Paul Jungwirth <pj@illuminatedcomputing.com>
To: pgsql-general@lists.postgresql.org
Subject: Re: Conditional INSERT
Date: Fri, 15 Mar 2019 11:26:24 -0700
Message-ID: <7767098b-339b-d097-8403-2263e07164d2@illuminatedcomputing.com> (raw)
In-Reply-To: <68951fae-3281-c9ad-09b7-205e0bb1c5ae@unix-solution.de>
References: <68951fae-3281-c9ad-09b7-205e0bb1c5ae@unix-solution.de>
On 3/15/19 10:55 AM, basti wrote:
> I want to insert data into table only if condition is true.
> For example:
>
> INSERT into mytable (domainid, hostname, txtdata)
> VALUES (100,'_acme.challenge.example', 'somedata');
>
> The insert should only be done if Hostname like %_acme.challenge%.
I would use `INSERT INTO ... SELECT` for this, instead of `INSERT INTO
... VALUES`. For example:
INSERT INTO mytable (domainid, hostname, txtdata)
SELECT 100, '_acme.challenge.example', 'somedata'
WHERE '_acme.challenge.example' LIKE '%_acme.challenge%'
;
(Presumably in the real code the hostname is parameterized so this isn't
quite as pointless as it looks. :-)
If you are inserting a lot of rows at once you could also SELECT from a
VALUES list:
INSERT INTO mytable (domainid, hostname, txtdata)
SELECT d, h, t
FROM (VALUES
(100, '_acme.challenge.example', 'somedata'),
(200, 'bar.example.com', 'somedata'),
(300, 'foo.example.com', 'somedata'),
(400, '_acme.challenge.example', 'somedata')
) x(d, h, t)
WHERE h LIKE '%_acme.challenge%'
;
I hope that helps!
Yours,
--
Paul ~{:-)
pj@illuminatedcomputing.com
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: pj@illuminatedcomputing.com
Subject: Re: Conditional INSERT
In-Reply-To: <7767098b-339b-d097-8403-2263e07164d2@illuminatedcomputing.com>
References: <68951fae-3281-c9ad-09b7-205e0bb1c5ae@unix-solution.de> <7767098b-339b-d097-8403-2263e07164d2@illuminatedcomputing.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox