Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: Check if rows exist in other table

I've got a query joining several tables and returning quite a few columns.

An indexed column of another table references the PK of one of these joined tables. Now I would like to add another column to the query that states if at least one row with that ID exists in the new table.

So if I have one of the old tables

ID
 1
 2
 3

and the new table

REF_ID
1
1
1
3

then I'd like to get

ID   REF_EXISTS
 1            1
 2            0
 3            1

I can think of several ways to do that, but what is the most elegant/efficient one?


EDIT I tested the performance of the queries provided with 50.000 records in the old table, every other record matched by two rows in the new table, so half of the records have REF_EXISTS=1.

I'm adding average results as comments to the answers in case anyone is interested. Thanks everyone!

like image 465
Peter Lang Avatar asked Dec 16 '09 19:12

Peter Lang


People also ask

How do you check if the row exists in a table Oracle?

Type a short Oracle program, using the following code as a guide: DECLARE record_exists INTEGER; BEGIN SELECT COUNT(*) INTO record_exists FROM your_table WHERE search_field = 'search value' AND ROWNUM = 1; IF record_exists = 1 THEN DBMS_OUTPUT. put_line('Record Exists') ELSE DBMS_OUTPUT.

How do you check if a row exists in a table?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do you select all records from one table that do not exist in another table Oracle?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


2 Answers

Another option:

select O.ID
    , case when N.ref_id is not null then 1 else 0 end as ref_exists
from old_table o
left outer join (select distinct ref_id from new_table) N
   on O.id = N.ref_id
like image 164
Shannon Severance Avatar answered Oct 14 '22 03:10

Shannon Severance


I would:

select distinct ID,
       case when exists (select 1 from REF_TABLE where ID_TABLE.ID = REF_TABLE.REF_ID)
    then 1 else 0 end
    from ID_TABLE

Provided you have indexes on the PK and FK you will get away with a table scan and index lookups.

Regards K

like image 31
Khb Avatar answered Oct 14 '22 05:10

Khb