I need to create an INSERT INTO ... WHERE NOT EXISTS ...
SQL query that works on both Postgres and Oracle. Unfortunately, since oracle does not support SELECT
statements without FROM
I’m struggling to get this query to work.
I found this answer ( https://stackoverflow.com/a/16639922 ) and implemented my query very similarly:
insert into TABLE (col1, col2)
select 'A', 100
from dual
where not exists(select *
from TABLE
where (col1='A' and col2=100));
The one part that causes me issues here is the from dual
statement. In postgres I would just omit this part and the query works. But for oracle it is necessary to add a FROM
statement so I have to select from some table. Unfortunately postgres does not have a DUAL
table. Is there any dummy table that I can select from in both cases, or is there an entirely different way to write that query? My initial approach with postgres’ ON CONFLICT DO NOTHING
obviously also wasn’t viable for oracle.
4
Answers
this might help
Equivalence of from dual in PostgreSQL
seems you don’t need a dual table in Postgresql
On Postgres you don’t need any actual table or
FROM
clause:Note that in Postgres, we also don’t even need to select anything in the exists clause.
A general version which should work on both Oracle and Postgres might just put the data into a CTE and then select from that.
Have a derived table that will always return exactly one row. (A dual similar solution.)
Demo: https://dbfiddle.uk/m2R2fDOZ
You can create a view in PostgreSQL to mimic the
DUAL
table:Then, in both Oracle and PostgreSQL, you can use:
or, probably more efficiently:
Note: From Oracle 23, the
FROM
clause of aSELECT
statement is optional and you can just useSELECT 'A' AS col1, 100 AS col2
and could use identical queries in PostgreSQL and Oracle without the need for aDUAL
table.PostgreSQL fiddle Oracle fiddle