PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

SELEZIONARE o INSERIRE una riga in un comando

Hai provato a unirlo?

Modifica:richiede Postgres 9.1:

create table mytable (id serial primary key, other_key varchar not null unique);

WITH new_row AS (
INSERT INTO mytable (other_key)
SELECT 'SOMETHING'
WHERE NOT EXISTS (SELECT * FROM mytable WHERE other_key = 'SOMETHING')
RETURNING *
)
SELECT * FROM new_row
UNION
SELECT * FROM mytable WHERE other_key = 'SOMETHING';

risulta in:

 id | other_key 
----+-----------
  1 | SOMETHING
(1 row)