Search code examples
sqloracle-databasesql-merge

convert query from merge to select count in Oracle


I have merge query with below syntax:

MERGE INTO target_table 
USING source_table 
ON search_condition
    WHEN NOT MATCHED THEN
        INSERT (col1,col2,...)
        values(value1,value2,...)
        WHERE <insert_condition>;

But i want change this query to see how many rows would insert and use the below query but i am not sure this is correct query:

select count(*) from target_table where not exists (select 1 from source_table where search_condition)

Solution

  • The MERGE statement inserts rows from source_table into target_table. So it is data from the source_table that doesn't yet exist in the target_table you want to count.

    select count(*)
    from source_table 
    where <insert_condition>
    and not exists
    (
      select *
      from target_table
      where <search_condition>
    );